context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Xml;
using log4net;
using Nini.Config;
using OpenSim.Framework;
namespace OpenSim
{
/// <summary>
/// Loads the Configuration files into nIni
/// </summary>
public class ConfigurationLoader
{
/// <summary>
/// Various Config settings the region needs to start
/// Physics Engine, Mesh Engine, GridMode, PhysicsPrim allowed, Neighbor,
/// StorageDLL, Storage Connection String, Estate connection String, Client Stack
/// Standalone settings.
/// </summary>
protected ConfigSettings m_configSettings;
/// <summary>
/// A source of Configuration data
/// </summary>
protected OpenSimConfigSource m_config;
/// <summary>
/// Grid Service Information. This refers to classes and addresses of the grid service
/// </summary>
protected NetworkServersInfo m_networkServersInfo;
/// <summary>
/// Console logger
/// </summary>
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
public ConfigurationLoader()
{
}
/// <summary>
/// Loads the region configuration
/// </summary>
/// <param name="argvSource">Parameters passed into the process when started</param>
/// <param name="configSettings"></param>
/// <param name="networkInfo"></param>
/// <returns>A configuration that gets passed to modules</returns>
public OpenSimConfigSource LoadConfigSettings(
IConfigSource argvSource, out ConfigSettings configSettings,
out NetworkServersInfo networkInfo)
{
m_configSettings = configSettings = new ConfigSettings();
m_networkServersInfo = networkInfo = new NetworkServersInfo();
bool iniFileExists = false;
IConfig startupConfig = argvSource.Configs["Startup"];
List<string> sources = new List<string>();
string masterFileName =
startupConfig.GetString("inimaster", String.Empty);
if (IsUri(masterFileName))
{
if (!sources.Contains(masterFileName))
sources.Add(masterFileName);
}
else
{
string masterFilePath = Path.GetFullPath(
Path.Combine(Util.configDir(), masterFileName));
if (masterFileName != String.Empty &&
File.Exists(masterFilePath) &&
(!sources.Contains(masterFilePath)))
sources.Add(masterFilePath);
}
string iniFileName =
startupConfig.GetString("inifile", "OpenSim.ini");
if (IsUri(iniFileName))
{
if (!sources.Contains(iniFileName))
sources.Add(iniFileName);
Application.iniFilePath = iniFileName;
}
else
{
Application.iniFilePath = Path.GetFullPath(
Path.Combine(Util.configDir(), iniFileName));
if (!File.Exists(Application.iniFilePath))
{
iniFileName = "OpenSim.xml";
Application.iniFilePath = Path.GetFullPath(
Path.Combine(Util.configDir(), iniFileName));
}
if (File.Exists(Application.iniFilePath))
{
if (!sources.Contains(Application.iniFilePath))
sources.Add(Application.iniFilePath);
}
}
string iniDirName =
startupConfig.GetString("inidirectory", "config");
string iniDirPath =
Path.Combine(Util.configDir(), iniDirName);
if (Directory.Exists(iniDirPath))
{
m_log.InfoFormat("Searching folder {0} for config ini files",
iniDirPath);
string[] fileEntries = Directory.GetFiles(iniDirName);
foreach (string filePath in fileEntries)
{
if (Path.GetExtension(filePath).ToLower() == ".ini")
{
if (!sources.Contains(Path.GetFullPath(filePath)))
sources.Add(Path.GetFullPath(filePath));
}
}
}
m_config = new OpenSimConfigSource();
m_config.Source = new IniConfigSource();
m_config.Source.Merge(DefaultConfig());
m_log.Info("[CONFIG] Reading configuration settings");
if (sources.Count == 0)
{
m_log.FatalFormat("[CONFIG] Could not load any configuration");
m_log.FatalFormat("[CONFIG] Did you copy the OpenSim.ini.example file to OpenSim.ini?");
Environment.Exit(1);
}
for (int i = 0 ; i < sources.Count ; i++)
{
if (ReadConfig(sources[i]))
iniFileExists = true;
AddIncludes(sources);
}
if (!iniFileExists)
{
m_log.FatalFormat("[CONFIG] Could not load any configuration");
m_log.FatalFormat("[CONFIG] Configuration exists, but there was an error loading it!");
Environment.Exit(1);
}
// Make sure command line options take precedence
//
m_config.Source.Merge(argvSource);
ReadConfigSettings();
return m_config;
}
/// <summary>
/// Adds the included files as ini configuration files
/// </summary>
/// <param name="sources">List of URL strings or filename strings</param>
private void AddIncludes(List<string> sources)
{
//loop over config sources
foreach (IConfig config in m_config.Source.Configs)
{
// Look for Include-* in the key name
string[] keys = config.GetKeys();
foreach (string k in keys)
{
if (k.StartsWith("Include-"))
{
// read the config file to be included.
string file = config.GetString(k);
if (IsUri(file))
{
if (!sources.Contains(file))
sources.Add(file);
}
else
{
string basepath = Path.GetFullPath(Util.configDir());
string path = Path.Combine(basepath, file);
string[] paths = Util.Glob(path);
foreach (string p in paths)
{
if (!sources.Contains(p))
sources.Add(p);
}
}
}
}
}
}
/// <summary>
/// Check if we can convert the string to a URI
/// </summary>
/// <param name="file">String uri to the remote resource</param>
/// <returns>true if we can convert the string to a Uri object</returns>
bool IsUri(string file)
{
Uri configUri;
return Uri.TryCreate(file, UriKind.Absolute,
out configUri) && configUri.Scheme == Uri.UriSchemeHttp;
}
/// <summary>
/// Provide same ini loader functionality for standard ini and master ini - file system or XML over http
/// </summary>
/// <param name="iniPath">Full path to the ini</param>
/// <returns></returns>
private bool ReadConfig(string iniPath)
{
bool success = false;
if (!IsUri(iniPath))
{
m_log.InfoFormat("[CONFIG] Reading configuration file {0}",
Path.GetFullPath(iniPath));
m_config.Source.Merge(new IniConfigSource(iniPath));
success = true;
}
else
{
m_log.InfoFormat("[CONFIG] {0} is a http:// URI, fetching ...",
iniPath);
// The ini file path is a http URI
// Try to read it
//
try
{
XmlReader r = XmlReader.Create(iniPath);
XmlConfigSource cs = new XmlConfigSource(r);
m_config.Source.Merge(cs);
success = true;
}
catch (Exception e)
{
m_log.FatalFormat("[CONFIG] Exception reading config from URI {0}\n" + e.ToString(), iniPath);
Environment.Exit(1);
}
}
return success;
}
/// <summary>
/// Setup a default config values in case they aren't present in the ini file
/// </summary>
/// <returns>A Configuration source containing the default configuration</returns>
private static IConfigSource DefaultConfig()
{
IConfigSource defaultConfig = new IniConfigSource();
{
IConfig config = defaultConfig.Configs["Startup"];
if (null == config)
config = defaultConfig.AddConfig("Startup");
config.Set("region_info_source", "filesystem");
config.Set("gridmode", false);
config.Set("physics", "basicphysics");
config.Set("meshing", "ZeroMesher");
config.Set("physical_prim", true);
config.Set("see_into_this_sim_from_neighbor", true);
config.Set("serverside_object_permissions", false);
config.Set("storage_plugin", "OpenSim.Data.SQLite.dll");
config.Set("storage_connection_string", "URI=file:OpenSim.db,version=3");
config.Set("storage_prim_inventories", true);
config.Set("startup_console_commands_file", String.Empty);
config.Set("shutdown_console_commands_file", String.Empty);
config.Set("DefaultScriptEngine", "XEngine");
config.Set("clientstack_plugin", "OpenSim.Region.ClientStack.LindenUDP.dll");
// life doesn't really work without this
config.Set("EventQueue", true);
}
{
IConfig config = defaultConfig.Configs["StandAlone"];
if (null == config)
config = defaultConfig.AddConfig("StandAlone");
config.Set("accounts_authenticate", true);
config.Set("welcome_message", "Welcome to OpenSimulator");
config.Set("inventory_plugin", "OpenSim.Data.SQLite.dll");
config.Set("inventory_source", "");
config.Set("userDatabase_plugin", "OpenSim.Data.SQLite.dll");
config.Set("user_source", "");
config.Set("LibrariesXMLFile", string.Format(".{0}inventory{0}Libraries.xml", Path.DirectorySeparatorChar));
}
{
IConfig config = defaultConfig.Configs["Network"];
if (null == config)
config = defaultConfig.AddConfig("Network");
config.Set("default_location_x", 1000);
config.Set("default_location_y", 1000);
config.Set("http_listener_port", ConfigSettings.DefaultRegionHttpPort);
config.Set("remoting_listener_port", ConfigSettings.DefaultRegionRemotingPort);
config.Set("grid_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultGridServerHttpPort.ToString());
config.Set("grid_send_key", "null");
config.Set("grid_recv_key", "null");
config.Set("user_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultUserServerHttpPort.ToString());
config.Set("user_send_key", "null");
config.Set("user_recv_key", "null");
config.Set("asset_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultAssetServerHttpPort.ToString());
config.Set("inventory_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultInventoryServerHttpPort.ToString());
config.Set("secure_inventory_server", "true");
}
return defaultConfig;
}
/// <summary>
/// Read initial region settings from the ConfigSource
/// </summary>
protected virtual void ReadConfigSettings()
{
IConfig startupConfig = m_config.Source.Configs["Startup"];
if (startupConfig != null)
{
m_configSettings.Standalone = !startupConfig.GetBoolean("gridmode", false);
m_configSettings.PhysicsEngine = startupConfig.GetString("physics");
m_configSettings.MeshEngineName = startupConfig.GetString("meshing");
m_configSettings.PhysicalPrim = startupConfig.GetBoolean("physical_prim", true);
m_configSettings.See_into_region_from_neighbor = startupConfig.GetBoolean("see_into_this_sim_from_neighbor", true);
m_configSettings.StorageDll = startupConfig.GetString("storage_plugin");
if (m_configSettings.StorageDll == "OpenSim.DataStore.MonoSqlite.dll")
{
m_configSettings.StorageDll = "OpenSim.Data.SQLite.dll";
m_log.Warn("WARNING: OpenSim.DataStore.MonoSqlite.dll is deprecated. Set storage_plugin to OpenSim.Data.SQLite.dll.");
Thread.Sleep(3000);
}
m_configSettings.StorageConnectionString
= startupConfig.GetString("storage_connection_string");
m_configSettings.EstateConnectionString
= startupConfig.GetString("estate_connection_string", m_configSettings.StorageConnectionString);
m_configSettings.ClientstackDll
= startupConfig.GetString("clientstack_plugin", "OpenSim.Region.ClientStack.LindenUDP.dll");
}
IConfig standaloneConfig = m_config.Source.Configs["StandAlone"];
if (standaloneConfig != null)
{
m_configSettings.StandaloneAuthenticate = standaloneConfig.GetBoolean("accounts_authenticate", true);
m_configSettings.StandaloneWelcomeMessage = standaloneConfig.GetString("welcome_message");
m_configSettings.StandaloneInventoryPlugin = standaloneConfig.GetString("inventory_plugin");
m_configSettings.StandaloneInventorySource = standaloneConfig.GetString("inventory_source");
m_configSettings.StandaloneUserPlugin = standaloneConfig.GetString("userDatabase_plugin");
m_configSettings.StandaloneUserSource = standaloneConfig.GetString("user_source");
m_configSettings.LibrariesXMLFile = standaloneConfig.GetString("LibrariesXMLFile");
}
m_networkServersInfo.loadFromConfiguration(m_config.Source);
}
}
}
| |
//
// 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 Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Sql.LegacySdk;
using Microsoft.Azure.Management.Sql.LegacySdk.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Sql.LegacySdk
{
/// <summary>
/// Represents all the operations for import/export on Azure SQL Databases.
/// Contains operations to: Import, Export, Get Import/Export status for
/// a database.
/// </summary>
internal partial class ImportExportOperations : IServiceOperations<SqlManagementClient>, IImportExportOperations
{
/// <summary>
/// Initializes a new instance of the ImportExportOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ImportExportOperations(SqlManagementClient client)
{
this._client = client;
}
private SqlManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.SqlManagementClient.
/// </summary>
public SqlManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Exports a Azure SQL Database to bacpac. To determine the status of
/// the operation call GetImportExportOperationStatus.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the database is
/// hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database to export.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for exporting a database.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response Azure Sql Import/Export operations.
/// </returns>
public async Task<ImportExportResponse> ExportAsync(string resourceGroupName, string serverName, string databaseName, ExportRequestParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "ExportAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/databases/";
url = url + Uri.EscapeDataString(databaseName);
url = url + "/export";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
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
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject exportRequestParametersValue = new JObject();
requestDoc = exportRequestParametersValue;
if (parameters.StorageKeyType != null)
{
exportRequestParametersValue["storageKeyType"] = parameters.StorageKeyType;
}
if (parameters.StorageKey != null)
{
exportRequestParametersValue["storageKey"] = parameters.StorageKey;
}
if (parameters.StorageUri != null)
{
exportRequestParametersValue["storageUri"] = parameters.StorageUri.AbsoluteUri;
}
if (parameters.AdministratorLogin != null)
{
exportRequestParametersValue["administratorLogin"] = parameters.AdministratorLogin;
}
if (parameters.AdministratorLoginPassword != null)
{
exportRequestParametersValue["administratorLoginPassword"] = parameters.AdministratorLoginPassword;
}
if (parameters.AuthenticationType != null)
{
exportRequestParametersValue["authenticationType"] = parameters.AuthenticationType;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
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.Accepted)
{
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
ImportExportResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ImportExportResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ErrorResponse errorInstance = new ErrorResponse();
result.Error = errorInstance;
JToken codeValue = responseDoc["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
errorInstance.Code = codeInstance;
}
JToken messageValue = responseDoc["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
errorInstance.Message = messageInstance;
}
JToken targetValue = responseDoc["target"];
if (targetValue != null && targetValue.Type != JTokenType.Null)
{
string targetInstance = ((string)targetValue);
errorInstance.Target = targetInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Location"))
{
result.OperationStatusLink = httpResponse.Headers.GetValues("Location").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Retry-After"))
{
result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture);
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.Accepted)
{
result.Status = OperationStatus.InProgress;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets the status of an Azure Sql Database import/export operation.
/// </summary>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for Azure Sql Import/Export Status operation.
/// </returns>
public async Task<ImportExportOperationStatusResponse> GetImportExportOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken)
{
// Validate
if (operationStatusLink == null)
{
throw new ArgumentNullException("operationStatusLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("operationStatusLink", operationStatusLink);
TracingAdapter.Enter(invocationId, this, "GetImportExportOperationStatusAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + operationStatusLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// 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 && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted)
{
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
ImportExportOperationStatusResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created || statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ImportExportOperationStatusResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
result.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
result.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
result.OperationResultType = typeInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ImportExportOperationStatusResponseProperties propertiesInstance = new ImportExportOperationStatusResponseProperties();
result.Properties = propertiesInstance;
JToken requestTypeValue = propertiesValue["requestType"];
if (requestTypeValue != null && requestTypeValue.Type != JTokenType.Null)
{
string requestTypeInstance = ((string)requestTypeValue);
propertiesInstance.RequestType = requestTypeInstance;
}
JToken serverNameValue = propertiesValue["serverName"];
if (serverNameValue != null && serverNameValue.Type != JTokenType.Null)
{
string serverNameInstance = ((string)serverNameValue);
propertiesInstance.ServerName = serverNameInstance;
}
JToken databaseNameValue = propertiesValue["databaseName"];
if (databaseNameValue != null && databaseNameValue.Type != JTokenType.Null)
{
string databaseNameInstance = ((string)databaseNameValue);
propertiesInstance.DatabaseName = databaseNameInstance;
}
JToken statusValue = propertiesValue["status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
string statusInstance = ((string)statusValue);
propertiesInstance.StatusMessage = statusInstance;
}
JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
string lastModifiedTimeInstance = ((string)lastModifiedTimeValue);
propertiesInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken queuedTimeValue = propertiesValue["queuedTime"];
if (queuedTimeValue != null && queuedTimeValue.Type != JTokenType.Null)
{
string queuedTimeInstance = ((string)queuedTimeValue);
propertiesInstance.QueuedTime = queuedTimeInstance;
}
JToken blobUriValue = propertiesValue["blobUri"];
if (blobUriValue != null && blobUriValue.Type != JTokenType.Null)
{
string blobUriInstance = ((string)blobUriValue);
propertiesInstance.BlobUri = blobUriInstance;
}
JToken errorMessageValue = propertiesValue["errorMessage"];
if (errorMessageValue != null && errorMessageValue.Type != JTokenType.Null)
{
string errorMessageInstance = ((string)errorMessageValue);
propertiesInstance.ErrorMessage = errorMessageInstance;
}
ErrorResponse errorInstance = new ErrorResponse();
result.Error = errorInstance;
JToken codeValue = propertiesValue["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
errorInstance.Code = codeInstance;
}
JToken messageValue = propertiesValue["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
errorInstance.Message = messageInstance;
}
JToken targetValue = propertiesValue["target"];
if (targetValue != null && targetValue.Type != JTokenType.Null)
{
string targetInstance = ((string)targetValue);
errorInstance.Target = targetInstance;
}
}
JToken requestTypeValue2 = responseDoc["requestType"];
if (requestTypeValue2 != null && requestTypeValue2.Type != JTokenType.Null)
{
string requestTypeInstance2 = ((string)requestTypeValue2);
result.RequestType = requestTypeInstance2;
}
JToken serverNameValue2 = responseDoc["serverName"];
if (serverNameValue2 != null && serverNameValue2.Type != JTokenType.Null)
{
string serverNameInstance2 = ((string)serverNameValue2);
result.ServerName = serverNameInstance2;
}
JToken databaseNameValue2 = responseDoc["databaseName"];
if (databaseNameValue2 != null && databaseNameValue2.Type != JTokenType.Null)
{
string databaseNameInstance2 = ((string)databaseNameValue2);
result.DatabaseName = databaseNameInstance2;
}
JToken statusValue2 = responseDoc["status"];
if (statusValue2 != null && statusValue2.Type != JTokenType.Null)
{
string statusInstance2 = ((string)statusValue2);
result.StatusMessage = statusInstance2;
}
JToken lastModifiedTimeValue2 = responseDoc["lastModifiedTime"];
if (lastModifiedTimeValue2 != null && lastModifiedTimeValue2.Type != JTokenType.Null)
{
string lastModifiedTimeInstance2 = ((string)lastModifiedTimeValue2);
result.LastModifiedTime = lastModifiedTimeInstance2;
}
JToken queuedTimeValue2 = responseDoc["queuedTime"];
if (queuedTimeValue2 != null && queuedTimeValue2.Type != JTokenType.Null)
{
string queuedTimeInstance2 = ((string)queuedTimeValue2);
result.QueuedTime = queuedTimeInstance2;
}
JToken blobUriValue2 = responseDoc["blobUri"];
if (blobUriValue2 != null && blobUriValue2.Type != JTokenType.Null)
{
string blobUriInstance2 = ((string)blobUriValue2);
result.BlobUri = blobUriInstance2;
}
JToken errorMessageValue2 = responseDoc["errorMessage"];
if (errorMessageValue2 != null && errorMessageValue2.Type != JTokenType.Null)
{
string errorMessageInstance2 = ((string)errorMessageValue2);
result.ErrorMessage = errorMessageInstance2;
}
ErrorResponse errorInstance2 = new ErrorResponse();
result.Error = errorInstance2;
JToken codeValue2 = responseDoc["code"];
if (codeValue2 != null && codeValue2.Type != JTokenType.Null)
{
string codeInstance2 = ((string)codeValue2);
errorInstance2.Code = codeInstance2;
}
JToken messageValue2 = responseDoc["message"];
if (messageValue2 != null && messageValue2.Type != JTokenType.Null)
{
string messageInstance2 = ((string)messageValue2);
errorInstance2.Message = messageInstance2;
}
JToken targetValue2 = responseDoc["target"];
if (targetValue2 != null && targetValue2.Type != JTokenType.Null)
{
string targetInstance2 = ((string)targetValue2);
errorInstance2.Target = targetInstance2;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.Accepted)
{
result.Status = OperationStatus.InProgress;
}
if (statusCode == HttpStatusCode.Created)
{
result.Status = OperationStatus.Succeeded;
}
if (statusCode == HttpStatusCode.OK)
{
result.Status = OperationStatus.Succeeded;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Imports a bacpac to Azure SQL Database. To determine the status of
/// the operation call GetImportExportOperationStatus.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the database is
/// hosted.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for importing to a database.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response Azure Sql Import/Export operations.
/// </returns>
public async Task<ImportExportResponse> ImportAsync(string resourceGroupName, string serverName, ImportRequestParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "ImportAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/import";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
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
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject importRequestParametersValue = new JObject();
requestDoc = importRequestParametersValue;
if (parameters.DatabaseName != null)
{
importRequestParametersValue["databaseName"] = parameters.DatabaseName;
}
if (parameters.Edition != null)
{
importRequestParametersValue["edition"] = parameters.Edition;
}
if (parameters.ServiceObjectiveName != null)
{
importRequestParametersValue["serviceObjectiveName"] = parameters.ServiceObjectiveName;
}
importRequestParametersValue["maxSizeBytes"] = parameters.DatabaseMaxSize.ToString();
if (parameters.StorageKeyType != null)
{
importRequestParametersValue["storageKeyType"] = parameters.StorageKeyType;
}
if (parameters.StorageKey != null)
{
importRequestParametersValue["storageKey"] = parameters.StorageKey;
}
if (parameters.StorageUri != null)
{
importRequestParametersValue["storageUri"] = parameters.StorageUri.AbsoluteUri;
}
if (parameters.AdministratorLogin != null)
{
importRequestParametersValue["administratorLogin"] = parameters.AdministratorLogin;
}
if (parameters.AdministratorLoginPassword != null)
{
importRequestParametersValue["administratorLoginPassword"] = parameters.AdministratorLoginPassword;
}
if (parameters.AuthenticationType != null)
{
importRequestParametersValue["authenticationType"] = parameters.AuthenticationType;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
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.Accepted)
{
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
ImportExportResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ImportExportResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ErrorResponse errorInstance = new ErrorResponse();
result.Error = errorInstance;
JToken codeValue = responseDoc["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
errorInstance.Code = codeInstance;
}
JToken messageValue = responseDoc["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
errorInstance.Message = messageInstance;
}
JToken targetValue = responseDoc["target"];
if (targetValue != null && targetValue.Type != JTokenType.Null)
{
string targetInstance = ((string)targetValue);
errorInstance.Target = targetInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Location"))
{
result.OperationStatusLink = httpResponse.Headers.GetValues("Location").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Retry-After"))
{
result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture);
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.Accepted)
{
result.Status = OperationStatus.InProgress;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Imports a bacpac to an empty Azure SQL Database. To determine the
/// status of the operation call GetImportExportOperationStatus.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the database is
/// hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database to import to.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for importing to a database.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response Azure Sql Import/Export operations.
/// </returns>
public async Task<ImportExportResponse> ImportToExistingDatabaseAsync(string resourceGroupName, string serverName, string databaseName, ImportExtensionRequestParameteres parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "ImportToExistingDatabaseAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/databases/";
url = url + Uri.EscapeDataString(databaseName);
url = url + "/extensions/import";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
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.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject importExtensionRequestParameteresValue = new JObject();
requestDoc = importExtensionRequestParameteresValue;
if (parameters.ExtensionName != null)
{
importExtensionRequestParameteresValue["name"] = parameters.ExtensionName;
}
if (parameters.ExtensionType != null)
{
importExtensionRequestParameteresValue["type"] = parameters.ExtensionType;
}
JObject propertiesValue = new JObject();
importExtensionRequestParameteresValue["properties"] = propertiesValue;
if (parameters.Properties.OperrationMode != null)
{
propertiesValue["operationMode"] = parameters.Properties.OperrationMode;
}
if (parameters.Properties.StorageKeyType != null)
{
propertiesValue["storageKeyType"] = parameters.Properties.StorageKeyType;
}
if (parameters.Properties.StorageKey != null)
{
propertiesValue["storageKey"] = parameters.Properties.StorageKey;
}
if (parameters.Properties.StorageUri != null)
{
propertiesValue["storageUri"] = parameters.Properties.StorageUri.AbsoluteUri;
}
if (parameters.Properties.AdministratorLogin != null)
{
propertiesValue["administratorLogin"] = parameters.Properties.AdministratorLogin;
}
if (parameters.Properties.AdministratorLoginPassword != null)
{
propertiesValue["administratorLoginPassword"] = parameters.Properties.AdministratorLoginPassword;
}
if (parameters.Properties.AuthenticationType != null)
{
propertiesValue["authenticationType"] = parameters.Properties.AuthenticationType;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
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.Accepted)
{
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
ImportExportResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ImportExportResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ErrorResponse errorInstance = new ErrorResponse();
result.Error = errorInstance;
JToken codeValue = responseDoc["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
errorInstance.Code = codeInstance;
}
JToken messageValue = responseDoc["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
errorInstance.Message = messageInstance;
}
JToken targetValue = responseDoc["target"];
if (targetValue != null && targetValue.Type != JTokenType.Null)
{
string targetInstance = ((string)targetValue);
errorInstance.Target = targetInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Location"))
{
result.OperationStatusLink = httpResponse.Headers.GetValues("Location").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Retry-After"))
{
result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture);
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.Accepted)
{
result.Status = OperationStatus.InProgress;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
namespace System.Data.SqlClient
{
internal sealed class SqlCommandSet
{
private const string SqlIdentifierPattern = "^@[\\p{Lo}\\p{Lu}\\p{Ll}\\p{Lm}_@#][\\p{Lo}\\p{Lu}\\p{Ll}\\p{Lm}\\p{Nd}\uff3f_@#\\$]*$";
private static readonly Regex s_sqlIdentifierParser = new Regex(SqlIdentifierPattern, RegexOptions.ExplicitCapture | RegexOptions.Singleline);
private List<LocalCommand> _commandList = new List<LocalCommand>();
private SqlCommand _batchCommand;
private sealed class LocalCommand
{
internal readonly string CommandText;
internal readonly SqlParameterCollection Parameters;
internal readonly int ReturnParameterIndex;
internal readonly CommandType CmdType;
internal LocalCommand(string commandText, SqlParameterCollection parameters, int returnParameterIndex, CommandType cmdType)
{
Debug.Assert(0 <= commandText.Length, "no text");
CommandText = commandText;
Parameters = parameters;
ReturnParameterIndex = returnParameterIndex;
CmdType = cmdType;
}
}
internal SqlCommandSet() : base()
{
_batchCommand = new SqlCommand();
}
private SqlCommand BatchCommand
{
get
{
SqlCommand command = _batchCommand;
if (null == command)
{
throw ADP.ObjectDisposed(this);
}
return command;
}
}
internal int CommandCount => CommandList.Count;
private List<LocalCommand> CommandList
{
get
{
List<LocalCommand> commandList = _commandList;
if (null == commandList)
{
throw ADP.ObjectDisposed(this);
}
return commandList;
}
}
internal int CommandTimeout
{
set
{
BatchCommand.CommandTimeout = value;
}
}
internal SqlConnection Connection
{
get
{
return BatchCommand.Connection;
}
set
{
BatchCommand.Connection = value;
}
}
internal SqlTransaction Transaction
{
set
{
BatchCommand.Transaction = value;
}
}
internal void Append(SqlCommand command)
{
ADP.CheckArgumentNull(command, nameof(command));
string cmdText = command.CommandText;
if (string.IsNullOrEmpty(cmdText))
{
throw ADP.CommandTextRequired(nameof(Append));
}
CommandType commandType = command.CommandType;
switch (commandType)
{
case CommandType.Text:
case CommandType.StoredProcedure:
break;
case CommandType.TableDirect:
throw SQL.NotSupportedCommandType(commandType);
default:
throw ADP.InvalidCommandType(commandType);
}
SqlParameterCollection parameters = null;
SqlParameterCollection collection = command.Parameters;
if (0 < collection.Count)
{
parameters = new SqlParameterCollection();
// clone parameters so they aren't destroyed
for (int i = 0; i < collection.Count; ++i)
{
SqlParameter p = new SqlParameter();
collection[i].CopyTo(p);
parameters.Add(p);
// SQL Injection awareness
if (!s_sqlIdentifierParser.IsMatch(p.ParameterName))
{
throw ADP.BadParameterName(p.ParameterName);
}
}
foreach (SqlParameter p in parameters)
{
// deep clone the parameter value if byte[] or char[]
object obj = p.Value;
byte[] byteValues = (obj as byte[]);
if (null != byteValues)
{
int offset = p.Offset;
int size = p.Size;
int countOfBytes = byteValues.Length - offset;
if ((0 != size) && (size < countOfBytes))
{
countOfBytes = size;
}
byte[] copy = new byte[Math.Max(countOfBytes, 0)];
Buffer.BlockCopy(byteValues, offset, copy, 0, copy.Length);
p.Offset = 0;
p.Value = copy;
}
else
{
char[] charValues = (obj as char[]);
if (null != charValues)
{
int offset = p.Offset;
int size = p.Size;
int countOfChars = charValues.Length - offset;
if ((0 != size) && (size < countOfChars))
{
countOfChars = size;
}
char[] copy = new char[Math.Max(countOfChars, 0)];
Buffer.BlockCopy(charValues, offset, copy, 0, copy.Length * 2);
p.Offset = 0;
p.Value = copy;
}
else
{
ICloneable cloneable = (obj as ICloneable);
if (null != cloneable)
{
p.Value = cloneable.Clone();
}
}
}
}
}
int returnParameterIndex = -1;
if (null != parameters)
{
for (int i = 0; i < parameters.Count; ++i)
{
if (ParameterDirection.ReturnValue == parameters[i].Direction)
{
returnParameterIndex = i;
break;
}
}
}
LocalCommand cmd = new LocalCommand(cmdText, parameters, returnParameterIndex, command.CommandType);
CommandList.Add(cmd);
}
internal static void BuildStoredProcedureName(StringBuilder builder, string part)
{
if ((null != part) && (0 < part.Length))
{
if ('[' == part[0])
{
int count = 0;
foreach (char c in part)
{
if (']' == c)
{
count++;
}
}
if (1 == (count % 2))
{
builder.Append(part);
return;
}
}
// the part is not escaped, escape it now
SqlServerEscapeHelper.EscapeIdentifier(builder, part);
}
}
internal void Clear()
{
DbCommand batchCommand = BatchCommand;
if (null != batchCommand)
{
batchCommand.Parameters.Clear();
batchCommand.CommandText = null;
}
List<LocalCommand> commandList = _commandList;
if (null != commandList)
{
commandList.Clear();
}
}
internal void Dispose()
{
SqlCommand command = _batchCommand;
_commandList = null;
_batchCommand = null;
if (null != command)
{
command.Dispose();
}
}
internal int ExecuteNonQuery()
{
ValidateCommandBehavior(nameof(ExecuteNonQuery), CommandBehavior.Default);
BatchCommand.BatchRPCMode = true;
BatchCommand.ClearBatchCommand();
BatchCommand.Parameters.Clear();
for (int ii = 0; ii < _commandList.Count; ii++)
{
LocalCommand cmd = _commandList[ii];
BatchCommand.AddBatchCommand(cmd.CommandText, cmd.Parameters, cmd.CmdType);
}
return BatchCommand.ExecuteBatchRPCCommand();
}
internal SqlParameter GetParameter(int commandIndex, int parameterIndex)
=> CommandList[commandIndex].Parameters[parameterIndex];
internal bool GetBatchedAffected(int commandIdentifier, out int recordsAffected, out Exception error)
{
error = BatchCommand.GetErrors(commandIdentifier);
int? affected = BatchCommand.GetRecordsAffected(commandIdentifier);
recordsAffected = affected.GetValueOrDefault();
return affected.HasValue;
}
internal int GetParameterCount(int commandIndex)
=> CommandList[commandIndex].Parameters.Count;
private void ValidateCommandBehavior(string method, CommandBehavior behavior)
{
if (0 != (behavior & ~(CommandBehavior.SequentialAccess | CommandBehavior.CloseConnection)))
{
ADP.ValidateCommandBehavior(behavior);
throw ADP.NotSupportedCommandBehavior(behavior & ~(CommandBehavior.SequentialAccess | CommandBehavior.CloseConnection), method);
}
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
//
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is DotSpatial
//
// The Initial Developer of this Original Code is Ted Dunsford. Created in February, 2008.
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using GeoAPI.Geometries;
using NetTopologySuite.Algorithm;
namespace DotSpatial.Data
{
/// <summary>
/// A shapefile class that handles the special case where the data is made up of polygons
/// </summary>
public class PolygonShapefile : Shapefile
{
/// <summary>
/// Creates a new instance of a PolygonShapefile for in-ram handling only.
/// </summary>
public PolygonShapefile()
: base(FeatureType.Polygon)
{
Attributes = new AttributeTable();
Header = new ShapefileHeader { FileLength = 100, ShapeType = ShapeType.Polygon };
}
/// <summary>
/// Creates a new instance of a PolygonShapefile that is loaded from the supplied fileName.
/// </summary>
/// <param name="fileName">The string fileName of the polygon shapefile to load</param>
public PolygonShapefile(string fileName)
: this()
{
Open(fileName, null);
}
/// <summary>
/// Opens a shapefile
/// </summary>
/// <param name="fileName">The string fileName of the polygon shapefile to load</param>
/// <param name="progressHandler">Any valid implementation of the DotSpatial.Data.IProgressHandler</param>
public void Open(string fileName, IProgressHandler progressHandler)
{
if (!File.Exists(fileName)) return;
Filename = fileName;
IndexMode = true;
Header = new ShapefileHeader(fileName);
switch (Header.ShapeType)
{
case ShapeType.PolygonM:
CoordinateType = CoordinateType.M;
break;
case ShapeType.PolygonZ:
CoordinateType = CoordinateType.Z;
break;
default:
CoordinateType = CoordinateType.Regular;
break;
}
Extent = Header.ToExtent();
Name = Path.GetFileNameWithoutExtension(fileName);
Attributes.Open(fileName);
LineShapefile.FillLines(fileName, progressHandler, this, FeatureType.Polygon);
ReadProjection();
}
// X Y Poly Lines: Total Length = 28 Bytes
// ---------------------------------------------------------
// Position Value Type Number Byte Order
// ---------------------------------------------------------
// Byte 0 Record Number Integer 1 Big
// Byte 4 Content Length Integer 1 Big
// Byte 8 Shape Type 3 Integer 1 Little
// Byte 12 Xmin Double 1 Little
// Byte 20 Ymin Double 1 Little
// Byte 28 Xmax Double 1 Little
// Byte 36 Ymax Double 1 Little
// Byte 44 NumParts Integer 1 Little
// Byte 48 NumPoints Integer 1 Little
// Byte 52 Parts Integer NumParts Little
// Byte X Points Point NumPoints Little
// X = 52 + 4 * NumParts
// X Y M Poly Lines: Total Length = 34 Bytes
// ---------------------------------------------------------
// Position Value Type Number Byte Order
// ---------------------------------------------------------
// Byte 0 Record Number Integer 1 Big
// Byte 4 Content Length Integer 1 Big
// Byte 8 Shape Type 23 Integer 1 Little
// Byte 12 Box Double 4 Little
// Byte 44 NumParts Integer 1 Little
// Byte 48 NumPoints Integer 1 Little
// Byte 52 Parts Integer NumParts Little
// Byte X Points Point NumPoints Little
// Byte Y* Mmin Double 1 Little
// Byte Y + 8* Mmax Double 1 Little
// Byte Y + 16* Marray Double NumPoints Little
// X = 52 + (4 * NumParts)
// Y = X + (16 * NumPoints)
// * = optional
// X Y Z M Poly Lines: Total Length = 44 Bytes
// ---------------------------------------------------------
// Position Value Type Number Byte Order
// ---------------------------------------------------------
// Byte 0 Record Number Integer 1 Big
// Byte 4 Content Length Integer 1 Big
// Byte 8 Shape Type 13 Integer 1 Little
// Byte 12 Box Double 4 Little
// Byte 44 NumParts Integer 1 Little
// Byte 48 NumPoints Integer 1 Little
// Byte 52 Parts Integer NumParts Little
// Byte X Points Point NumPoints Little
// Byte Y Zmin Double 1 Little
// Byte Y + 8 Zmax Double 1 Little
// Byte Y + 16 Zarray Double NumPoints Little
// Byte Z* Mmin Double 1 Little
// Byte Z+8* Mmax Double 1 Little
// Byte Z+16* Marray Double NumPoints Little
// X = 52 + (4 * NumParts)
// Y = X + (16 * NumPoints)
// Z = Y + 16 + (8 * NumPoints)
// * = optional
/// <summary>
/// Gets the specified feature by constructing it from the vertices, rather
/// than requiring that all the features be created. (which takes up a lot of memory).
/// </summary>
/// <param name="index">The integer index</param>
public override IFeature GetFeature(int index)
{
IFeature f;
if (!IndexMode)
{
f = Features[index];
}
else
{
f = GetPolygon(index);
f.DataRow = AttributesPopulated ? DataTable.Rows[index] : Attributes.SupplyPageOfData(index, 1).Rows[0];
}
return f;
}
/// <summary>
/// Saves the file to a new location
/// </summary>
/// <param name="fileName">The fileName to save</param>
/// <param name="overwrite">Boolean that specifies whether or not to overwrite the existing file</param>
public override void SaveAs(string fileName, bool overwrite)
{
EnsureValidFileToSave(fileName, overwrite);
Filename = fileName;
// Set ShapeType before setting extent.
if (CoordinateType == CoordinateType.Regular)
{
Header.ShapeType = ShapeType.Polygon;
}
if (CoordinateType == CoordinateType.M)
{
Header.ShapeType = ShapeType.PolygonM;
}
if (CoordinateType == CoordinateType.Z)
{
Header.ShapeType = ShapeType.PolygonZ;
}
HeaderSaveAs(fileName);
if (IndexMode)
{
SaveAsIndexed(fileName);
return;
}
var bbWriter = new BufferedBinaryWriter(fileName);
var indexWriter = new BufferedBinaryWriter(Header.ShxFilename);
int fid = 0;
int offset = 50; // the shapefile header starts at 100 bytes, so the initial offset is 50 words
int contentLength = 0;
foreach (IFeature f in Features)
{
List<int> parts = new List<int>();
offset += contentLength; // adding the previous content length from each loop calculates the word offset
List<Coordinate> points = new List<Coordinate>();
contentLength = 22;
for (int iPart = 0; iPart < f.Geometry.NumGeometries; iPart++)
{
parts.Add(points.Count);
IPolygon pg = f.Geometry.GetGeometryN(iPart) as IPolygon;
if (pg == null) continue;
ILineString bl = pg.Shell;
IEnumerable<Coordinate> coords = bl.Coordinates;
if (CGAlgorithms.IsCCW(bl.Coordinates))
{
// Exterior rings need to be clockwise
coords = coords.Reverse();
}
foreach (Coordinate coord in coords)
{
points.Add(coord);
}
foreach (ILineString hole in pg.Holes)
{
parts.Add(points.Count);
IEnumerable<Coordinate> holeCoords = hole.Coordinates;
if (!CGAlgorithms.IsCCW(hole.Coordinates))
{
// Interior rings need to be counter-clockwise
holeCoords = holeCoords.Reverse();
}
foreach (Coordinate coord in holeCoords)
{
points.Add(coord);
}
}
}
contentLength += 2 * parts.Count;
if (Header.ShapeType == ShapeType.Polygon)
{
contentLength += points.Count * 8;
}
if (Header.ShapeType == ShapeType.PolygonM)
{
contentLength += 8; // mmin mmax
contentLength += points.Count * 12; // x, y, m
}
if (Header.ShapeType == ShapeType.PolygonZ)
{
contentLength += 16; // mmin, mmax, zmin, zmax
contentLength += points.Count * 16; // x, y, m, z
}
// Index File
// ---------------------------------------------------------
// Position Value Type Number Byte Order
// ---------------------------------------------------------
indexWriter.Write(offset, false); // Byte 0 Offset Integer 1 Big
indexWriter.Write(contentLength, false); // Byte 4 Content Length Integer 1 Big
// X Y Poly Lines
// ---------------------------------------------------------
// Position Value Type Number Byte Order
// ---------------------------------------------------------
bbWriter.Write(fid + 1, false); // Byte 0 Record Number Integer 1 Big
bbWriter.Write(contentLength, false); // Byte 4 Content Length Integer 1 Big
bbWriter.Write((int)Header.ShapeType); // Byte 8 Shape Type 3 Integer 1 Little
if (Header.ShapeType == ShapeType.NullShape)
{
continue;
}
bbWriter.Write(f.Geometry.EnvelopeInternal.MinX); // Byte 12 Xmin Double 1 Little
bbWriter.Write(f.Geometry.EnvelopeInternal.MinY); // Byte 20 Ymin Double 1 Little
bbWriter.Write(f.Geometry.EnvelopeInternal.MaxX); // Byte 28 Xmax Double 1 Little
bbWriter.Write(f.Geometry.EnvelopeInternal.MaxY); // Byte 36 Ymax Double 1 Little
bbWriter.Write(parts.Count); // Byte 44 NumParts Integer 1 Little
bbWriter.Write(points.Count); // Byte 48 NumPoints Integer 1 Little
// Byte 52 Parts Integer NumParts Little
foreach (int iPart in parts)
{
bbWriter.Write(iPart);
}
double[] xyVals = new double[points.Count * 2];
int i = 0;
// Byte X Points Point NumPoints Little
foreach (Coordinate coord in points)
{
xyVals[i * 2] = coord.X;
xyVals[i * 2 + 1] = coord.Y;
i++;
}
bbWriter.Write(xyVals);
if (Header.ShapeType == ShapeType.PolygonZ)
{
bbWriter.Write(f.Geometry.EnvelopeInternal.Minimum.Z);
bbWriter.Write(f.Geometry.EnvelopeInternal.Maximum.Z);
double[] zVals = new double[points.Count];
for (int ipoint = 0; ipoint < points.Count; i++)
{
zVals[ipoint] = points[ipoint].Z;
ipoint++;
}
bbWriter.Write(zVals);
}
if (Header.ShapeType == ShapeType.PolygonM || Header.ShapeType == ShapeType.PolygonZ)
{
if (f.Geometry.EnvelopeInternal == null)
{
bbWriter.Write(0.0);
bbWriter.Write(0.0);
}
else
{
bbWriter.Write(f.Geometry.EnvelopeInternal.Minimum.M);
bbWriter.Write(f.Geometry.EnvelopeInternal.Maximum.M);
}
double[] mVals = new double[points.Count];
for (int ipoint = 0; ipoint < points.Count; i++)
{
mVals[ipoint] = points[ipoint].M;
ipoint++;
}
bbWriter.Write(mVals);
}
fid++;
offset += 4; // header bytes
}
bbWriter.Close();
indexWriter.Close();
offset += contentLength;
//offset += 4;
WriteFileLength(fileName, offset);
WriteFileLength(Header.ShxFilename, 50 + fid * 4);
UpdateAttributes();
SaveProjection();
}
private void SaveAsIndexed(string fileName)
{
var shpStream = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.None, 10000000);
var shxStream = new FileStream(Header.ShxFilename, FileMode.Append, FileAccess.Write, FileShare.None, 10000000);
int fid = 0;
int offset = 50; // the shapefile header starts at 100 bytes, so the initial offset is 50 words
int contentLength = 0;
foreach (ShapeRange shape in ShapeIndices)
{
offset += contentLength; // adding the previous content length from each loop calculates the word offset
contentLength = 22;
contentLength += 2 * shape.NumParts;
if (Header.ShapeType == ShapeType.Polygon)
{
contentLength += shape.NumPoints * 8;
}
if (Header.ShapeType == ShapeType.PolygonM)
{
contentLength += 8; // mmin mmax
contentLength += shape.NumPoints * 12; // x, y, m
}
if (Header.ShapeType == ShapeType.PolygonZ)
{
contentLength += 16; // mmin, mmax, zmin, zmax
contentLength += shape.NumPoints * 16; // x, y, m, z
}
// Index File
// ---------------------------------------------------------
// Position Value Type Number Byte Order
// ---------------------------------------------------------
shxStream.WriteBe(offset); // Byte 0 Offset Integer 1 Big
shxStream.WriteBe(contentLength); // Byte 4 Content Length Integer 1 Big
// X Y Poly Lines
// ---------------------------------------------------------
// Position Value Type Number Byte Order
// ---------------------------------------------------------
shpStream.WriteBe(fid + 1); // Byte 0 Record Number Integer 1 Big
shpStream.WriteBe(contentLength); // Byte 4 Content Length Integer 1 Big
shpStream.WriteLe((int)Header.ShapeType); // Byte 8 Shape Type 3 Integer 1 Little
if (Header.ShapeType == ShapeType.NullShape)
{
continue;
}
shpStream.WriteLe(shape.Extent.MinX); // Byte 12 Xmin Double 1 Little
shpStream.WriteLe(shape.Extent.MinY); // Byte 20 Ymin Double 1 Little
shpStream.WriteLe(shape.Extent.MaxX); // Byte 28 Xmax Double 1 Little
shpStream.WriteLe(shape.Extent.MaxY); // Byte 36 Ymax Double 1 Little
shpStream.WriteLe(shape.NumParts); // Byte 44 NumParts Integer 1 Little
shpStream.WriteLe(shape.NumPoints); // Byte 48 NumPoints Integer 1 Little
// Byte 52 Parts Integer NumParts Little
foreach (PartRange part in shape.Parts)
{
shpStream.WriteLe(part.PartOffset);
}
int start = shape.StartIndex;
int count = shape.NumPoints;
shpStream.WriteLe(Vertex, start * 2, count * 2);
if (Header.ShapeType == ShapeType.PolygonZ)
{
double[] shapeZ = new double[count];
Array.Copy(Z, start, shapeZ, 0, count);
shpStream.WriteLe(shapeZ.Min());
shpStream.WriteLe(shapeZ.Max());
shpStream.WriteLe(Z, start, count);
}
if (Header.ShapeType == ShapeType.PolygonM || Header.ShapeType == ShapeType.PolygonZ)
{
if (M != null && M.Length >= start + count)
{
double[] shapeM = new double[count];
Array.Copy(M, start, shapeM, 0, count);
shpStream.WriteLe(shapeM.Min());
shpStream.WriteLe(shapeM.Max());
shpStream.WriteLe(M, start, count);
}
}
fid++;
offset += 4; // header bytes
}
shpStream.Close();
shxStream.Close();
offset += contentLength;
WriteFileLength(fileName, offset);
WriteFileLength(Header.ShxFilename, 50 + fid * 4);
UpdateAttributes();
SaveProjection();
}
}
}
| |
using System;
using System.Globalization;
namespace System.Management
{
public sealed class ManagementDateTimeConverter
{
private const int SIZEOFDMTFDATETIME = 25;
private const int MAXSIZE_UTC_DMTF = 0x3e7;
private const long MAXDATE_INTIMESPAN = 0x5f5e0ffL;
private ManagementDateTimeConverter()
{
}
public static DateTime ToDateTime(string dmtfDate)
{
DateTime minValue = DateTime.MinValue;
int year = minValue.Year;
DateTime dateTime = DateTime.MinValue;
int month = dateTime.Month;
DateTime minValue1 = DateTime.MinValue;
int day = minValue1.Day;
DateTime dateTime1 = DateTime.MinValue;
int hour = dateTime1.Hour;
DateTime minValue2 = DateTime.MinValue;
int minute = minValue2.Minute;
DateTime dateTime2 = DateTime.MinValue;
int second = dateTime2.Second;
int num = 0;
string str = dmtfDate;
if (str != null)
{
if (str.Length != 0)
{
if (str.Length == 25)
{
IFormatProvider format = (IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(int));
long num1 = (long)0;
try
{
string str1 = str.Substring(0, 4);
if ("****" != str1)
{
year = int.Parse(str1, format);
}
str1 = str.Substring(4, 2);
if ("**" != str1)
{
month = int.Parse(str1, format);
}
str1 = str.Substring(6, 2);
if ("**" != str1)
{
day = int.Parse(str1, format);
}
str1 = str.Substring(8, 2);
if ("**" != str1)
{
hour = int.Parse(str1, format);
}
str1 = str.Substring(10, 2);
if ("**" != str1)
{
minute = int.Parse(str1, format);
}
str1 = str.Substring(12, 2);
if ("**" != str1)
{
second = int.Parse(str1, format);
}
str1 = str.Substring(15, 6);
if ("******" != str1)
{
num1 = long.Parse(str1, (IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(long))) * (long)10;
}
if (year < 0 || month < 0 || day < 0 || hour < 0 || minute < 0 || second < 0 || num1 < (long)0)
{
throw new ArgumentOutOfRangeException("dmtfDate");
}
}
catch
{
throw new ArgumentOutOfRangeException("dmtfDate");
}
DateTime dateTime3 = new DateTime(year, month, day, hour, minute, second, num);
dateTime3 = dateTime3.AddTicks(num1);
TimeZone currentTimeZone = TimeZone.CurrentTimeZone;
TimeSpan utcOffset = currentTimeZone.GetUtcOffset(dateTime3);
long ticks = utcOffset.Ticks / (long)0x23c34600;
int num2 = 0;
string str2 = str.Substring(22, 3);
if ("***" != str2)
{
str2 = str.Substring(21, 4);
try
{
num2 = int.Parse(str2, format);
}
catch
{
throw new ArgumentOutOfRangeException();
}
long num3 = (long)num2 - ticks;
dateTime3 = dateTime3.AddMinutes((double)(num3 * (long)-1));
}
return dateTime3;
}
else
{
throw new ArgumentOutOfRangeException("dmtfDate");
}
}
else
{
throw new ArgumentOutOfRangeException("dmtfDate");
}
}
else
{
throw new ArgumentOutOfRangeException("dmtfDate");
}
}
public static string ToDmtfDateTime(DateTime date)
{
string str;
TimeZone currentTimeZone = TimeZone.CurrentTimeZone;
TimeSpan utcOffset = currentTimeZone.GetUtcOffset(date);
long ticks = utcOffset.Ticks / (long)0x23c34600;
IFormatProvider format = (IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(int));
if (Math.Abs(ticks) <= (long)0x3e7)
{
if (utcOffset.Ticks < (long)0)
{
string str1 = ticks.ToString(format);
str = string.Concat("-", str1.Substring(1, str1.Length - 1).PadLeft(3, '0'));
}
else
{
long num = utcOffset.Ticks / (long)0x23c34600;
str = string.Concat("+", num.ToString(format).PadLeft(3, '0'));
}
}
else
{
date = date.ToUniversalTime();
str = "+000";
}
int year = date.Year;
string str2 = year.ToString(format).PadLeft(4, '0');
int month = date.Month;
str2 = string.Concat(str2, month.ToString(format).PadLeft(2, '0'));
int day = date.Day;
str2 = string.Concat(str2, day.ToString(format).PadLeft(2, '0'));
int hour = date.Hour;
str2 = string.Concat(str2, hour.ToString(format).PadLeft(2, '0'));
int minute = date.Minute;
str2 = string.Concat(str2, minute.ToString(format).PadLeft(2, '0'));
int second = date.Second;
str2 = string.Concat(str2, second.ToString(format).PadLeft(2, '0'));
str2 = string.Concat(str2, ".");
DateTime dateTime = new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0);
long ticks1 = (date.Ticks - dateTime.Ticks) * (long)0x3e8 / (long)0x2710;
string str3 = ticks1.ToString((IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(long)));
if (str3.Length > 6)
{
str3 = str3.Substring(0, 6);
}
str2 = string.Concat(str2, str3.PadLeft(6, '0'));
str2 = string.Concat(str2, str);
return str2;
}
public static string ToDmtfTimeInterval(TimeSpan timespan)
{
int days = timespan.Days;
string str = days.ToString((IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(int))).PadLeft(8, '0');
IFormatProvider format = (IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(int));
if ((long)timespan.Days > (long)0x5f5e0ff || timespan < TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException();
}
else
{
int hours = timespan.Hours;
str = string.Concat(str, hours.ToString(format).PadLeft(2, '0'));
int minutes = timespan.Minutes;
str = string.Concat(str, minutes.ToString(format).PadLeft(2, '0'));
int seconds = timespan.Seconds;
str = string.Concat(str, seconds.ToString(format).PadLeft(2, '0'));
str = string.Concat(str, ".");
TimeSpan timeSpan = new TimeSpan(timespan.Days, timespan.Hours, timespan.Minutes, timespan.Seconds, 0);
long ticks = (timespan.Ticks - timeSpan.Ticks) * (long)0x3e8 / (long)0x2710;
string str1 = ticks.ToString((IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(long)));
if (str1.Length > 6)
{
str1 = str1.Substring(0, 6);
}
str = string.Concat(str, str1.PadLeft(6, '0'));
str = string.Concat(str, ":000");
return str;
}
}
public static TimeSpan ToTimeSpan(string dmtfTimespan)
{
int num = 0;
int num1 = 0;
int num2 = 0;
int num3 = 0;
IFormatProvider format = (IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(int));
string str = dmtfTimespan;
if (str != null)
{
if (str.Length != 0)
{
if (str.Length == 25)
{
if (str.Substring(21, 4) == ":000")
{
long num4 = (long)0;
try
{
string str1 = str.Substring(0, 8);
num = int.Parse(str1, format);
str1 = str.Substring(8, 2);
num1 = int.Parse(str1, format);
str1 = str.Substring(10, 2);
num2 = int.Parse(str1, format);
str1 = str.Substring(12, 2);
num3 = int.Parse(str1, format);
str1 = str.Substring(15, 6);
num4 = long.Parse(str1, (IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(long))) * (long)10;
}
catch
{
throw new ArgumentOutOfRangeException("dmtfTimespan");
}
if (num < 0 || num1 < 0 || num2 < 0 || num3 < 0 || num4 < (long)0)
{
throw new ArgumentOutOfRangeException("dmtfTimespan");
}
else
{
TimeSpan timeSpan = new TimeSpan(num, num1, num2, num3, 0);
TimeSpan timeSpan1 = TimeSpan.FromTicks(num4);
timeSpan = timeSpan + timeSpan1;
return timeSpan;
}
}
else
{
throw new ArgumentOutOfRangeException("dmtfTimespan");
}
}
else
{
throw new ArgumentOutOfRangeException("dmtfTimespan");
}
}
else
{
throw new ArgumentOutOfRangeException("dmtfTimespan");
}
}
else
{
throw new ArgumentOutOfRangeException("dmtfTimespan");
}
}
}
}
| |
// 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!
namespace Google.Cloud.Datastore.Admin.V1.Snippets
{
using Google.Api.Gax;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using gcdav = Google.Cloud.Datastore.Admin.V1;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedDatastoreAdminClientSnippets
{
/// <summary>Snippet for ExportEntities</summary>
public void ExportEntitiesRequestObject()
{
// Snippet: ExportEntities(ExportEntitiesRequest, CallSettings)
// Create client
DatastoreAdminClient datastoreAdminClient = DatastoreAdminClient.Create();
// Initialize request argument(s)
ExportEntitiesRequest request = new ExportEntitiesRequest
{
ProjectId = "",
Labels = { { "", "" }, },
EntityFilter = new EntityFilter(),
OutputUrlPrefix = "",
};
// Make the request
Operation<ExportEntitiesResponse, ExportEntitiesMetadata> response = datastoreAdminClient.ExportEntities(request);
// Poll until the returned long-running operation is complete
Operation<ExportEntitiesResponse, ExportEntitiesMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
ExportEntitiesResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ExportEntitiesResponse, ExportEntitiesMetadata> retrievedResponse = datastoreAdminClient.PollOnceExportEntities(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ExportEntitiesResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ExportEntitiesAsync</summary>
public async Task ExportEntitiesRequestObjectAsync()
{
// Snippet: ExportEntitiesAsync(ExportEntitiesRequest, CallSettings)
// Additional: ExportEntitiesAsync(ExportEntitiesRequest, CancellationToken)
// Create client
DatastoreAdminClient datastoreAdminClient = await DatastoreAdminClient.CreateAsync();
// Initialize request argument(s)
ExportEntitiesRequest request = new ExportEntitiesRequest
{
ProjectId = "",
Labels = { { "", "" }, },
EntityFilter = new EntityFilter(),
OutputUrlPrefix = "",
};
// Make the request
Operation<ExportEntitiesResponse, ExportEntitiesMetadata> response = await datastoreAdminClient.ExportEntitiesAsync(request);
// Poll until the returned long-running operation is complete
Operation<ExportEntitiesResponse, ExportEntitiesMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
ExportEntitiesResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ExportEntitiesResponse, ExportEntitiesMetadata> retrievedResponse = await datastoreAdminClient.PollOnceExportEntitiesAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ExportEntitiesResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ExportEntities</summary>
public void ExportEntities()
{
// Snippet: ExportEntities(string, IDictionary<string,string>, EntityFilter, string, CallSettings)
// Create client
DatastoreAdminClient datastoreAdminClient = DatastoreAdminClient.Create();
// Initialize request argument(s)
string projectId = "";
IDictionary<string, string> labels = new Dictionary<string, string> { { "", "" }, };
EntityFilter entityFilter = new EntityFilter();
string outputUrlPrefix = "";
// Make the request
Operation<ExportEntitiesResponse, ExportEntitiesMetadata> response = datastoreAdminClient.ExportEntities(projectId, labels, entityFilter, outputUrlPrefix);
// Poll until the returned long-running operation is complete
Operation<ExportEntitiesResponse, ExportEntitiesMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
ExportEntitiesResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ExportEntitiesResponse, ExportEntitiesMetadata> retrievedResponse = datastoreAdminClient.PollOnceExportEntities(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ExportEntitiesResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ExportEntitiesAsync</summary>
public async Task ExportEntitiesAsync()
{
// Snippet: ExportEntitiesAsync(string, IDictionary<string,string>, EntityFilter, string, CallSettings)
// Additional: ExportEntitiesAsync(string, IDictionary<string,string>, EntityFilter, string, CancellationToken)
// Create client
DatastoreAdminClient datastoreAdminClient = await DatastoreAdminClient.CreateAsync();
// Initialize request argument(s)
string projectId = "";
IDictionary<string, string> labels = new Dictionary<string, string> { { "", "" }, };
EntityFilter entityFilter = new EntityFilter();
string outputUrlPrefix = "";
// Make the request
Operation<ExportEntitiesResponse, ExportEntitiesMetadata> response = await datastoreAdminClient.ExportEntitiesAsync(projectId, labels, entityFilter, outputUrlPrefix);
// Poll until the returned long-running operation is complete
Operation<ExportEntitiesResponse, ExportEntitiesMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
ExportEntitiesResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ExportEntitiesResponse, ExportEntitiesMetadata> retrievedResponse = await datastoreAdminClient.PollOnceExportEntitiesAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ExportEntitiesResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ImportEntities</summary>
public void ImportEntitiesRequestObject()
{
// Snippet: ImportEntities(ImportEntitiesRequest, CallSettings)
// Create client
DatastoreAdminClient datastoreAdminClient = DatastoreAdminClient.Create();
// Initialize request argument(s)
ImportEntitiesRequest request = new ImportEntitiesRequest
{
ProjectId = "",
Labels = { { "", "" }, },
InputUrl = "",
EntityFilter = new EntityFilter(),
};
// Make the request
Operation<Empty, ImportEntitiesMetadata> response = datastoreAdminClient.ImportEntities(request);
// Poll until the returned long-running operation is complete
Operation<Empty, ImportEntitiesMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, ImportEntitiesMetadata> retrievedResponse = datastoreAdminClient.PollOnceImportEntities(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ImportEntitiesAsync</summary>
public async Task ImportEntitiesRequestObjectAsync()
{
// Snippet: ImportEntitiesAsync(ImportEntitiesRequest, CallSettings)
// Additional: ImportEntitiesAsync(ImportEntitiesRequest, CancellationToken)
// Create client
DatastoreAdminClient datastoreAdminClient = await DatastoreAdminClient.CreateAsync();
// Initialize request argument(s)
ImportEntitiesRequest request = new ImportEntitiesRequest
{
ProjectId = "",
Labels = { { "", "" }, },
InputUrl = "",
EntityFilter = new EntityFilter(),
};
// Make the request
Operation<Empty, ImportEntitiesMetadata> response = await datastoreAdminClient.ImportEntitiesAsync(request);
// Poll until the returned long-running operation is complete
Operation<Empty, ImportEntitiesMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, ImportEntitiesMetadata> retrievedResponse = await datastoreAdminClient.PollOnceImportEntitiesAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ImportEntities</summary>
public void ImportEntities()
{
// Snippet: ImportEntities(string, IDictionary<string,string>, string, EntityFilter, CallSettings)
// Create client
DatastoreAdminClient datastoreAdminClient = DatastoreAdminClient.Create();
// Initialize request argument(s)
string projectId = "";
IDictionary<string, string> labels = new Dictionary<string, string> { { "", "" }, };
string inputUrl = "";
EntityFilter entityFilter = new EntityFilter();
// Make the request
Operation<Empty, ImportEntitiesMetadata> response = datastoreAdminClient.ImportEntities(projectId, labels, inputUrl, entityFilter);
// Poll until the returned long-running operation is complete
Operation<Empty, ImportEntitiesMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, ImportEntitiesMetadata> retrievedResponse = datastoreAdminClient.PollOnceImportEntities(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ImportEntitiesAsync</summary>
public async Task ImportEntitiesAsync()
{
// Snippet: ImportEntitiesAsync(string, IDictionary<string,string>, string, EntityFilter, CallSettings)
// Additional: ImportEntitiesAsync(string, IDictionary<string,string>, string, EntityFilter, CancellationToken)
// Create client
DatastoreAdminClient datastoreAdminClient = await DatastoreAdminClient.CreateAsync();
// Initialize request argument(s)
string projectId = "";
IDictionary<string, string> labels = new Dictionary<string, string> { { "", "" }, };
string inputUrl = "";
EntityFilter entityFilter = new EntityFilter();
// Make the request
Operation<Empty, ImportEntitiesMetadata> response = await datastoreAdminClient.ImportEntitiesAsync(projectId, labels, inputUrl, entityFilter);
// Poll until the returned long-running operation is complete
Operation<Empty, ImportEntitiesMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, ImportEntitiesMetadata> retrievedResponse = await datastoreAdminClient.PollOnceImportEntitiesAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateIndex</summary>
public void CreateIndexRequestObject()
{
// Snippet: CreateIndex(CreateIndexRequest, CallSettings)
// Create client
DatastoreAdminClient datastoreAdminClient = DatastoreAdminClient.Create();
// Initialize request argument(s)
CreateIndexRequest request = new CreateIndexRequest
{
ProjectId = "",
Index = new gcdav::Index(),
};
// Make the request
Operation<gcdav::Index, IndexOperationMetadata> response = datastoreAdminClient.CreateIndex(request);
// Poll until the returned long-running operation is complete
Operation<gcdav::Index, IndexOperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
gcdav::Index result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<gcdav::Index, IndexOperationMetadata> retrievedResponse = datastoreAdminClient.PollOnceCreateIndex(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
gcdav::Index retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateIndexAsync</summary>
public async Task CreateIndexRequestObjectAsync()
{
// Snippet: CreateIndexAsync(CreateIndexRequest, CallSettings)
// Additional: CreateIndexAsync(CreateIndexRequest, CancellationToken)
// Create client
DatastoreAdminClient datastoreAdminClient = await DatastoreAdminClient.CreateAsync();
// Initialize request argument(s)
CreateIndexRequest request = new CreateIndexRequest
{
ProjectId = "",
Index = new gcdav::Index(),
};
// Make the request
Operation<gcdav::Index, IndexOperationMetadata> response = await datastoreAdminClient.CreateIndexAsync(request);
// Poll until the returned long-running operation is complete
Operation<gcdav::Index, IndexOperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
gcdav::Index result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<gcdav::Index, IndexOperationMetadata> retrievedResponse = await datastoreAdminClient.PollOnceCreateIndexAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
gcdav::Index retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteIndex</summary>
public void DeleteIndexRequestObject()
{
// Snippet: DeleteIndex(DeleteIndexRequest, CallSettings)
// Create client
DatastoreAdminClient datastoreAdminClient = DatastoreAdminClient.Create();
// Initialize request argument(s)
DeleteIndexRequest request = new DeleteIndexRequest
{
ProjectId = "",
IndexId = "",
};
// Make the request
Operation<gcdav::Index, IndexOperationMetadata> response = datastoreAdminClient.DeleteIndex(request);
// Poll until the returned long-running operation is complete
Operation<gcdav::Index, IndexOperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
gcdav::Index result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<gcdav::Index, IndexOperationMetadata> retrievedResponse = datastoreAdminClient.PollOnceDeleteIndex(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
gcdav::Index retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteIndexAsync</summary>
public async Task DeleteIndexRequestObjectAsync()
{
// Snippet: DeleteIndexAsync(DeleteIndexRequest, CallSettings)
// Additional: DeleteIndexAsync(DeleteIndexRequest, CancellationToken)
// Create client
DatastoreAdminClient datastoreAdminClient = await DatastoreAdminClient.CreateAsync();
// Initialize request argument(s)
DeleteIndexRequest request = new DeleteIndexRequest
{
ProjectId = "",
IndexId = "",
};
// Make the request
Operation<gcdav::Index, IndexOperationMetadata> response = await datastoreAdminClient.DeleteIndexAsync(request);
// Poll until the returned long-running operation is complete
Operation<gcdav::Index, IndexOperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
gcdav::Index result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<gcdav::Index, IndexOperationMetadata> retrievedResponse = await datastoreAdminClient.PollOnceDeleteIndexAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
gcdav::Index retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for GetIndex</summary>
public void GetIndexRequestObject()
{
// Snippet: GetIndex(GetIndexRequest, CallSettings)
// Create client
DatastoreAdminClient datastoreAdminClient = DatastoreAdminClient.Create();
// Initialize request argument(s)
GetIndexRequest request = new GetIndexRequest
{
ProjectId = "",
IndexId = "",
};
// Make the request
gcdav::Index response = datastoreAdminClient.GetIndex(request);
// End snippet
}
/// <summary>Snippet for GetIndexAsync</summary>
public async Task GetIndexRequestObjectAsync()
{
// Snippet: GetIndexAsync(GetIndexRequest, CallSettings)
// Additional: GetIndexAsync(GetIndexRequest, CancellationToken)
// Create client
DatastoreAdminClient datastoreAdminClient = await DatastoreAdminClient.CreateAsync();
// Initialize request argument(s)
GetIndexRequest request = new GetIndexRequest
{
ProjectId = "",
IndexId = "",
};
// Make the request
gcdav::Index response = await datastoreAdminClient.GetIndexAsync(request);
// End snippet
}
/// <summary>Snippet for ListIndexes</summary>
public void ListIndexesRequestObject()
{
// Snippet: ListIndexes(ListIndexesRequest, CallSettings)
// Create client
DatastoreAdminClient datastoreAdminClient = DatastoreAdminClient.Create();
// Initialize request argument(s)
ListIndexesRequest request = new ListIndexesRequest
{
ProjectId = "",
Filter = "",
};
// Make the request
PagedEnumerable<ListIndexesResponse, gcdav::Index> response = datastoreAdminClient.ListIndexes(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (gcdav::Index item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListIndexesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (gcdav::Index item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<gcdav::Index> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (gcdav::Index item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListIndexesAsync</summary>
public async Task ListIndexesRequestObjectAsync()
{
// Snippet: ListIndexesAsync(ListIndexesRequest, CallSettings)
// Create client
DatastoreAdminClient datastoreAdminClient = await DatastoreAdminClient.CreateAsync();
// Initialize request argument(s)
ListIndexesRequest request = new ListIndexesRequest
{
ProjectId = "",
Filter = "",
};
// Make the request
PagedAsyncEnumerable<ListIndexesResponse, gcdav::Index> response = datastoreAdminClient.ListIndexesAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((gcdav::Index item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListIndexesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (gcdav::Index item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<gcdav::Index> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (gcdav::Index item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Phonix
{
public enum Direction
{
Rightward,
Leftward
}
public sealed class Rule : AbstractRule
{
public Rule(string name, IEnumerable<IRuleSegment> segments, IEnumerable<IRuleSegment> excluded)
: base(name)
{
if (segments == null || excluded == null)
{
throw new ArgumentNullException();
}
Segments = new List<IRuleSegment>(segments);
ExcludedSegments = new List<IRuleSegment>(excluded);
_hasExcluded = ExcludedSegments.Count() > 0;
UndefinedVariableUsed += (r, v) => {};
ScalarValueRangeViolation += (r, f, v) => {};
InvalidScalarValueOp += (r, f, s) => {};
}
public readonly IEnumerable<IRuleSegment> Segments;
public readonly IEnumerable<IRuleSegment> ExcludedSegments;
private readonly bool _hasExcluded = false;
private Random _random = new Random();
public IMatrixMatcher Filter { get; set; }
public Direction Direction { get; set; }
public event Action<Rule, IFeatureValue> UndefinedVariableUsed;
public event Action<Rule, ScalarFeature, int> ScalarValueRangeViolation;
public event Action<Rule, ScalarFeature, string> InvalidScalarValueOp;
private double _applicationRate = 1.0;
public double ApplicationRate
{
get { return _applicationRate; }
set
{
if (value < 0 || value > 1)
{
throw new ArgumentException("ApplicationRate must be between zero and one");
}
_applicationRate = value;
}
}
private string _description;
public override string Description
{
get
{
if (_description == null)
{
// build the description string. this is kinda complicated,
// which is why we don't do it until we're asked (and we
// save the result)
var leftCtx = new StringBuilder();
var rightCtx = new StringBuilder();
var leftAct = new StringBuilder();
var rightAct = new StringBuilder();
bool leftSide = true;
// iterate over all of the segments here, and append their
// strings to the left or right context or left/right action as
// necessary. We start by putting match segments on the left
// context, then switch to the right context as soon as we've
// encountered any action segments.
foreach (var seg in Segments)
{
if (seg.IsMatchOnlySegment)
{
if (leftSide)
{
leftCtx.Append(seg.MatchString);
}
else
{
rightCtx.Append(seg.MatchString);
}
}
else
{
leftAct.Append(seg.MatchString);
rightAct.Append(seg.CombineString);
leftSide = false;
}
}
_description = String.Format("{0} => {1} / {2} _ {3}",
leftAct.ToString(),
rightAct.ToString(),
leftCtx.ToString(),
rightCtx.ToString());
}
return _description;
}
}
public override void Apply(Word word)
{
OnEntered(word);
try
{
foreach (var slice in AppliedEnumeration(word))
{
OnApplied(word, slice);
}
}
finally
{
OnExited(word);
}
}
internal IEnumerable<WordSlice> AppliedEnumeration(Word word)
{
foreach (var slice in word.Slice(Direction, Filter))
{
if (_applicationRate < 1.0)
{
if (_random.NextDouble() > _applicationRate)
{
// skip this potential application of the rule
continue;
}
}
var ctx = new RuleContext();
// match all of the segments
if (!MatchesSegments(slice, Segments, ctx))
{
continue;
}
// ensure that we don't match the excluded segments
if (_hasExcluded && MatchesSegments(slice, ExcludedSegments, ctx))
{
continue;
}
// apply all of the segments
using (var mutableSegment = slice.GetMutableEnumerator())
{
foreach (var ruleSegment in Segments)
{
try
{
ruleSegment.Combine(ctx, mutableSegment);
}
catch (UndefinedFeatureVariableException ex)
{
UndefinedVariableUsed(this, ex.Variable);
}
catch (ScalarValueRangeException ex)
{
ScalarValueRangeViolation(this, ex.Feature, ex.Value);
}
catch (InvalidScalarOpException ex)
{
InvalidScalarValueOp(this, ex.Feature, ex.Message);
}
}
yield return slice;
}
}
yield break;
}
private static bool MatchesSegments(WordSlice slice, IEnumerable<IRuleSegment> segments, RuleContext ctx)
{
using (var seg = slice.GetEnumerator())
{
foreach (var ruleSeg in segments)
{
if (!ruleSeg.Matches(ctx, seg))
{
return false;
}
}
}
return true;
}
public override string ShowApplication(Word word, WordSlice slice, SymbolSet symbolSet)
{
FeatureMatrix current = null;
Segment firstSliceSeg = null;
try
{
var ctx = new RuleContext();
var seg = Segments.GetEnumerator();
var pos = slice.GetEnumerator();
// get the first segment in the slice
pos.MoveNext();
firstSliceSeg = pos.Current;
pos = slice.GetEnumerator(); // reset the pos
// match until we get to the current segment, so that we can
// display which segment was acted upon
while (seg.MoveNext() && seg.Current.IsMatchOnlySegment)
{
// we call Matches() but throw away the value, since we're
// only calling this in order to move the enumerator
seg.Current.Matches(ctx, pos);
}
current = pos.MoveNext() ? pos.Current.Matrix : null;
}
catch (SegmentDeletedException)
{
// this occurs when we try to get the enumerator for a deleted
// segment. this exception (and only this exception) can be
// safely swallowed
}
var str = new StringBuilder();
bool inSlice = false;
foreach (var seg in word)
{
string marker = " ";
Symbol symbol;
if (seg == firstSliceSeg)
{
inSlice = true;
}
if (current != null && inSlice && seg.Matrix == current)
{
marker = ">";
}
try
{
symbol = symbolSet.Spell(seg.Matrix);
}
catch (SpellingException)
{
symbol = Symbol.Unknown;
}
str.AppendLine(String.Format("{0} {1} : {2}", marker, symbol, seg.Matrix));
}
return str.ToString();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Versioning;
using Moq;
using NuGet.Test.Mocks;
using Xunit;
namespace NuGet.Test
{
public class PackageRepositoryTest
{
[Fact]
public void FindByIdReturnsPackage()
{
// Arrange
var repo = GetLocalRepository();
// Act
var package = repo.FindPackage(packageId: "A");
// Assert
Assert.NotNull(package);
Assert.Equal("A", package.Id);
}
[Fact]
public void FindByIdReturnsNullWhenPackageNotFound()
{
// Arrange
var repo = GetLocalRepository();
// Act
var package = repo.FindPackage(packageId: "X");
// Assert
Assert.Null(package);
}
[Fact]
public void FindByIdAndVersionReturnsPackage()
{
// Arrange
var repo = GetRemoteRepository();
// Act
var package = repo.FindPackage(packageId: "A", version: SemanticVersion.Parse("1.0"));
// Assert
Assert.NotNull(package);
Assert.Equal("A", package.Id);
Assert.Equal(SemanticVersion.Parse("1.0"), package.Version);
}
[Fact]
public void FindByIdAndVersionReturnsNullWhenPackageNotFound()
{
// Arrange
var repo = GetLocalRepository();
// Act
var package1 = repo.FindPackage(packageId: "X", version: SemanticVersion.Parse("1.0"));
var package2 = repo.FindPackage(packageId: "A", version: SemanticVersion.Parse("1.1"));
// Assert
Assert.Null(package1 ?? package2);
}
[Fact]
public void FindByIdAndVersionRangeReturnsPackage()
{
// Arrange
var repo = GetRemoteRepository();
var versionSpec = VersionUtility.ParseVersionSpec("[0.9, 1.1]");
// Act
var package = repo.FindPackage("A", versionSpec, allowPrereleaseVersions: false, allowUnlisted: true);
// Assert
Assert.NotNull(package);
Assert.Equal("A", package.Id);
Assert.Equal(SemanticVersion.Parse("1.0"), package.Version);
}
[Fact]
public void FindByIdAndVersionRangeReturnsNullWhenPackageNotFound()
{
// Arrange
var repo = GetLocalRepository();
var versionSpec = VersionUtility.ParseVersionSpec("[0.9, 1.1]");
// Act
var package1 = repo.FindPackage("X", VersionUtility.ParseVersionSpec("[0.9, 1.1]"), allowPrereleaseVersions: false, allowUnlisted: true);
var package2 = repo.FindPackage("A", VersionUtility.ParseVersionSpec("[1.4, 1.5]"), allowPrereleaseVersions: false, allowUnlisted: true);
// Assert
Assert.Null(package1 ?? package2);
}
[Fact]
public void FindPackageByIdVersionAndVersionRangesUsesRangeIfExactVersionIsNull()
{
// Arrange
var repo = GetRemoteRepository();
// Act
var package = repo.FindPackage("A", VersionUtility.ParseVersionSpec("[0.6, 1.1.5]"), allowPrereleaseVersions: false, allowUnlisted: true);
// Assert
Assert.NotNull(package);
Assert.Equal("A", package.Id);
Assert.Equal(SemanticVersion.Parse("1.0"), package.Version);
}
[Fact]
public void FindPackagesReturnsPackagesWithTermInPackageTagOrDescriptionOrId()
{
// Arrange
var term = "TAG";
var repo = new MockPackageRepository();
repo.Add(CreateMockPackage("A", "1.0", "Description", " TAG "));
repo.Add(CreateMockPackage("B", "2.0", "Description", "Tags"));
repo.Add(CreateMockPackage("C", "1.0", "This description has tags in it"));
repo.Add(CreateMockPackage("D", "1.0", "Description"));
repo.Add(CreateMockPackage("TagCloud", "1.0", "Description"));
// Act
var packages = repo.GetPackages().Find(term).ToList();
// Assert
Assert.Equal(3, packages.Count);
Assert.Equal("A", packages[0].Id);
Assert.Equal("C", packages[1].Id);
Assert.Equal("TagCloud", packages[2].Id);
}
[Fact]
public void FindPackagesReturnsPrereleasePackagesIfTheFlagIsSetToTrue()
{
// Arrange
var term = "B";
var repo = GetRemoteRepository(includePrerelease: true);
// Act
var packages = repo.GetPackages().Find(term);
// Assert
Assert.Equal(packages.Count(), 2);
packages = packages.OrderBy(p => p.Id);
Assert.Equal(packages.ElementAt(0).Id, "B");
Assert.Equal(packages.ElementAt(0).Version, new SemanticVersion("1.0"));
Assert.Equal(packages.ElementAt(1).Id, "B");
Assert.Equal(packages.ElementAt(1).Version, new SemanticVersion("1.0-beta"));
}
[Fact]
public void FindPackagesReturnsPackagesWithTerm()
{
// Arrange
var term = "B xaml";
var repo = GetRemoteRepository();
// Act
var packages = repo.GetPackages().Find(term);
// Assert
Assert.Equal(packages.Count(), 2);
packages = packages.OrderBy(p => p.Id);
Assert.Equal(packages.ElementAt(0).Id, "B");
Assert.Equal(packages.ElementAt(1).Id, "C");
}
[Fact]
public void FindPackagesReturnsEmptyCollectionWhenNoPackageContainsTerm()
{
// Arrange
var term = "does-not-exist";
var repo = GetRemoteRepository();
// Act
var packages = repo.GetPackages().Find(term);
// Assert
Assert.False(packages.Any());
}
[Fact]
public void FindPackagesReturnsAllPackagesWhenSearchTermIsNullOrEmpty()
{
// Arrange
var repo = GetLocalRepository();
// Act
var packages1 = repo.GetPackages().Find(String.Empty);
var packages2 = repo.GetPackages().Find(null);
var packages3 = repo.GetPackages();
// Assert
Assert.Equal(packages1.ToList(), packages2.ToList());
Assert.Equal(packages2.ToList(), packages3.ToList());
}
[Fact]
public void SearchUsesInterfaceIfImplementedByRepository()
{
// Arrange
var repo = new Mock<MockPackageRepository>(MockBehavior.Strict);
repo.Setup(m => m.GetPackages()).Returns(Enumerable.Empty<IPackage>().AsQueryable());
repo.As<IServiceBasedRepository>().Setup(m => m.Search(It.IsAny<string>(), It.IsAny<IEnumerable<string>>(), false))
.Returns(new[] { PackageUtility.CreatePackage("A") }.AsQueryable());
// Act
var packages = repo.Object.Search("Hello", new[] { ".NETFramework" }, allowPrereleaseVersions: false).ToList();
// Assert
Assert.Equal(1, packages.Count);
Assert.Equal("A", packages[0].Id);
}
[Fact]
public void GetUpdatesReturnsPackagesWithUpdates()
{
// Arrange
var localRepo = GetLocalRepository();
var remoteRepo = GetRemoteRepository();
// Act
var packages = remoteRepo.GetUpdates(localRepo.GetPackages(), includePrerelease: false, includeAllVersions: false);
// Assert
Assert.True(packages.Any());
Assert.Equal(packages.First().Id, "A");
Assert.Equal(packages.First().Version, SemanticVersion.Parse("1.2"));
}
[Fact]
public void GetUpdatesReturnsEmptyCollectionWhenSourceRepositoryIsEmpty()
{
// Arrange
var localRepo = GetLocalRepository();
var remoteRepo = GetEmptyRepository();
// Act
var packages = remoteRepo.GetUpdates(localRepo.GetPackages(), includePrerelease: false, includeAllVersions: false);
// Assert
Assert.False(packages.Any());
}
[Fact]
public void FindDependencyPicksHighestVersionIfNotSpecified()
{
// Arrange
var repository = new MockPackageRepository() {
PackageUtility.CreatePackage("B", "2.0"),
PackageUtility.CreatePackage("B", "1.0"),
PackageUtility.CreatePackage("B", "1.0.1"),
PackageUtility.CreatePackage("B", "1.0.9"),
PackageUtility.CreatePackage("B", "1.1")
};
var dependency = new PackageDependency("B");
// Act
IPackage package = repository.ResolveDependency(dependency, allowPrereleaseVersions: false, preferListedPackages: false);
// Assert
Assert.Equal("B", package.Id);
Assert.Equal(new SemanticVersion("2.0"), package.Version);
}
[Fact]
public void FindPackageNormalizesVersionBeforeComparing()
{
// Arrange
var repository = new MockPackageRepository() {
PackageUtility.CreatePackage("B", "1.0.0"),
PackageUtility.CreatePackage("B", "1.0.0.1")
};
// Act
IPackage package = repository.FindPackage("B", new SemanticVersion("1.0"));
// Assert
Assert.Equal("B", package.Id);
Assert.Equal(new SemanticVersion("1.0.0"), package.Version);
}
[Fact]
public void FindDependencyPicksLowestMajorAndMinorVersionButHighestBuildAndRevision()
{
// Arrange
var repository = new MockPackageRepository() {
PackageUtility.CreatePackage("B", "2.0"),
PackageUtility.CreatePackage("B", "1.0"),
PackageUtility.CreatePackage("B", "1.0.1"),
PackageUtility.CreatePackage("B", "1.0.9"),
PackageUtility.CreatePackage("B", "1.1")
};
// B >= 1.0
PackageDependency dependency1 = PackageDependency.CreateDependency("B", "1.0");
// B >= 1.0.0
PackageDependency dependency2 = PackageDependency.CreateDependency("B", "1.0.0");
// B >= 1.0.0.0
PackageDependency dependency3 = PackageDependency.CreateDependency("B", "1.0.0.0");
// B = 1.0
PackageDependency dependency4 = PackageDependency.CreateDependency("B", "[1.0]");
// B >= 1.0.0 && <= 1.0.8
PackageDependency dependency5 = PackageDependency.CreateDependency("B", "[1.0.0, 1.0.8]");
// Act
IPackage package1 = repository.ResolveDependency(dependency1, allowPrereleaseVersions: false, preferListedPackages: false);
IPackage package2 = repository.ResolveDependency(dependency2, allowPrereleaseVersions: false, preferListedPackages: false);
IPackage package3 = repository.ResolveDependency(dependency3, allowPrereleaseVersions: false, preferListedPackages: false);
IPackage package4 = repository.ResolveDependency(dependency4, allowPrereleaseVersions: false, preferListedPackages: false);
IPackage package5 = repository.ResolveDependency(dependency5, allowPrereleaseVersions: false, preferListedPackages: false);
// Assert
Assert.Equal("B", package1.Id);
Assert.Equal(new SemanticVersion("1.0.9"), package1.Version);
Assert.Equal("B", package2.Id);
Assert.Equal(new SemanticVersion("1.0.9"), package2.Version);
Assert.Equal("B", package3.Id);
Assert.Equal(new SemanticVersion("1.0.9"), package3.Version);
Assert.Equal("B", package4.Id);
Assert.Equal(new SemanticVersion("1.0"), package4.Version);
Assert.Equal("B", package5.Id);
Assert.Equal(new SemanticVersion("1.0.1"), package5.Version);
}
[Fact]
public void ResolveSafeVersionReturnsNullIfPackagesNull()
{
// Act
var package = PackageRepositoryExtensions.ResolveSafeVersion(null);
// Assert
Assert.Null(package);
}
[Fact]
public void ResolveSafeVersionReturnsNullIfEmptyPackages()
{
// Act
var package = PackageRepositoryExtensions.ResolveSafeVersion(Enumerable.Empty<IPackage>());
// Assert
Assert.Null(package);
}
[Fact]
public void ResolveSafeVersionReturnsHighestBuildAndRevisionWithLowestMajorAndMinor()
{
var packages = new[] {
PackageUtility.CreatePackage("A", "0.9"),
PackageUtility.CreatePackage("A", "0.9.3"),
PackageUtility.CreatePackage("A", "1.0"),
PackageUtility.CreatePackage("A", "1.0.2"),
PackageUtility.CreatePackage("A", "1.0.12"),
PackageUtility.CreatePackage("A", "1.0.13"),
};
// Act
var package = PackageRepositoryExtensions.ResolveSafeVersion(packages);
// Assert
Assert.NotNull(package);
Assert.Equal("A", package.Id);
Assert.Equal(new SemanticVersion("0.9.3"), package.Version);
}
private static IPackageRepository GetEmptyRepository()
{
Mock<IPackageRepository> repository = new Mock<IPackageRepository>();
repository.Setup(c => c.GetPackages()).Returns(() => Enumerable.Empty<IPackage>().AsQueryable());
return repository.Object;
}
private static IPackageRepository GetRemoteRepository(bool includePrerelease = false)
{
Mock<IPackageRepository> repository = new Mock<IPackageRepository>();
var packages = new List<IPackage> {
CreateMockPackage("A", "1.0", "scripts style"),
CreateMockPackage("B", "1.0", "testing"),
CreateMockPackage("C", "2.0", "xaml"),
CreateMockPackage("A", "1.2", "a updated desc") };
if (includePrerelease)
{
packages.Add(CreateMockPackage("A", "2.0-alpha", "a prerelease package"));
packages.Add(CreateMockPackage("B", "1.0-beta", "another prerelease package"));
}
repository.Setup(c => c.GetPackages()).Returns(() => packages.AsQueryable());
return repository.Object;
}
private static IPackageRepository GetLocalRepository()
{
Mock<IPackageRepository> repository = new Mock<IPackageRepository>();
var packages = new[] { CreateMockPackage("A", "1.0"), CreateMockPackage("B", "1.0") };
repository.Setup(c => c.GetPackages()).Returns(() => packages.AsQueryable());
return repository.Object;
}
private static IPackage CreateMockPackage(string name, string version, string desc = null, string tags = null)
{
Mock<IPackage> package = new Mock<IPackage>();
package.SetupGet(p => p.Id).Returns(name);
package.SetupGet(p => p.Version).Returns(SemanticVersion.Parse(version));
package.SetupGet(p => p.Description).Returns(desc);
package.SetupGet(p => p.Tags).Returns(tags);
package.SetupGet(p => p.Listed).Returns(true);
return package.Object;
}
}
}
| |
// 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: Capture execution context for a thread
**
**
===========================================================*/
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.Serialization;
namespace System.Threading
{
public delegate void ContextCallback(object state);
internal delegate void ContextCallback<TState>(ref TState state);
public sealed class ExecutionContext : IDisposable, ISerializable
{
internal static readonly ExecutionContext Default = new ExecutionContext(isDefault: true);
internal static readonly ExecutionContext DefaultFlowSuppressed = new ExecutionContext(AsyncLocalValueMap.Empty, Array.Empty<IAsyncLocal>(), isFlowSuppressed: true);
private readonly IAsyncLocalValueMap m_localValues;
private readonly IAsyncLocal[] m_localChangeNotifications;
private readonly bool m_isFlowSuppressed;
private readonly bool m_isDefault;
private ExecutionContext(bool isDefault)
{
m_isDefault = isDefault;
}
private ExecutionContext(
IAsyncLocalValueMap localValues,
IAsyncLocal[] localChangeNotifications,
bool isFlowSuppressed)
{
m_localValues = localValues;
m_localChangeNotifications = localChangeNotifications;
m_isFlowSuppressed = isFlowSuppressed;
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
public static ExecutionContext Capture()
{
ExecutionContext executionContext = Thread.CurrentThread._executionContext;
if (executionContext == null)
{
executionContext = Default;
}
else if (executionContext.m_isFlowSuppressed)
{
executionContext = null;
}
return executionContext;
}
private ExecutionContext ShallowClone(bool isFlowSuppressed)
{
Debug.Assert(isFlowSuppressed != m_isFlowSuppressed);
if (m_localValues == null || AsyncLocalValueMap.IsEmpty(m_localValues))
{
return isFlowSuppressed ?
DefaultFlowSuppressed :
null; // implies the default context
}
return new ExecutionContext(m_localValues, m_localChangeNotifications, isFlowSuppressed);
}
public static AsyncFlowControl SuppressFlow()
{
Thread currentThread = Thread.CurrentThread;
ExecutionContext executionContext = currentThread._executionContext ?? Default;
if (executionContext.m_isFlowSuppressed)
{
throw new InvalidOperationException(SR.InvalidOperation_CannotSupressFlowMultipleTimes);
}
executionContext = executionContext.ShallowClone(isFlowSuppressed: true);
var asyncFlowControl = new AsyncFlowControl();
currentThread._executionContext = executionContext;
asyncFlowControl.Initialize(currentThread);
return asyncFlowControl;
}
public static void RestoreFlow()
{
Thread currentThread = Thread.CurrentThread;
ExecutionContext executionContext = currentThread._executionContext;
if (executionContext == null || !executionContext.m_isFlowSuppressed)
{
throw new InvalidOperationException(SR.InvalidOperation_CannotRestoreUnsupressedFlow);
}
currentThread._executionContext = executionContext.ShallowClone(isFlowSuppressed: false);
}
public static bool IsFlowSuppressed()
{
ExecutionContext executionContext = Thread.CurrentThread._executionContext;
return executionContext != null && executionContext.m_isFlowSuppressed;
}
internal bool HasChangeNotifications => m_localChangeNotifications != null;
internal bool IsDefault => m_isDefault;
public static void Run(ExecutionContext executionContext, ContextCallback callback, object state)
{
// Note: ExecutionContext.Run is an extremely hot function and used by every await, ThreadPool execution, etc.
if (executionContext == null)
{
ThrowNullContext();
}
RunInternal(executionContext, callback, state);
}
internal static void RunInternal(ExecutionContext executionContext, ContextCallback callback, object state)
{
// Note: ExecutionContext.RunInternal is an extremely hot function and used by every await, ThreadPool execution, etc.
// Note: Manual enregistering may be addressed by "Exception Handling Write Through Optimization"
// https://github.com/dotnet/coreclr/blob/master/Documentation/design-docs/eh-writethru.md
// Enregister variables with 0 post-fix so they can be used in registers without EH forcing them to stack
// Capture references to Thread Contexts
Thread currentThread0 = Thread.CurrentThread;
Thread currentThread = currentThread0;
ExecutionContext previousExecutionCtx0 = currentThread0._executionContext;
if (previousExecutionCtx0 != null && previousExecutionCtx0.m_isDefault)
{
// Default is a null ExecutionContext internally
previousExecutionCtx0 = null;
}
// Store current ExecutionContext and SynchronizationContext as "previousXxx".
// This allows us to restore them and undo any Context changes made in callback.Invoke
// so that they won't "leak" back into caller.
// These variables will cross EH so be forced to stack
ExecutionContext previousExecutionCtx = previousExecutionCtx0;
SynchronizationContext previousSyncCtx = currentThread0._synchronizationContext;
if (executionContext != null && executionContext.m_isDefault)
{
// Default is a null ExecutionContext internally
executionContext = null;
}
if (previousExecutionCtx0 != executionContext)
{
RestoreChangedContextToThread(currentThread0, executionContext, previousExecutionCtx0);
}
ExceptionDispatchInfo edi = null;
try
{
callback.Invoke(state);
}
catch (Exception ex)
{
// Note: we have a "catch" rather than a "finally" because we want
// to stop the first pass of EH here. That way we can restore the previous
// context before any of our callers' EH filters run.
edi = ExceptionDispatchInfo.Capture(ex);
}
// Re-enregistrer variables post EH with 1 post-fix so they can be used in registers rather than from stack
SynchronizationContext previousSyncCtx1 = previousSyncCtx;
Thread currentThread1 = currentThread;
// The common case is that these have not changed, so avoid the cost of a write barrier if not needed.
if (currentThread1._synchronizationContext != previousSyncCtx1)
{
// Restore changed SynchronizationContext back to previous
currentThread1._synchronizationContext = previousSyncCtx1;
}
ExecutionContext previousExecutionCtx1 = previousExecutionCtx;
ExecutionContext currentExecutionCtx1 = currentThread1._executionContext;
if (currentExecutionCtx1 != previousExecutionCtx1)
{
RestoreChangedContextToThread(currentThread1, previousExecutionCtx1, currentExecutionCtx1);
}
// If exception was thrown by callback, rethrow it now original contexts are restored
edi?.Throw();
}
// Direct copy of the above RunInternal overload, except that it passes the state into the callback strongly-typed and by ref.
internal static void RunInternal<TState>(ExecutionContext executionContext, ContextCallback<TState> callback, ref TState state)
{
// Note: ExecutionContext.RunInternal is an extremely hot function and used by every await, ThreadPool execution, etc.
// Note: Manual enregistering may be addressed by "Exception Handling Write Through Optimization"
// https://github.com/dotnet/coreclr/blob/master/Documentation/design-docs/eh-writethru.md
// Enregister variables with 0 post-fix so they can be used in registers without EH forcing them to stack
// Capture references to Thread Contexts
Thread currentThread0 = Thread.CurrentThread;
Thread currentThread = currentThread0;
ExecutionContext previousExecutionCtx0 = currentThread0._executionContext;
if (previousExecutionCtx0 != null && previousExecutionCtx0.m_isDefault)
{
// Default is a null ExecutionContext internally
previousExecutionCtx0 = null;
}
// Store current ExecutionContext and SynchronizationContext as "previousXxx".
// This allows us to restore them and undo any Context changes made in callback.Invoke
// so that they won't "leak" back into caller.
// These variables will cross EH so be forced to stack
ExecutionContext previousExecutionCtx = previousExecutionCtx0;
SynchronizationContext previousSyncCtx = currentThread0._synchronizationContext;
if (executionContext != null && executionContext.m_isDefault)
{
// Default is a null ExecutionContext internally
executionContext = null;
}
if (previousExecutionCtx0 != executionContext)
{
RestoreChangedContextToThread(currentThread0, executionContext, previousExecutionCtx0);
}
ExceptionDispatchInfo edi = null;
try
{
callback.Invoke(ref state);
}
catch (Exception ex)
{
// Note: we have a "catch" rather than a "finally" because we want
// to stop the first pass of EH here. That way we can restore the previous
// context before any of our callers' EH filters run.
edi = ExceptionDispatchInfo.Capture(ex);
}
// Re-enregistrer variables post EH with 1 post-fix so they can be used in registers rather than from stack
SynchronizationContext previousSyncCtx1 = previousSyncCtx;
Thread currentThread1 = currentThread;
// The common case is that these have not changed, so avoid the cost of a write barrier if not needed.
if (currentThread1._synchronizationContext != previousSyncCtx1)
{
// Restore changed SynchronizationContext back to previous
currentThread1._synchronizationContext = previousSyncCtx1;
}
ExecutionContext previousExecutionCtx1 = previousExecutionCtx;
ExecutionContext currentExecutionCtx1 = currentThread1._executionContext;
if (currentExecutionCtx1 != previousExecutionCtx1)
{
RestoreChangedContextToThread(currentThread1, previousExecutionCtx1, currentExecutionCtx1);
}
// If exception was thrown by callback, rethrow it now original contexts are restored
edi?.Throw();
}
internal static void RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, object state)
{
Debug.Assert(threadPoolThread == Thread.CurrentThread);
CheckThreadPoolAndContextsAreDefault();
// ThreadPool starts on Default Context so we don't need to save the "previous" state as we know it is Default (null)
// Default is a null ExecutionContext internally
if (executionContext != null && !executionContext.m_isDefault)
{
// Non-Default context to restore
RestoreChangedContextToThread(threadPoolThread, contextToRestore: executionContext, currentContext: null);
}
ExceptionDispatchInfo edi = null;
try
{
callback.Invoke(state);
}
catch (Exception ex)
{
// Note: we have a "catch" rather than a "finally" because we want
// to stop the first pass of EH here. That way we can restore the previous
// context before any of our callers' EH filters run.
edi = ExceptionDispatchInfo.Capture(ex);
}
// Enregister threadPoolThread as it crossed EH, and use enregistered variable
Thread currentThread = threadPoolThread;
ExecutionContext currentExecutionCtx = currentThread._executionContext;
// Restore changed SynchronizationContext back to Default
currentThread._synchronizationContext = null;
if (currentExecutionCtx != null)
{
// The EC always needs to be reset for this overload, as it will flow back to the caller if it performs
// extra work prior to returning to the Dispatch loop. For example for Task-likes it will flow out of await points
RestoreChangedContextToThread(currentThread, contextToRestore: null, currentExecutionCtx);
}
// If exception was thrown by callback, rethrow it now original contexts are restored
edi?.Throw();
}
internal static void RunForThreadPoolUnsafe<TState>(ExecutionContext executionContext, Action<TState> callback, in TState state)
{
// We aren't running in try/catch as if an exception is directly thrown on the ThreadPool either process
// will crash or its a ThreadAbortException.
CheckThreadPoolAndContextsAreDefault();
Debug.Assert(executionContext != null && !executionContext.m_isDefault, "ExecutionContext argument is Default.");
// Restore Non-Default context
Thread.CurrentThread._executionContext = executionContext;
if (executionContext.HasChangeNotifications)
{
OnValuesChanged(previousExecutionCtx: null, executionContext);
}
callback.Invoke(state);
// ThreadPoolWorkQueue.Dispatch will handle notifications and reset EC and SyncCtx back to default
}
internal static void RestoreChangedContextToThread(Thread currentThread, ExecutionContext contextToRestore, ExecutionContext currentContext)
{
Debug.Assert(currentThread == Thread.CurrentThread);
Debug.Assert(contextToRestore != currentContext);
// Restore changed ExecutionContext back to previous
currentThread._executionContext = contextToRestore;
if ((currentContext != null && currentContext.HasChangeNotifications) ||
(contextToRestore != null && contextToRestore.HasChangeNotifications))
{
// There are change notifications; trigger any affected
OnValuesChanged(currentContext, contextToRestore);
}
}
// Inline as only called in one place and always called
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void ResetThreadPoolThread(Thread currentThread)
{
ExecutionContext currentExecutionCtx = currentThread._executionContext;
// Reset to defaults
currentThread._synchronizationContext = null;
currentThread._executionContext = null;
if (currentExecutionCtx != null && currentExecutionCtx.HasChangeNotifications)
{
OnValuesChanged(currentExecutionCtx, nextExecutionCtx: null);
// Reset to defaults again without change notifications in case the Change handler changed the contexts
currentThread._synchronizationContext = null;
currentThread._executionContext = null;
}
}
[System.Diagnostics.Conditional("DEBUG")]
internal static void CheckThreadPoolAndContextsAreDefault()
{
Debug.Assert(Thread.CurrentThread.IsThreadPoolThread);
Debug.Assert(Thread.CurrentThread._executionContext == null, "ThreadPool thread not on Default ExecutionContext.");
Debug.Assert(Thread.CurrentThread._synchronizationContext == null, "ThreadPool thread not on Default SynchronizationContext.");
}
internal static void OnValuesChanged(ExecutionContext previousExecutionCtx, ExecutionContext nextExecutionCtx)
{
Debug.Assert(previousExecutionCtx != nextExecutionCtx);
// Collect Change Notifications
IAsyncLocal[] previousChangeNotifications = previousExecutionCtx?.m_localChangeNotifications;
IAsyncLocal[] nextChangeNotifications = nextExecutionCtx?.m_localChangeNotifications;
// At least one side must have notifications
Debug.Assert(previousChangeNotifications != null || nextChangeNotifications != null);
// Fire Change Notifications
try
{
if (previousChangeNotifications != null && nextChangeNotifications != null)
{
// Notifications can't exist without values
Debug.Assert(previousExecutionCtx.m_localValues != null);
Debug.Assert(nextExecutionCtx.m_localValues != null);
// Both contexts have change notifications, check previousExecutionCtx first
foreach (IAsyncLocal local in previousChangeNotifications)
{
previousExecutionCtx.m_localValues.TryGetValue(local, out object previousValue);
nextExecutionCtx.m_localValues.TryGetValue(local, out object currentValue);
if (previousValue != currentValue)
{
local.OnValueChanged(previousValue, currentValue, contextChanged: true);
}
}
if (nextChangeNotifications != previousChangeNotifications)
{
// Check for additional notifications in nextExecutionCtx
foreach (IAsyncLocal local in nextChangeNotifications)
{
// If the local has a value in the previous context, we already fired the event
// for that local in the code above.
if (!previousExecutionCtx.m_localValues.TryGetValue(local, out object previousValue))
{
nextExecutionCtx.m_localValues.TryGetValue(local, out object currentValue);
if (previousValue != currentValue)
{
local.OnValueChanged(previousValue, currentValue, contextChanged: true);
}
}
}
}
}
else if (previousChangeNotifications != null)
{
// Notifications can't exist without values
Debug.Assert(previousExecutionCtx.m_localValues != null);
// No current values, so just check previous against null
foreach (IAsyncLocal local in previousChangeNotifications)
{
previousExecutionCtx.m_localValues.TryGetValue(local, out object previousValue);
if (previousValue != null)
{
local.OnValueChanged(previousValue, null, contextChanged: true);
}
}
}
else // Implied: nextChangeNotifications != null
{
// Notifications can't exist without values
Debug.Assert(nextExecutionCtx.m_localValues != null);
// No previous values, so just check current against null
foreach (IAsyncLocal local in nextChangeNotifications)
{
nextExecutionCtx.m_localValues.TryGetValue(local, out object currentValue);
if (currentValue != null)
{
local.OnValueChanged(null, currentValue, contextChanged: true);
}
}
}
}
catch (Exception ex)
{
Environment.FailFast(
SR.ExecutionContext_ExceptionInAsyncLocalNotification,
ex);
}
}
[StackTraceHidden]
private static void ThrowNullContext()
{
throw new InvalidOperationException(SR.InvalidOperation_NullContext);
}
internal static object GetLocalValue(IAsyncLocal local)
{
ExecutionContext current = Thread.CurrentThread._executionContext;
if (current == null)
{
return null;
}
current.m_localValues.TryGetValue(local, out object value);
return value;
}
internal static void SetLocalValue(IAsyncLocal local, object newValue, bool needChangeNotifications)
{
ExecutionContext current = Thread.CurrentThread._executionContext;
object previousValue = null;
bool hadPreviousValue = false;
if (current != null)
{
hadPreviousValue = current.m_localValues.TryGetValue(local, out previousValue);
}
if (previousValue == newValue)
{
return;
}
// Regarding 'treatNullValueAsNonexistent: !needChangeNotifications' below:
// - When change notifications are not necessary for this IAsyncLocal, there is no observable difference between
// storing a null value and removing the IAsyncLocal from 'm_localValues'
// - When change notifications are necessary for this IAsyncLocal, the IAsyncLocal's absence in 'm_localValues'
// indicates that this is the first value change for the IAsyncLocal and it needs to be registered for change
// notifications. So in this case, a null value must be stored in 'm_localValues' to indicate that the IAsyncLocal
// is already registered for change notifications.
IAsyncLocal[] newChangeNotifications = null;
IAsyncLocalValueMap newValues;
bool isFlowSuppressed = false;
if (current != null)
{
isFlowSuppressed = current.m_isFlowSuppressed;
newValues = current.m_localValues.Set(local, newValue, treatNullValueAsNonexistent: !needChangeNotifications);
newChangeNotifications = current.m_localChangeNotifications;
}
else
{
// First AsyncLocal
newValues = AsyncLocalValueMap.Create(local, newValue, treatNullValueAsNonexistent: !needChangeNotifications);
}
//
// Either copy the change notification array, or create a new one, depending on whether we need to add a new item.
//
if (needChangeNotifications)
{
if (hadPreviousValue)
{
Debug.Assert(newChangeNotifications != null);
Debug.Assert(Array.IndexOf(newChangeNotifications, local) >= 0);
}
else if (newChangeNotifications == null)
{
newChangeNotifications = new IAsyncLocal[1] { local };
}
else
{
int newNotificationIndex = newChangeNotifications.Length;
Array.Resize(ref newChangeNotifications, newNotificationIndex + 1);
newChangeNotifications[newNotificationIndex] = local;
}
}
Thread.CurrentThread._executionContext =
(!isFlowSuppressed && AsyncLocalValueMap.IsEmpty(newValues)) ?
null : // No values, return to Default context
new ExecutionContext(newValues, newChangeNotifications, isFlowSuppressed);
if (needChangeNotifications)
{
local.OnValueChanged(previousValue, newValue, contextChanged: false);
}
}
public ExecutionContext CreateCopy()
{
return this; // since CoreCLR's ExecutionContext is immutable, we don't need to create copies.
}
public void Dispose()
{
// For CLR compat only
}
}
public struct AsyncFlowControl : IDisposable
{
private Thread _thread;
internal void Initialize(Thread currentThread)
{
Debug.Assert(currentThread == Thread.CurrentThread);
_thread = currentThread;
}
public void Undo()
{
if (_thread == null)
{
throw new InvalidOperationException(SR.InvalidOperation_CannotUseAFCMultiple);
}
if (Thread.CurrentThread != _thread)
{
throw new InvalidOperationException(SR.InvalidOperation_CannotUseAFCOtherThread);
}
// An async flow control cannot be undone when a different execution context is applied. The desktop framework
// mutates the execution context when its state changes, and only changes the instance when an execution context
// is applied (for instance, through ExecutionContext.Run). The framework prevents a suppressed-flow execution
// context from being applied by returning null from ExecutionContext.Capture, so the only type of execution
// context that can be applied is one whose flow is not suppressed. After suppressing flow and changing an async
// local's value, the desktop framework verifies that a different execution context has not been applied by
// checking the execution context instance against the one saved from when flow was suppressed. In .NET Core,
// since the execution context instance will change after changing the async local's value, it verifies that a
// different execution context has not been applied, by instead ensuring that the current execution context's
// flow is suppressed.
if (!ExecutionContext.IsFlowSuppressed())
{
throw new InvalidOperationException(SR.InvalidOperation_AsyncFlowCtrlCtxMismatch);
}
_thread = null;
ExecutionContext.RestoreFlow();
}
public void Dispose()
{
Undo();
}
public override bool Equals(object obj)
{
return obj is AsyncFlowControl && Equals((AsyncFlowControl)obj);
}
public bool Equals(AsyncFlowControl obj)
{
return _thread == obj._thread;
}
public override int GetHashCode()
{
return _thread?.GetHashCode() ?? 0;
}
public static bool operator ==(AsyncFlowControl a, AsyncFlowControl b)
{
return a.Equals(b);
}
public static bool operator !=(AsyncFlowControl a, AsyncFlowControl b)
{
return !(a == b);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using Abp;
using Abp.Configuration.Startup;
using Abp.Domain.Uow;
using Abp.Runtime.Session;
using Abp.TestBase;
using AbpCompanyName.AbpProjectName.EntityFramework;
using AbpCompanyName.AbpProjectName.Migrations.SeedData;
using AbpCompanyName.AbpProjectName.MultiTenancy;
using AbpCompanyName.AbpProjectName.Users;
using Castle.MicroKernel.Registration;
using Effort;
using EntityFramework.DynamicFilters;
namespace AbpCompanyName.AbpProjectName.Tests
{
public abstract class AbpProjectNameTestBase : AbpIntegratedTestBase<AbpProjectNameTestModule>
{
private DbConnection _hostDb;
private Dictionary<int, DbConnection> _tenantDbs; //only used for db per tenant architecture
protected AbpProjectNameTestBase()
{
//Seed initial data for host
AbpSession.TenantId = null;
UsingDbContext(context =>
{
new InitialHostDbBuilder(context).Create();
new DefaultTenantCreator(context).Create();
});
//Seed initial data for default tenant
AbpSession.TenantId = 1;
UsingDbContext(context =>
{
new TenantRoleAndUserBuilder(context, 1).Create();
});
LoginAsDefaultTenantAdmin();
}
protected override void PreInitialize()
{
base.PreInitialize();
/* You can switch database architecture here: */
UseSingleDatabase();
//UseDatabasePerTenant();
}
/* Uses single database for host and all tenants.
*/
private void UseSingleDatabase()
{
_hostDb = DbConnectionFactory.CreateTransient();
LocalIocManager.IocContainer.Register(
Component.For<DbConnection>()
.UsingFactoryMethod(() => _hostDb)
.LifestyleSingleton()
);
}
/* Uses single database for host and Default tenant,
* but dedicated databases for all other tenants.
*/
private void UseDatabasePerTenant()
{
_hostDb = DbConnectionFactory.CreateTransient();
_tenantDbs = new Dictionary<int, DbConnection>();
LocalIocManager.IocContainer.Register(
Component.For<DbConnection>()
.UsingFactoryMethod((kernel) =>
{
lock (_tenantDbs)
{
var currentUow = kernel.Resolve<ICurrentUnitOfWorkProvider>().Current;
var abpSession = kernel.Resolve<IAbpSession>();
var tenantId = currentUow != null ? currentUow.GetTenantId() : abpSession.TenantId;
if (tenantId == null || tenantId == 1) //host and default tenant are stored in host db
{
return _hostDb;
}
if (!_tenantDbs.ContainsKey(tenantId.Value))
{
_tenantDbs[tenantId.Value] = DbConnectionFactory.CreateTransient();
}
return _tenantDbs[tenantId.Value];
}
}, true)
.LifestyleTransient()
);
}
#region UsingDbContext
protected IDisposable UsingTenantId(int? tenantId)
{
var previousTenantId = AbpSession.TenantId;
AbpSession.TenantId = tenantId;
return new DisposeAction(() => AbpSession.TenantId = previousTenantId);
}
protected void UsingDbContext(Action<AbpProjectNameDbContext> action)
{
UsingDbContext(AbpSession.TenantId, action);
}
protected Task UsingDbContextAsync(Func<AbpProjectNameDbContext, Task> action)
{
return UsingDbContextAsync(AbpSession.TenantId, action);
}
protected T UsingDbContext<T>(Func<AbpProjectNameDbContext, T> func)
{
return UsingDbContext(AbpSession.TenantId, func);
}
protected Task<T> UsingDbContextAsync<T>(Func<AbpProjectNameDbContext, Task<T>> func)
{
return UsingDbContextAsync(AbpSession.TenantId, func);
}
protected void UsingDbContext(int? tenantId, Action<AbpProjectNameDbContext> action)
{
using (UsingTenantId(tenantId))
{
using (var context = LocalIocManager.Resolve<AbpProjectNameDbContext>())
{
context.DisableAllFilters();
action(context);
context.SaveChanges();
}
}
}
protected async Task UsingDbContextAsync(int? tenantId, Func<AbpProjectNameDbContext, Task> action)
{
using (UsingTenantId(tenantId))
{
using (var context = LocalIocManager.Resolve<AbpProjectNameDbContext>())
{
context.DisableAllFilters();
await action(context);
await context.SaveChangesAsync();
}
}
}
protected T UsingDbContext<T>(int? tenantId, Func<AbpProjectNameDbContext, T> func)
{
T result;
using (UsingTenantId(tenantId))
{
using (var context = LocalIocManager.Resolve<AbpProjectNameDbContext>())
{
context.DisableAllFilters();
result = func(context);
context.SaveChanges();
}
}
return result;
}
protected async Task<T> UsingDbContextAsync<T>(int? tenantId, Func<AbpProjectNameDbContext, Task<T>> func)
{
T result;
using (UsingTenantId(tenantId))
{
using (var context = LocalIocManager.Resolve<AbpProjectNameDbContext>())
{
context.DisableAllFilters();
result = await func(context);
await context.SaveChangesAsync();
}
}
return result;
}
#endregion
#region Login
protected void LoginAsHostAdmin()
{
LoginAsHost(User.AdminUserName);
}
protected void LoginAsDefaultTenantAdmin()
{
LoginAsTenant(Tenant.DefaultTenantName, User.AdminUserName);
}
protected void LoginAsHost(string userName)
{
Resolve<IMultiTenancyConfig>().IsEnabled = true;
AbpSession.TenantId = null;
var user =
UsingDbContext(
context =>
context.Users.FirstOrDefault(u => u.TenantId == AbpSession.TenantId && u.UserName == userName));
if (user == null)
{
throw new Exception("There is no user: " + userName + " for host.");
}
AbpSession.UserId = user.Id;
}
protected void LoginAsTenant(string tenancyName, string userName)
{
var tenant = UsingDbContext(context => context.Tenants.FirstOrDefault(t => t.TenancyName == tenancyName));
if (tenant == null)
{
throw new Exception("There is no tenant: " + tenancyName);
}
AbpSession.TenantId = tenant.Id;
var user =
UsingDbContext(
context =>
context.Users.FirstOrDefault(u => u.TenantId == AbpSession.TenantId && u.UserName == userName));
if (user == null)
{
throw new Exception("There is no user: " + userName + " for tenant: " + tenancyName);
}
AbpSession.UserId = user.Id;
}
#endregion
/// <summary>
/// Gets current user if <see cref="IAbpSession.UserId"/> is not null.
/// Throws exception if it's null.
/// </summary>
protected async Task<User> GetCurrentUserAsync()
{
var userId = AbpSession.GetUserId();
return await UsingDbContext(context => context.Users.SingleAsync(u => u.Id == userId));
}
/// <summary>
/// Gets current tenant if <see cref="IAbpSession.TenantId"/> is not null.
/// Throws exception if there is no current tenant.
/// </summary>
protected async Task<Tenant> GetCurrentTenantAsync()
{
var tenantId = AbpSession.GetTenantId();
return await UsingDbContext(context => context.Tenants.SingleAsync(t => t.Id == tenantId));
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
namespace UMA
{
/// <summary>
/// Default mesh combiner for UMA UMAMeshdata from slots.
/// </summary>
public class UMADefaultMeshCombiner : UMAMeshCombiner
{
protected List<SkinnedMeshCombiner.CombineInstance> combinedMeshList;
protected List<Material> combinedMaterialList;
UMAData umaData;
int atlasResolution;
private UMAClothProperties clothProperties;
int currentRendererIndex;
SkinnedMeshRenderer[] renderers;
protected void EnsureUMADataSetup(UMAData umaData)
{
if (umaData.umaRoot == null)
{
GameObject newRoot = new GameObject("Root");
//make root of the UMAAvatar respect the layer setting of the UMAAvatar so cameras can just target this layer
newRoot.layer = umaData.gameObject.layer;
newRoot.transform.parent = umaData.transform;
newRoot.transform.localPosition = Vector3.zero;
newRoot.transform.localRotation = Quaternion.Euler(270f, 0, 0f);
newRoot.transform.localScale = Vector3.one;
umaData.umaRoot = newRoot;
GameObject newGlobal = new GameObject("Global");
newGlobal.transform.parent = newRoot.transform;
newGlobal.transform.localPosition = Vector3.zero;
newGlobal.transform.localRotation = Quaternion.Euler(90f, 90f, 0f);
umaData.skeleton = new UMASkeleton(newGlobal.transform);
renderers = new SkinnedMeshRenderer[umaData.generatedMaterials.rendererCount];
for (int i = 0; i < umaData.generatedMaterials.rendererCount; i++)
{
renderers[i] = MakeRenderer(i, newGlobal.transform);
}
umaData.SetRenderers(renderers);
}
else
{
umaData.CleanMesh(false);
if (umaData.rendererCount == umaData.generatedMaterials.rendererCount)
{
renderers = umaData.GetRenderers();
}
else
{
var oldRenderers = umaData.GetRenderers();
var globalTransform = umaData.GetGlobalTransform();
renderers = new SkinnedMeshRenderer[umaData.generatedMaterials.rendererCount];
for (int i = 0; i < umaData.generatedMaterials.rendererCount; i++)
{
if (oldRenderers != null && oldRenderers.Length > i)
{
renderers[i] = oldRenderers[i];
continue;
}
renderers[i] = MakeRenderer(i, globalTransform);
}
if (oldRenderers != null)
{
for (int i = umaData.generatedMaterials.rendererCount; i < oldRenderers.Length; i++)
{
UMAUtils.DestroySceneObject(oldRenderers[i].gameObject);
//For cloth, be aware of issue: 845868
//https://issuetracker.unity3d.com/issues/cloth-repeatedly-destroying-objects-with-cloth-components-causes-a-crash-in-unity-cloth-updatenormals
}
}
umaData.SetRenderers(renderers);
}
}
//Clear out old cloth components
for (int i = 0; i < umaData.rendererCount; i++)
{
Cloth cloth = renderers[i].GetComponent<Cloth>();
if (cloth != null)
DestroyImmediate(cloth,false); //Crashes if trying to use Destroy()
}
}
private SkinnedMeshRenderer MakeRenderer(int i, Transform rootBone)
{
GameObject newSMRGO = new GameObject(i == 0 ? "UMARenderer" : ("UMARenderer " + i));
newSMRGO.transform.parent = umaData.transform;
newSMRGO.transform.localPosition = Vector3.zero;
newSMRGO.transform.localRotation = Quaternion.Euler(0, 0, 0f);
newSMRGO.transform.localScale = Vector3.one;
newSMRGO.gameObject.layer = umaData.gameObject.layer;
var newRenderer = newSMRGO.AddComponent<SkinnedMeshRenderer>();
newRenderer.enabled = false;
newRenderer.sharedMesh = new Mesh();
newRenderer.rootBone = rootBone;
newRenderer.quality = SkinQuality.Bone4;
newRenderer.sharedMesh.name = i == 0 ? "UMAMesh" : ("UMAMesh " + i);
return newRenderer;
}
/// <summary>
/// Updates the UMA mesh and skeleton to match current slots.
/// </summary>
/// <param name="updatedAtlas">If set to <c>true</c> atlas has changed.</param>
/// <param name="umaData">UMA data.</param>
/// <param name="atlasResolution">Atlas resolution.</param>
public override void UpdateUMAMesh(bool updatedAtlas, UMAData umaData, int atlasResolution)
{
this.umaData = umaData;
this.atlasResolution = atlasResolution;
combinedMeshList = new List<SkinnedMeshCombiner.CombineInstance>(umaData.umaRecipe.slotDataList.Length);
combinedMaterialList = new List<Material>();
EnsureUMADataSetup(umaData);
umaData.skeleton.BeginSkeletonUpdate();
for (currentRendererIndex = 0; currentRendererIndex < umaData.generatedMaterials.rendererCount; currentRendererIndex++)
{
//Move umaMesh creation to with in the renderer loops
//May want to make sure to set all it's buffers to null instead of creating a new UMAMeshData
UMAMeshData umaMesh = new UMAMeshData();
umaMesh.ClaimSharedBuffers();
umaMesh.subMeshCount = 0;
umaMesh.vertexCount = 0;
combinedMeshList.Clear();
combinedMaterialList.Clear();
clothProperties = null;
BuildCombineInstances();
if (combinedMeshList.Count == 1)
{
// fast track
var tempMesh = SkinnedMeshCombiner.ShallowInstanceMesh(combinedMeshList[0].meshData);
tempMesh.ApplyDataToUnityMesh(renderers[currentRendererIndex], umaData.skeleton);
}
else
{
SkinnedMeshCombiner.CombineMeshes(umaMesh, combinedMeshList.ToArray(), umaData.blendShapeSettings );
if (updatedAtlas)
{
RecalculateUV(umaMesh);
}
umaMesh.ApplyDataToUnityMesh(renderers[currentRendererIndex], umaData.skeleton);
}
var cloth = renderers[currentRendererIndex].GetComponent<Cloth>();
if (clothProperties != null)
{
if (cloth != null)
{
clothProperties.ApplyValues(cloth);
}
}
else
{
UMAUtils.DestroySceneObject(cloth);
}
var materials = combinedMaterialList.ToArray();
renderers[currentRendererIndex].sharedMaterials = materials;
umaMesh.ReleaseSharedBuffers();
}
umaData.umaRecipe.ClearDNAConverters();
for (int i = 0; i < umaData.umaRecipe.slotDataList.Length; i++)
{
SlotData slotData = umaData.umaRecipe.slotDataList[i];
if (slotData != null)
{
umaData.umaRecipe.AddDNAUpdater(slotData.asset.slotDNA);
}
}
umaData.firstBake = false;
}
protected void BuildCombineInstances()
{
SkinnedMeshCombiner.CombineInstance combineInstance;
//Since BuildCombineInstances is called within a renderer loop, use a variable to keep track of the materialIndex per renderer
int rendererMaterialIndex = 0;
for (int materialIndex = 0; materialIndex < umaData.generatedMaterials.materials.Count; materialIndex++)
{
var generatedMaterial = umaData.generatedMaterials.materials[materialIndex];
if (generatedMaterial.renderer != currentRendererIndex)
continue;
combinedMaterialList.Add(generatedMaterial.material);
for (int materialDefinitionIndex = 0; materialDefinitionIndex < generatedMaterial.materialFragments.Count; materialDefinitionIndex++)
{
var materialDefinition = generatedMaterial.materialFragments[materialDefinitionIndex];
var slotData = materialDefinition.slotData;
combineInstance = new SkinnedMeshCombiner.CombineInstance();
combineInstance.meshData = slotData.asset.meshData;
combineInstance.targetSubmeshIndices = new int[combineInstance.meshData.subMeshCount];
for (int i = 0; i < combineInstance.meshData.subMeshCount; i++)
{
combineInstance.targetSubmeshIndices[i] = -1;
}
combineInstance.targetSubmeshIndices[slotData.asset.subMeshIndex] = rendererMaterialIndex;
combinedMeshList.Add(combineInstance);
if (slotData.asset.SlotAtlassed != null)
{
slotData.asset.SlotAtlassed.Invoke(umaData, slotData, generatedMaterial.material, materialDefinition.atlasRegion);
}
if (slotData.asset.material.clothProperties != null)
{
clothProperties = slotData.asset.material.clothProperties;
}
}
rendererMaterialIndex++;
}
}
protected void RecalculateUV(UMAMeshData umaMesh)
{
int idx = 0;
//Handle Atlassed Verts
for (int materialIndex = 0; materialIndex < umaData.generatedMaterials.materials.Count; materialIndex++)
{
var generatedMaterial = umaData.generatedMaterials.materials[materialIndex];
if (generatedMaterial.renderer != currentRendererIndex)
continue;
if (generatedMaterial.umaMaterial.materialType != UMAMaterial.MaterialType.Atlas)
{
var fragment = generatedMaterial.materialFragments[0];
int vertexCount = fragment.slotData.asset.meshData.vertices.Length;
idx += vertexCount;
continue;
}
for (int materialDefinitionIndex = 0; materialDefinitionIndex < generatedMaterial.materialFragments.Count; materialDefinitionIndex++)
{
var fragment = generatedMaterial.materialFragments[materialDefinitionIndex];
var tempAtlasRect = fragment.atlasRegion;
int vertexCount = fragment.slotData.asset.meshData.vertices.Length;
float atlasXMin = tempAtlasRect.xMin / atlasResolution;
float atlasXMax = tempAtlasRect.xMax / atlasResolution;
float atlasXRange = atlasXMax - atlasXMin;
float atlasYMin = tempAtlasRect.yMin / atlasResolution;
float atlasYMax = tempAtlasRect.yMax / atlasResolution;
float atlasYRange = atlasYMax - atlasYMin;
while (vertexCount-- > 0)
{
umaMesh.uv[idx].x = atlasXMin + atlasXRange * umaMesh.uv[idx].x;
umaMesh.uv[idx].y = atlasYMin + atlasYRange * umaMesh.uv[idx].y;
idx++;
}
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace System.IO
{
/// <summary>
/// Provides a string parser that may be used instead of String.Split
/// to avoid unnecessary string and array allocations.
/// </summary>
internal struct StringParser
{
/// <summary>The string being parsed.</summary>
private readonly string _buffer;
/// <summary>The separator character used to separate subcomponents of the larger string.</summary>
private readonly char _separator;
/// <summary>true if empty subcomponents should be skipped; false to treat them as valid entries.</summary>
private readonly bool _skipEmpty;
/// <summary>The starting index from which to parse the current entry.</summary>
private int _startIndex;
/// <summary>The ending index that represents the next index after the last character that's part of the current entry.</summary>
private int _endIndex;
/// <summary>Initialize the StringParser.</summary>
/// <param name="buffer">The string to parse.</param>
/// <param name="separator">The separator character used to separate subcomponents of <paramref name="buffer"/>.</param>
/// <param name="skipEmpty">true if empty subcomponents should be skipped; false to treat them as valid entries. Defaults to false.</param>
public StringParser(string buffer, char separator, bool skipEmpty = false)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
_buffer = buffer;
_separator = separator;
_skipEmpty = skipEmpty;
_startIndex = -1;
_endIndex = -1;
}
/// <summary>Moves to the next component of the string.</summary>
/// <returns>true if there is a next component to be parsed; otherwise, false.</returns>
public bool MoveNext()
{
if (_buffer == null)
{
throw new InvalidOperationException();
}
while (true)
{
if (_endIndex >= _buffer.Length)
{
_startIndex = _endIndex;
return false;
}
int nextSeparator = _buffer.IndexOf(_separator, _endIndex + 1);
_startIndex = _endIndex + 1;
_endIndex = nextSeparator >= 0 ? nextSeparator : _buffer.Length;
if (!_skipEmpty || _endIndex > _startIndex + 1)
{
return true;
}
}
}
/// <summary>
/// Moves to the next component of the string. If there isn't one, it throws an exception.
/// </summary>
public void MoveNextOrFail()
{
if (!MoveNext())
{
ThrowForInvalidData();
}
}
/// <summary>
/// Moves to the next component of the string and returns it as a string.
/// </summary>
/// <returns></returns>
public string MoveAndExtractNext()
{
MoveNextOrFail();
return _buffer.Substring(_startIndex, _endIndex - _startIndex);
}
/// <summary>
/// Gets the current subcomponent of the string as a string.
/// </summary>
public string ExtractCurrent()
{
if (_buffer == null || _startIndex == -1)
{
throw new InvalidOperationException();
}
return _buffer.Substring(_startIndex, _endIndex - _startIndex);
}
/// <summary>Moves to the next component and parses it as an Int32.</summary>
public unsafe int ParseNextInt32()
{
MoveNextOrFail();
bool negative = false;
int result = 0;
fixed (char* bufferPtr = _buffer)
{
char* p = bufferPtr + _startIndex;
char* end = bufferPtr + _endIndex;
if (p == end)
{
ThrowForInvalidData();
}
if (*p == '-')
{
negative = true;
p++;
if (p == end)
{
ThrowForInvalidData();
}
}
while (p != end)
{
int d = *p - '0';
if (d < 0 || d > 9)
{
ThrowForInvalidData();
}
result = checked((result * 10) + d);
p++;
}
}
if (negative)
{
result *= -1;
}
Debug.Assert(result == int.Parse(ExtractCurrent()), "Expected manually parsed result to match Parse result");
return result;
}
/// <summary>Moves to the next component and parses it as an Int64.</summary>
public unsafe long ParseNextInt64()
{
MoveNextOrFail();
bool negative = false;
long result = 0;
fixed (char* bufferPtr = _buffer)
{
char* p = bufferPtr + _startIndex;
char* end = bufferPtr + _endIndex;
if (p == end)
{
ThrowForInvalidData();
}
if (*p == '-')
{
negative = true;
p++;
if (p == end)
{
ThrowForInvalidData();
}
}
while (p != end)
{
int d = *p - '0';
if (d < 0 || d > 9)
{
ThrowForInvalidData();
}
result = checked((result * 10) + d);
p++;
}
}
if (negative)
{
result *= -1;
}
Debug.Assert(result == long.Parse(ExtractCurrent()), "Expected manually parsed result to match Parse result");
return result;
}
/// <summary>Moves to the next component and parses it as a UInt32.</summary>
public unsafe uint ParseNextUInt32()
{
MoveNextOrFail();
if (_startIndex == _endIndex)
{
ThrowForInvalidData();
}
uint result = 0;
fixed (char* bufferPtr = _buffer)
{
char* p = bufferPtr + _startIndex;
char* end = bufferPtr + _endIndex;
while (p != end)
{
int d = *p - '0';
if (d < 0 || d > 9)
{
ThrowForInvalidData();
}
result = (uint)checked((result * 10) + d);
p++;
}
}
Debug.Assert(result == uint.Parse(ExtractCurrent()), "Expected manually parsed result to match Parse result");
return result;
}
/// <summary>Moves to the next component and parses it as a UInt64.</summary>
public unsafe ulong ParseNextUInt64()
{
MoveNextOrFail();
ulong result = 0;
fixed (char* bufferPtr = _buffer)
{
char* p = bufferPtr + _startIndex;
char* end = bufferPtr + _endIndex;
while (p != end)
{
int d = *p - '0';
if (d < 0 || d > 9)
{
ThrowForInvalidData();
}
result = checked((result * 10ul) + (ulong)d);
p++;
}
}
Debug.Assert(result == ulong.Parse(ExtractCurrent()), "Expected manually parsed result to match Parse result");
return result;
}
/// <summary>Moves to the next component and parses it as a Char.</summary>
public char ParseNextChar()
{
MoveNextOrFail();
if (_endIndex - _startIndex != 1)
{
ThrowForInvalidData();
}
char result = _buffer[_startIndex];
Debug.Assert(result == char.Parse(ExtractCurrent()), "Expected manually parsed result to match Parse result");
return result;
}
internal delegate T ParseRawFunc<T>(string buffer, ref int startIndex, ref int endIndex);
/// <summary>
/// Moves to the next component and hands the raw buffer and indexing data to a selector function
/// that can validate and return the appropriate data from the component.
/// </summary>
internal T ParseRaw<T>(ParseRawFunc<T> selector)
{
MoveNextOrFail();
return selector(_buffer, ref _startIndex, ref _endIndex);
}
/// <summary>Throws unconditionally for invalid data.</summary>
private static void ThrowForInvalidData()
{
throw new InvalidDataException();
}
}
}
| |
/*
Copyright 2006 - 2010 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Text;
using OpenSource.UPnP;
using System.Threading;
using OpenSource.UPnP.AV;
using System.Collections;
using OpenSource.Utilities;
using OpenSource.UPnP.AV.CdsMetadata;
namespace OpenSource.UPnP.AV.MediaServer.CP
{
/// <summary>
/// This class abstracts the gory details of finding MediaServer devices.
/// The class employs a concept of a "good" server and a non-good server.
/// Good servers the ones that properly handle the subscription request
/// for both services and then properly event. All servers are considered
/// non-good until they do this. Programmers may choose to use only the
/// good servers, as it may indicate a more reliable implementation.
/// The servers are configured to virtualize only their containers.
///
/// <para>
/// It should be noted that this class has been hard-coded to
/// instantiate the root container with settings that will
/// always assume that all items and container are not to
/// be persisted, thus requiring the use of a <see cref="CdsSpider"/>
/// object to ensure that child objects are persisted as desired.
/// The basic reason for this design decision is that
/// MediaServerDiscovery should/must allow for static scenarios,
/// where multiple plug-in applications share the same global address
/// space, thus allowing a single instance of a media object to
/// be shared. Thus <see cref="MediaServerDiscovery"/>,
/// <see cref="ContainerDiscovery"/>, and all media objects become
/// shared resources across multiple applications with each
/// application using the <see cref="CdsSpider"/> object to
/// cause persistence of the items that are of interest
/// to individual applications.
/// </para>
/// </summary>
public sealed class MediaServerDiscovery
{
/// <summary>
/// Unhooks all events
/// </summary>
public void Dispose()
{
TheInstance.OnCpServerAdded -= new _MediaServerDiscovery.Delegate_OnGoodServersChange(this.Sink_OnGoodServerAdded);
TheInstance.OnCpServerRemoved -= new _MediaServerDiscovery.Delegate_OnGoodServersChange(this.Sink_OnGoodServerRemoved);
TheInstance.OnServerSeen -= new _MediaServerDiscovery.Delegate_OnServerDeviceChange(this.Sink_OnServerAdded);
TheInstance.OnServerGone -= new _MediaServerDiscovery.Delegate_OnServerDeviceChange(this.Sink_OnServerRemoved);
this.OnGoodServerAdded = null;
this.OnGoodServerRemoved = null;
this.OnServerGone = null;
this.OnServerSeen = null;
}
/// <summary>
/// This delegate is used when a MediaServer shows up or disappears.
/// Determination of whether the server is good or non-good isn't known.
/// </summary>
public delegate void Delegate_OnServerDeviceChange(MediaServerDiscovery sender, UPnPDevice device);
/// <summary>
/// This delegate is used when a good MediaServer shows up or disappears.
/// </summary>
public delegate void Delegate_OnGoodServersChange(MediaServerDiscovery sender, CpMediaServer server);
/// <summary>
/// Fired when a server shows up.
/// </summary>
public event Delegate_OnServerDeviceChange OnServerSeen;
/// <summary>
/// Fired when a server disappears.
/// </summary>
public event Delegate_OnServerDeviceChange OnServerGone;
/// <summary>
/// Fired when a good server shows up.
/// </summary>
public event Delegate_OnGoodServersChange OnGoodServerAdded;
/// <summary>
/// Fired when a good server disappears.
/// </summary>
public event Delegate_OnGoodServersChange OnGoodServerRemoved;
/// <summary>
/// Returns a shallow copy array of non-good servers.
/// </summary>
public CpMediaServer[] NonGoodServers
{
get
{
return TheInstance.NonGoodServers;
}
}
/// <summary>
/// Returns a shallow copy array of good servers.
/// </summary>
public CpMediaServer[] GoodServers
{
get
{
return TheInstance.GoodServers;
}
}
/// <summary>
/// Constructs a MediaServerDiscovery object.
/// </summary>
/// <param name="onServerAddedCallback">null, if not interested in the OnServerSeen event; otherwise adds the callback to the multicasted event</param>
/// <param name="onServerRemovedCallback">null, if not interested in the OnServerGone event; otherwise adds the callback to the multicasted event</param>
/// <param name="onGoodServerAddedCallback">null, if not interested in the OnGoodServerAdded event; strongly recommended that this is not null; otherwise adds the callback to the multicasted event</param>
/// <param name="onGoodServerRemovedCallback">null, if not interested in the OnGoodServerRemoved event; otherwise adds the callback to the multicasted event</param>
public MediaServerDiscovery
(
Delegate_OnServerDeviceChange onServerAddedCallback,
Delegate_OnServerDeviceChange onServerRemovedCallback,
Delegate_OnGoodServersChange onGoodServerAddedCallback,
Delegate_OnGoodServersChange onGoodServerRemovedCallback
)
{
if (onServerAddedCallback != null)
{
this.OnServerSeen += onServerAddedCallback;
}
if (onServerRemovedCallback != null)
{
this.OnServerGone += onServerRemovedCallback;
}
if (onGoodServerAddedCallback != null)
{
this.OnGoodServerAdded += onGoodServerAddedCallback;
}
if (onGoodServerRemovedCallback != null)
{
this.OnGoodServerRemoved += onGoodServerRemovedCallback;
}
CpMediaServer[] servers = null;
CpMediaServer[] goodServers = null;
TheLock.WaitOne();
if (TheInstance != null)
{
servers = TheInstance.GoodServers;
goodServers = TheInstance.GoodServers;
}
else
{
TheInstance = new _MediaServerDiscovery(true);
}
TheLock.ReleaseMutex();
TheInstance.OnCpServerAdded += new _MediaServerDiscovery.Delegate_OnGoodServersChange(this.Sink_OnGoodServerAdded);
TheInstance.OnCpServerRemoved += new _MediaServerDiscovery.Delegate_OnGoodServersChange(this.Sink_OnGoodServerRemoved);
TheInstance.OnServerSeen += new _MediaServerDiscovery.Delegate_OnServerDeviceChange(this.Sink_OnServerAdded);
TheInstance.OnServerGone += new _MediaServerDiscovery.Delegate_OnServerDeviceChange(this.Sink_OnServerRemoved);
if (servers != null)
{
if (this.OnServerSeen != null)
{
foreach (CpMediaServer server in servers)
{
if (servers.Length > 0)
{
this.OnServerSeen(this, server.ConnectionManager.GetUPnPService().ParentDevice);
}
}
}
}
if (goodServers != null)
{
if (this.OnGoodServerAdded != null)
{
foreach (CpMediaServer server in goodServers)
{
if (servers.Length > 0)
{
this.OnGoodServerAdded(this, server);
}
}
}
}
}
/// <summary>
/// Method executes when a server is discovered.
/// </summary>
/// <param name="sender"></param>
/// <param name="device"></param>
private void Sink_OnServerAdded (_MediaServerDiscovery sender, UPnPDevice device)
{
if(this.OnServerSeen != null)
{
this.OnServerSeen(this, device);
}
}
/// <summary>
/// Method executes when a server says BEY BYE.
/// </summary>
/// <param name="sender"></param>
/// <param name="device"></param>
private void Sink_OnServerRemoved (_MediaServerDiscovery sender, UPnPDevice device)
{
if(this.OnServerGone != null)
{
this.OnServerGone(this, device);
}
}
/// <summary>
/// Method executes when a server has been promoted to be a "good" server.
/// </summary>
/// <param name="sender"></param>
/// <param name="server"></param>
private void Sink_OnGoodServerAdded (_MediaServerDiscovery sender, CpMediaServer server)
{
if(this.OnGoodServerAdded != null)
{
this.OnGoodServerAdded(this, server);
}
}
/// <summary>
/// Method executes when a "good" server has done bye bye.
/// </summary>
/// <param name="sender"></param>
/// <param name="server"></param>
private void Sink_OnGoodServerRemoved (_MediaServerDiscovery sender, CpMediaServer server)
{
if(this.OnGoodServerRemoved != null)
{
this.OnGoodServerRemoved(this, server);
}
}
/// <summary>
/// The one and only instance.
/// </summary>
private static _MediaServerDiscovery TheInstance;
private static Mutex TheLock = new Mutex();
}
/// <summary>
/// Handles the core logic for finding MediaServerDiscovery in
/// such a way that we minimize impact by having a static list.
/// </summary>
internal sealed class _MediaServerDiscovery
{
/// <summary>
/// This delegate is used when a MediaServer shows up or disappears.
/// Determination of whether the server is good or non-good isn't known.
/// </summary>
public delegate void Delegate_OnServerDeviceChange(_MediaServerDiscovery sender, UPnPDevice device);
/// <summary>
/// This delegate is used when a good MediaServer shows up or disappears.
/// </summary>
public delegate void Delegate_OnGoodServersChange(_MediaServerDiscovery sender, CpMediaServer server);
/// <summary>
/// Fired when a server shows up.
/// </summary>
public event Delegate_OnServerDeviceChange OnServerSeen;
/// <summary>
/// Fired when a server disappears.
/// </summary>
public event Delegate_OnServerDeviceChange OnServerGone;
/// <summary>
/// Fired when a good server shows up.
/// </summary>
public event Delegate_OnGoodServersChange OnCpServerAdded;
/// <summary>
/// Fired when a good server disappears.
/// </summary>
public event Delegate_OnGoodServersChange OnCpServerRemoved;
/// <summary>
/// Returns an array of non-good servers.
/// </summary>
public CpMediaServer[] NonGoodServers
{
get
{
CpMediaServer[] results = null;
lock (LockHashes)
{
ICollection servers = UdnToInitStatus.Values;
results = new CpMediaServer[servers.Count];
int i=0;
foreach (InitStatus status in servers)
{
results[i] = status.Server;
i++;
}
}
return results;
}
}
/// <summary>
/// Returns an array of good servers.
/// </summary>
public CpMediaServer[] GoodServers
{
get
{
CpMediaServer[] results = null;
lock (LockHashes)
{
ICollection servers = UdnToServer.Values;
results = new CpMediaServer[servers.Count];
int i=0;
foreach (CpMediaServer server in servers)
{
results[i] = server;
i++;
}
}
return results;
}
}
/// <summary>
/// This is the internal constructor, that basically makes it so
/// only one object is responsible for keeping track of
/// media server objects.
/// </summary>
/// <param name="readOnlyDesiredContainerState">
/// If true, then the public programmer cannot set the desired
/// state of containers, automatically causing each container
/// to virtualize only their immediate child containers.
/// </param>
internal _MediaServerDiscovery
(
bool readOnlyDesiredContainerState
)
{
m_Scp = new UPnPSmartControlPoint(
new UPnPSmartControlPoint.DeviceHandler(this.Temporary_AddServer),
null,
new string[2] { CpContentDirectory.SERVICE_NAME, CpConnectionManager.SERVICE_NAME } );
m_Scp.OnRemovedDevice += new UPnPSmartControlPoint.DeviceHandler(this.RemoveServer);
m_readOnlyDesiredState = readOnlyDesiredContainerState;
}
/// <summary>
/// Indicates if the containers have a read-only desired state.
/// If true, then all of the CpMediaContainer objects will
/// only virtualize their immediate child containers.
/// </summary>
private bool m_readOnlyDesiredState;
/// <summary>
/// Memory cleanup.
/// </summary>
public void Dispose()
{
m_Scp.OnRemovedDevice -= new UPnPSmartControlPoint.DeviceHandler(this.RemoveServer);
this.OnCpServerAdded = null;
this.OnCpServerRemoved = null;
this.OnServerGone = null;
this.OnServerSeen = null;
m_Scp = null;
}
/// <summary>
/// When a MediaServer device is found, we add it to a temp list.
/// Then we attempt to subscribe to its services.
/// </summary>
/// <param name="sender">the smart cp that found the device</param>
/// <param name="device">the mediaserver device</param>
private void Temporary_AddServer(UPnPSmartControlPoint sender, UPnPDevice device)
{
if (this.OnServerSeen != null)
{
this.OnServerSeen(this, device);
}
UPnPService sCD = device.GetServices(CpContentDirectory.SERVICE_NAME)[0];
UPnPService sCM = device.GetServices(CpConnectionManager.SERVICE_NAME)[0];
CpMediaServer newServer;
try
{
newServer = new CpMediaServer(device);
}
catch (UPnPCustomException)
{
newServer = null;
}
if (newServer != null)
{
InitStatus status = new InitStatus();
status.SubcribeCD = false;
status.SubcribeCM = false;
status.EventedCD = false;
status.EventedCM = false;
status.Server = newServer;
lock (LockHashes)
{
UdnToInitStatus[device.UniqueDeviceName] = status;
}
newServer.ConnectionManager.OnSubscribe += new CpConnectionManager.SubscribeHandler(this.Sink_OnCmServiceSubscribe);
newServer.ContentDirectory.OnSubscribe += new CpContentDirectory.SubscribeHandler(this.Sink_OnCdServiceSubscribe);
newServer.ConnectionManager.OnStateVariable_SourceProtocolInfo += new CpConnectionManager.StateVariableModifiedHandler_SourceProtocolInfo(this.Sink_OnCmEvented);
newServer.ContentDirectory.OnStateVariable_SystemUpdateID += new CpContentDirectory.StateVariableModifiedHandler_SystemUpdateID(this.Sink_OnCdEvented);
newServer.ConnectionManager._subscribe(600);
newServer.ContentDirectory._subscribe(600);
}
}
/// <summary>
/// Executes when the ContentDirectory service returns on the subscribe status.
/// </summary>
/// <param name="sender"></param>
/// <param name="success"></param>
private void Sink_OnCdServiceSubscribe(CpContentDirectory sender, bool success)
{
sender.OnSubscribe -= new CpContentDirectory.SubscribeHandler(this.Sink_OnCdServiceSubscribe);
string udn = sender.GetUPnPService().ParentDevice.UniqueDeviceName;
lock (LockHashes)
{
InitStatus status = (InitStatus) UdnToInitStatus[udn];
if (status != null)
{
status.ZeroMeansDone--;
status.SubcribeCD = success;
this.ProcessInitStatusChange(udn);
}
}
}
/// <summary>
/// Executes when the ConnectionManager service returns on the subscribe status.
/// </summary>
/// <param name="sender"></param>
/// <param name="success"></param>
private void Sink_OnCmServiceSubscribe(CpConnectionManager sender, bool success)
{
sender.OnSubscribe -= new CpConnectionManager.SubscribeHandler(this.Sink_OnCmServiceSubscribe);
string udn = sender.GetUPnPService().ParentDevice.UniqueDeviceName;
lock (LockHashes)
{
InitStatus status = (InitStatus) UdnToInitStatus[udn];
if (status != null)
{
status.ZeroMeansDone--;
status.SubcribeCM = success;
this.ProcessInitStatusChange(udn);
}
}
}
/// <summary>
/// Executes when the ContentDirectory events for the first time.
/// </summary>
/// <param name="sender"></param>
/// <param name="newVal"></param>
private void Sink_OnCdEvented (CpContentDirectory sender, UInt32 newVal)
{
sender.OnStateVariable_SystemUpdateID -= new CpContentDirectory.StateVariableModifiedHandler_SystemUpdateID(this.Sink_OnCdEvented);
string udn = sender.GetUPnPService().ParentDevice.UniqueDeviceName;
lock (LockHashes)
{
InitStatus status = (InitStatus) UdnToInitStatus[udn];
if (status != null)
{
status.ZeroMeansDone--;
status.EventedCD = true;
this.ProcessInitStatusChange(udn);
}
}
}
/// <summary>
/// Executes when the ConnectionManager events for the first time.
/// </summary>
/// <param name="sender"></param>
/// <param name="newVal"></param>
private void Sink_OnCmEvented (CpConnectionManager sender, string newVal)
{
sender.OnStateVariable_SourceProtocolInfo -= new CpConnectionManager.StateVariableModifiedHandler_SourceProtocolInfo(this.Sink_OnCmEvented);
string udn = sender.GetUPnPService().ParentDevice.UniqueDeviceName;
lock (LockHashes)
{
InitStatus status = (InitStatus) UdnToInitStatus[udn];
if (status != null)
{
status.ZeroMeansDone--;
status.EventedCM = true;
this.ProcessInitStatusChange(udn);
}
}
}
/// <summary>
/// Whenever Sink_Onxxx method executes, it calls this method to
/// determine whether a server has been upgraded from non-good
/// to good status.
/// </summary>
/// <param name="udn"></param>
private void ProcessInitStatusChange (string udn)
{
CpMediaServer addedThis = null;
InitStatus status = null;
lock (LockHashes)
{
status = (InitStatus) UdnToInitStatus[udn];
if (status != null)
{
if (status.ZeroMeansDone == 0)
{
if (
(status.EventedCD) &&
(status.EventedCM) &&
(status.SubcribeCD) &&
(status.SubcribeCM)
)
{
// We were evented for both services
// and we subscribed successfully,
// so we're good to go.
UdnToInitStatus.Remove(udn);
UdnToServer[udn] = status.Server;
addedThis = status.Server;
}
else
{
// we didn't subscribe successfully
// or we never got evented after
// we subscribed... but this
// code should never execute because
// we will have never decremented
// ZeroMeansDone==0
}
}
if (addedThis == null)
{
if (BadServersAreGoodServersToo)
{
// but since we're configured to be
// nice to crappy servers that
// don't event properly... we'll
// promote the server to full status
UdnToInitStatus.Remove(udn);
UdnToServer[udn] = status.Server;
addedThis = status.Server;
}
}
}
}
if (addedThis != null)
{
if (this.OnCpServerAdded != null)
{
this.OnCpServerAdded(this, addedThis);
}
}
}
/// <summary>
/// Method executes when smart control point notices that
/// a upnp media server has left the network.
/// </summary>
/// <param name="sender"></param>
/// <param name="device"></param>
private void RemoveServer(UPnPSmartControlPoint sender, UPnPDevice device)
{
string udn = device.UniqueDeviceName;
CpMediaServer removeThis = null;
lock (LockHashes)
{
if (UdnToInitStatus.Contains(udn))
{
InitStatus status = (InitStatus) UdnToInitStatus[udn];
}
if (UdnToServer.Contains(udn))
{
removeThis = (CpMediaServer) UdnToServer[udn];
UdnToServer.Remove(udn);
}
}
if (this.OnServerGone != null)
{
this.OnServerGone(this, device);
}
if (removeThis != null)
{
if (this.OnCpServerRemoved != null)
{
this.OnCpServerRemoved(this, removeThis);
}
}
System.GC.Collect();
}
/// <summary>
/// Object is used a lock to force consistency in the
/// hashtables.
/// </summary>
private object LockHashes = new object();
/// <summary>
/// Contains the init status for a server, keyed by the device's udn.
/// </summary>
private Hashtable UdnToInitStatus = new Hashtable();
/// <summary>
/// Hashtable of UDN to
/// <see cref="CpMediaServer"/>
/// objects that are actively mirroring content hierarchies.
/// </summary>
private Hashtable UdnToServer = new Hashtable();
/// <summary>
/// UPNP smart control point that tells me when
/// mediaservers show up.
/// </summary>
private UPnPSmartControlPoint m_Scp;
/// <summary>
/// If this is set to true, then all discovered
/// bad servers will be treated as good servers.
/// This value should not be switched on-off
/// regularly as it is not yet thread-safe.
/// </summary>
public const bool BadServersAreGoodServersToo = true;
/// <summary>
/// The subscribe status for a media server.
/// </summary>
private class InitStatus
{
public bool SubcribeCM;
public bool SubcribeCD;
public bool EventedCM;
public bool EventedCD;
public int ZeroMeansDone = 4;
public CpMediaServer Server;
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
// <auto-generated />
namespace SouthwindRepository{
/// <summary>
/// Strongly-typed collection for the SalesTotalsByAmount class.
/// </summary>
[Serializable]
public partial class SalesTotalsByAmountCollection : ReadOnlyList<SalesTotalsByAmount, SalesTotalsByAmountCollection>
{
public SalesTotalsByAmountCollection() {}
}
/// <summary>
/// This is Read-only wrapper class for the sales totals by amount view.
/// </summary>
[Serializable]
public partial class SalesTotalsByAmount : ReadOnlyRecord<SalesTotalsByAmount>, IReadOnlyRecord
{
#region Default Settings
protected static void SetSQLProps()
{
GetTableSchema();
}
#endregion
#region Schema Accessor
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
{
SetSQLProps();
}
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("sales totals by amount", TableType.View, DataService.GetInstance("SouthwindRepository"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"";
//columns
TableSchema.TableColumn colvarSaleAmount = new TableSchema.TableColumn(schema);
colvarSaleAmount.ColumnName = "SaleAmount";
colvarSaleAmount.DataType = DbType.Decimal;
colvarSaleAmount.MaxLength = 0;
colvarSaleAmount.AutoIncrement = false;
colvarSaleAmount.IsNullable = true;
colvarSaleAmount.IsPrimaryKey = false;
colvarSaleAmount.IsForeignKey = false;
colvarSaleAmount.IsReadOnly = false;
schema.Columns.Add(colvarSaleAmount);
TableSchema.TableColumn colvarOrderID = new TableSchema.TableColumn(schema);
colvarOrderID.ColumnName = "OrderID";
colvarOrderID.DataType = DbType.Int32;
colvarOrderID.MaxLength = 10;
colvarOrderID.AutoIncrement = false;
colvarOrderID.IsNullable = false;
colvarOrderID.IsPrimaryKey = false;
colvarOrderID.IsForeignKey = false;
colvarOrderID.IsReadOnly = false;
schema.Columns.Add(colvarOrderID);
TableSchema.TableColumn colvarCompanyName = new TableSchema.TableColumn(schema);
colvarCompanyName.ColumnName = "CompanyName";
colvarCompanyName.DataType = DbType.String;
colvarCompanyName.MaxLength = 40;
colvarCompanyName.AutoIncrement = false;
colvarCompanyName.IsNullable = false;
colvarCompanyName.IsPrimaryKey = false;
colvarCompanyName.IsForeignKey = false;
colvarCompanyName.IsReadOnly = false;
schema.Columns.Add(colvarCompanyName);
TableSchema.TableColumn colvarShippedDate = new TableSchema.TableColumn(schema);
colvarShippedDate.ColumnName = "ShippedDate";
colvarShippedDate.DataType = DbType.DateTime;
colvarShippedDate.MaxLength = 0;
colvarShippedDate.AutoIncrement = false;
colvarShippedDate.IsNullable = true;
colvarShippedDate.IsPrimaryKey = false;
colvarShippedDate.IsForeignKey = false;
colvarShippedDate.IsReadOnly = false;
schema.Columns.Add(colvarShippedDate);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["SouthwindRepository"].AddSchema("sales totals by amount",schema);
}
}
#endregion
#region Query Accessor
public static Query CreateQuery()
{
return new Query(Schema);
}
#endregion
#region .ctors
public SalesTotalsByAmount()
{
SetSQLProps();
SetDefaults();
MarkNew();
}
public SalesTotalsByAmount(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
{
ForceDefaults();
}
MarkNew();
}
public SalesTotalsByAmount(object keyID)
{
SetSQLProps();
LoadByKey(keyID);
}
public SalesTotalsByAmount(string columnName, object columnValue)
{
SetSQLProps();
LoadByParam(columnName,columnValue);
}
#endregion
#region Props
[XmlAttribute("SaleAmount")]
[Bindable(true)]
public decimal? SaleAmount
{
get
{
return GetColumnValue<decimal?>("SaleAmount");
}
set
{
SetColumnValue("SaleAmount", value);
}
}
[XmlAttribute("OrderID")]
[Bindable(true)]
public int OrderID
{
get
{
return GetColumnValue<int>("OrderID");
}
set
{
SetColumnValue("OrderID", value);
}
}
[XmlAttribute("CompanyName")]
[Bindable(true)]
public string CompanyName
{
get
{
return GetColumnValue<string>("CompanyName");
}
set
{
SetColumnValue("CompanyName", value);
}
}
[XmlAttribute("ShippedDate")]
[Bindable(true)]
public DateTime? ShippedDate
{
get
{
return GetColumnValue<DateTime?>("ShippedDate");
}
set
{
SetColumnValue("ShippedDate", value);
}
}
#endregion
#region Columns Struct
public struct Columns
{
public static string SaleAmount = @"SaleAmount";
public static string OrderID = @"OrderID";
public static string CompanyName = @"CompanyName";
public static string ShippedDate = @"ShippedDate";
}
#endregion
#region IAbstractRecord Members
public new CT GetColumnValue<CT>(string columnName) {
return base.GetColumnValue<CT>(columnName);
}
public object GetColumnValue(string columnName) {
return base.GetColumnValue<object>(columnName);
}
#endregion
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PlotView.cs" company="OxyPlot">
// Copyright (c) 2014 OxyPlot contributors
// </copyright>
// <summary>
// Provides a view that can show a <see cref="PlotModel" />.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace OxyPlot.Mono.Mac
{
using System;
using System.Drawing;
using MonoMac.Foundation;
using MonoMac.AppKit;
using OxyPlot;
/// <summary>
/// Provides a view that can show a <see cref="PlotModel" />.
/// </summary>
[Register("PlotView")]
public class PlotView : NSControl, IPlotView
{
/// <summary>
/// The current plot model.
/// </summary>
private PlotModel model;
/// <summary>
/// The default plot controller.
/// </summary>
private IPlotController defaultController;
/// <summary>
/// Initializes a new instance of the <see cref="OxyPlot.Xamarin.Mac.PlotView"/> class.
/// </summary>
public PlotView()
{
this.Initialize ();
}
/// <summary>
/// Initializes a new instance of the <see cref="OxyPlot.Xamarin.Mac.PlotView"/> class.
/// </summary>
/// <param name="frame">The initial frame.</param>
public PlotView(RectangleF frame) : base(frame)
{
this.Initialize ();
}
/// <summary>
/// Initializes a new instance of the <see cref="OxyPlot.Xamarin.Mac.PlotView"/> class.
/// </summary>
/// <param name="coder">Coder.</param>
[Export ("initWithCoder:")]
public PlotView(NSCoder coder) : base (coder)
{
this.Initialize ();
}
/// <summary>
/// Uses the new layout.
/// </summary>
/// <returns><c>true</c>, if new layout was used, <c>false</c> otherwise.</returns>
[Export ("requiresConstraintBasedLayout")]
bool UseNewLayout ()
{
return true;
}
/// <summary>
/// Initialize the view.
/// </summary>
private void Initialize() {
this.AcceptsTouchEvents = true;
}
/// <summary>
/// Gets or sets the <see cref="PlotModel"/> to show in the view.
/// </summary>
/// <value>The <see cref="PlotModel"/>.</value>
public PlotModel Model
{
get
{
return this.model;
}
set
{
if (this.model != value)
{
if (this.model != null)
{
((IPlotModel)this.model).AttachPlotView(null);
this.model = null;
}
if (value != null)
{
((IPlotModel)value).AttachPlotView(this);
this.model = value;
}
this.InvalidatePlot();
}
}
}
/// <summary>
/// Gets or sets the <see cref="IPlotController"/> that handles input events.
/// </summary>
/// <value>The <see cref="IPlotController"/>.</value>
public IPlotController Controller { get; set; }
/// <summary>
/// Gets the actual model in the view.
/// </summary>
/// <value>
/// The actual model.
/// </value>
Model IView.ActualModel
{
get
{
return this.Model;
}
}
/// <summary>
/// Gets the actual <see cref="PlotModel"/> to show.
/// </summary>
/// <value>The actual model.</value>
public PlotModel ActualModel
{
get
{
return this.Model;
}
}
/// <summary>
/// Gets the actual controller.
/// </summary>
/// <value>
/// The actual <see cref="IController" />.
/// </value>
IController IView.ActualController
{
get
{
return this.ActualController;
}
}
/// <summary>
/// Gets the coordinates of the client area of the view.
/// </summary>
public OxyRect ClientArea
{
get
{
// TODO
return new OxyRect(0, 0, 100, 100);
}
}
/// <summary>
/// Gets the actual <see cref="IPlotController"/>.
/// </summary>
/// <value>The actual plot controller.</value>
public IPlotController ActualController
{
get
{
return this.Controller ?? (this.defaultController ?? (this.defaultController = CreateDefaultController()));
}
}
private PlotController CreateDefaultController(){
var c = new PlotController ();
c.UnbindMouseDown (OxyMouseButton.Left);
c.BindMouseDown (OxyMouseButton.Left, PlotCommands.PanAt);
return c;
}
/// <summary>
/// Hides the tracker.
/// </summary>
public void HideTracker()
{
}
/// <summary>
/// Hides the zoom rectangle.
/// </summary>
public void HideZoomRectangle()
{
}
/// <summary>
/// Invalidates the plot (not blocking the UI thread)
/// </summary>
/// <param name="updateData">If set to <c>true</c> update data.</param>
public void InvalidatePlot(bool updateData = true)
{
var actualModel = this.model;
if (actualModel != null)
{
// TODO: update the model on a background thread
((IPlotModel)actualModel).Update(updateData);
}
if (actualModel != null && !actualModel.Background.IsUndefined())
{
// this.BackgroundColor = actualModel.Background.ToUIColor();
}
else
{
// Use white as default background color
// this.BackgroundColor = UIColor.White;
}
this.NeedsDisplay = true;
// this.SetNeedsDisplay();
}
/// <summary>
/// Sets the cursor type.
/// </summary>
/// <param name="cursorType">The cursor type.</param>
public void SetCursorType(CursorType cursorType)
{
this.ResetCursorRects ();
var cursor = Convert (cursorType);
if (cursor!=null)
this.AddCursorRect (this.Bounds, cursor);
}
public static NSCursor Convert(CursorType cursorType){
switch (cursorType) {
case CursorType.Default:
return null;
case CursorType.Pan:
return NSCursor.PointingHandCursor;
case CursorType.ZoomHorizontal:
return NSCursor.ResizeUpDownCursor;
case CursorType.ZoomVertical:
return NSCursor.ResizeLeftRightCursor;
case CursorType.ZoomRectangle:
return NSCursor.CrosshairCursor;
default:
return null;
}
}
/// <summary>
/// Shows the tracker.
/// </summary>
/// <param name="trackerHitResult">The tracker data.</param>
public void ShowTracker(TrackerHitResult trackerHitResult)
{
// TODO
}
/// <summary>
/// Shows the zoom rectangle.
/// </summary>
/// <param name="rectangle">The rectangle.</param>
public void ShowZoomRectangle(OxyRect rectangle)
{
// TODO
}
/// <summary>
/// Stores text on the clipboard.
/// </summary>
/// <param name="text">The text.</param>
public void SetClipboardText(string text)
{
// TODO
// UIPasteboard.General.SetValue(new NSString(text), "public.utf8-plain-text");
}
/// <summary>
/// Draws the content of the view.
/// </summary>
/// <param name="dirtyRect">The rectangle to draw.</param>
public override void DrawRect(RectangleF dirtyRect)
{
if (this.model != null)
{
var context = NSGraphicsContext.CurrentContext.GraphicsPort;
context.TranslateCTM(0f, dirtyRect.Height);
context.ScaleCTM(1f, -1f);
// TODO: scale font matrix??
using (var renderer = new CoreGraphicsRenderContext(context))
{
((IPlotModel)this.model).Render(renderer, dirtyRect.Width, dirtyRect.Height);
}
}
}
public override void MouseDown (NSEvent theEvent)
{
base.MouseDown (theEvent);
this.ActualController.HandleMouseDown (this, theEvent.ToMouseDownEventArgs(this.Bounds));
}
public override void MouseDragged (NSEvent theEvent)
{
base.MouseDragged (theEvent);
this.ActualController.HandleMouseMove (this, theEvent.ToMouseEventArgs (this.Bounds));
}
public override void MouseMoved (NSEvent theEvent)
{
base.MouseMoved (theEvent);
this.ActualController.HandleMouseMove (this, theEvent.ToMouseEventArgs (this.Bounds));
}
public override void MouseUp (NSEvent theEvent)
{
base.MouseUp (theEvent);
this.ActualController.HandleMouseUp (this, theEvent.ToMouseEventArgs (this.Bounds));
}
public override void MouseEntered (NSEvent theEvent)
{
base.MouseEntered (theEvent);
this.ActualController.HandleMouseEnter (this, theEvent.ToMouseEventArgs (this.Bounds));
}
public override void MouseExited (NSEvent theEvent)
{
base.MouseExited (theEvent);
this.ActualController.HandleMouseLeave (this, theEvent.ToMouseEventArgs (this.Bounds));
}
public override void ScrollWheel (NSEvent theEvent)
{
// TODO: use scroll events to pan?
base.ScrollWheel (theEvent);
this.ActualController.HandleMouseWheel (this, theEvent.ToMouseWheelEventArgs (this.Bounds));
}
public override void OtherMouseDown (NSEvent theEvent)
{
base.OtherMouseDown (theEvent);
}
public override void RightMouseDown (NSEvent theEvent)
{
base.RightMouseDown (theEvent);
}
public override void KeyDown (NSEvent theEvent)
{
base.KeyDown (theEvent);
this.ActualController.HandleKeyDown (this, theEvent.ToKeyEventArgs ());
}
public override void TouchesBeganWithEvent (NSEvent theEvent)
{
base.TouchesBeganWithEvent (theEvent);
}
public override void MagnifyWithEvent (NSEvent theEvent)
{
base.MagnifyWithEvent (theEvent);
// TODO: handle pinch event
// https://developer.apple.com/library/mac/documentation/cocoa/conceptual/eventoverview/HandlingTouchEvents/HandlingTouchEvents.html
}
//public override void SmartMagnify (NSEvent withEvent)
//{
// base.SmartMagnify (withEvent);
//}
public override void SwipeWithEvent (NSEvent theEvent)
{
base.SwipeWithEvent (theEvent);
}
}
}
| |
using Signum.Engine.MachineLearning;
using Signum.Entities.MachineLearning;
using Signum.React.ApiControllers;
using Signum.Utilities.Reflection;
using Signum.React.Facades;
using System.Text.Json;
namespace Signum.React.MachineLearning;
public static class PredictRequestExtensions
{
public static Dictionary<QueryToken, object?> ParseMainKeys(this PredictorPredictContext pctx, Dictionary<string, object?> mainKeys)
{
Dictionary<QueryToken, object?> filters = new Dictionary<QueryToken, object?>();
var options = SignumServer.JsonSerializerOptions;
var qd = QueryLogic.Queries.QueryDescription(pctx.Predictor.MainQuery.Query.ToQueryName());
foreach (var kvp in mainKeys)
{
var qt = QueryUtils.Parse(kvp.Key, qd, SubTokensOptions.CanElement | SubTokensOptions.CanAggregate);
var obj = kvp.Value is JsonElement jt ? jt.ToObject(qt.Type, options) : ReflectionTools.ChangeType(kvp.Value, qt.Type);
filters.Add(qt, obj);
}
return filters;
}
public static PredictDictionary GetInputsFromRequest(this PredictorPredictContext pctx, PredictRequestTS request)
{
ParseValues(request, pctx);
return new PredictDictionary(pctx.Predictor, null, null)
{
MainQueryValues = pctx.Predictor.MainQuery.Columns
.Select((col, i) => new { col, request.columns[i].value })
.Where(a => a.col!.Usage == PredictorColumnUsage.Input)
.Select(a => KeyValuePair.Create(a.col!, (object?)a.value))
.ToDictionaryEx(),
SubQueries = pctx.Predictor.SubQueries.Select(sq =>
{
var sqt = request.subQueries.Single(a => a.subQuery.Is(sq));
SplitColumns(sq, out var splitKeys, out var values);
return new PredictSubQueryDictionary(sq)
{
SubQueryGroups = sqt.rows.Select(array => KeyValuePair.Create(
array.Slice(0, splitKeys.Count),
values.Select((a, i) => KeyValuePair.Create(a, array[splitKeys.Count + i])).ToDictionary()
)).ToDictionary(ObjectArrayComparer.Instance)
};
}).ToDictionaryEx(a => a.SubQuery)
};
}
private static void SplitColumns(PredictorSubQueryEntity sq, out List<PredictorSubQueryColumnEmbedded> splitKeys, out List<PredictorSubQueryColumnEmbedded> values)
{
var columns = sq.Columns.ToList();
var parentKey = columns.Extract(a => a.Usage == PredictorSubQueryColumnUsage.ParentKey);
splitKeys = columns.Extract(a => a.Usage == PredictorSubQueryColumnUsage.SplitBy).ToList();
values = columns.ToList();
}
public static void SetOutput(this PredictRequestTS request, PredictDictionary predicted)
{
var predictedMainCols = predicted.MainQueryValues.SelectDictionary(qt => qt.Token.Token.FullKey(), v => v);
foreach (var c in request.columns.Where(a => a.usage == PredictorColumnUsage.Output))
{
var pValue = predictedMainCols.GetOrThrow(c.token.fullKey);
if (request.hasOriginal)
((PredictOutputTuple)c.value!).predicted = pValue;
else
c.value = pValue;
}
foreach (var sq in request.subQueries)
{
PredictSubQueryDictionary psq = predicted.SubQueries.Values.Single(a => sq.subQuery.Is(a.SubQuery));
if (psq.SubQueryGroups.Comparer != ObjectArrayComparer.Instance)
throw new InvalidOperationException("Unexpected comparer");
SplitColumns(psq.SubQuery, out var splitKeys, out var values);
Dictionary<string, PredictorSubQueryColumnEmbedded> fullKeyToToken = psq.SubQuery.Columns.ToDictionary(a => a.Token.Token.FullKey());
foreach (var r in sq.rows)
{
var key = r.Slice(0, splitKeys.Count);
var dic = psq.SubQueryGroups.TryGetC(key);
for (int i = 0; i < values.Count; i++)
{
var c = sq.columnHeaders[splitKeys.Count + i];
if (c.headerType == PredictorHeaderType.Output)
{
ref var box = ref r[splitKeys.Count + i];
var token = fullKeyToToken.GetOrThrow(c.token.fullKey);
var pValue = dic?.GetOrThrow(token);
if (request.hasOriginal)
((PredictOutputTuple)box!).predicted = pValue;
else
box = pValue;
}
}
}
}
}
public static PredictRequestTS CreatePredictModel(this PredictorPredictContext pctx,
PredictDictionary? inputs,
PredictDictionary? originalOutputs,
PredictDictionary predictedOutputs)
{
return new PredictRequestTS
{
predictor = pctx.Predictor.ToLite(),
hasOriginal = originalOutputs != null,
columns = pctx.Predictor.MainQuery.Columns.Select(c => new PredictColumnTS
{
token = new QueryTokenTS(c.Token.Token, true),
usage = c.Usage,
value = c.Usage == PredictorColumnUsage.Input ? inputs?.MainQueryValues.GetOrThrow(c) :
originalOutputs == null ? predictedOutputs?.MainQueryValues.GetOrThrow(c) :
new PredictOutputTuple
{
original = originalOutputs?.MainQueryValues.GetOrThrow(c),
predicted = predictedOutputs?.MainQueryValues.GetOrThrow(c),
}
}).ToList(),
subQueries = pctx.Predictor.SubQueries.Select(sq =>
{
var inputsSQ = inputs?.SubQueries.GetOrThrow(sq);
var originalOutputsSQ = originalOutputs?.SubQueries.GetOrThrow(sq);
var predictedOutputsSQ = predictedOutputs?.SubQueries.GetOrThrow(sq);
SplitColumns(sq, out var splitKeys, out var values);
var columnHeaders =
splitKeys.Select(gk => new PredictSubQueryHeaderTS { token = new QueryTokenTS(gk.Token.Token, true), headerType = PredictorHeaderType.Key }).Concat(
values.Select(agg => new PredictSubQueryHeaderTS { token = new QueryTokenTS(agg.Token.Token, true), headerType = agg.Usage == PredictorSubQueryColumnUsage.Input ? PredictorHeaderType.Input : PredictorHeaderType.Output }))
.ToList();
return new PredictSubQueryTableTS
{
subQuery = sq.ToLite(),
columnHeaders = columnHeaders,
rows = pctx.SubQueryOutputCodifications[sq].Groups
.Select(kvp => CreateRow(splitKeys, values, kvp.Key, inputsSQ, originalOutputsSQ, predictedOutputsSQ))
.ToList()
};
}).ToList()
};
}
static object?[] CreateRow(List<PredictorSubQueryColumnEmbedded> groupKeys, List<PredictorSubQueryColumnEmbedded> values, object?[] key, PredictSubQueryDictionary? inputs, PredictSubQueryDictionary? originalOutputs, PredictSubQueryDictionary? predictedOutputs)
{
var row = new object?[groupKeys.Count + values.Count];
var inputsGR = inputs?.SubQueryGroups.TryGetC(key);
var originalOutputsGR = originalOutputs?.SubQueryGroups.TryGetC(key);
var predictedOutputsGR = predictedOutputs?.SubQueryGroups.GetOrThrow(key);
for (int i = 0; i < groupKeys.Count; i++)
{
row[i] = key[i];
}
for (int i = 0; i < values.Count; i++)
{
var v = values[i];
row[i + key.Length] = v.Usage == PredictorSubQueryColumnUsage.Input ? inputsGR?.GetOrThrow(v) :
originalOutputs == null ? predictedOutputsGR!.GetOrThrow(v) :
new PredictOutputTuple
{
predicted = predictedOutputsGR!.GetOrThrow(v),
original = originalOutputsGR?.GetOrThrow(v),
};
}
return row;
}
public static void ParseValues(this PredictRequestTS predict, PredictorPredictContext ctx)
{
var options = SignumServer.JsonSerializerOptions;
for (int i = 0; i < ctx.Predictor.MainQuery.Columns.Count; i++)
{
predict.columns[i].value = FixValue(predict.columns[i].value, ctx.Predictor.MainQuery.Columns[i].Token.Token, options);
}
foreach (var tuple in ctx.SubQueryOutputCodifications.Values.ZipStrict(predict.subQueries, (sqCtx, table) => (sqCtx, table)))
{
var sq = tuple.sqCtx.SubQuery;
SplitColumns(sq, out var splitKeys, out var values);
foreach (var row in tuple.table.rows)
{
for (int i = 0; i < splitKeys.Count; i++)
{
row[i] = FixValue(row[i], splitKeys[i].Token.Token, options);
}
for (int i = 0; i < values.Count; i++)
{
var colIndex = i + splitKeys.Count;
row[colIndex] = FixValue(row[colIndex], values[i].Token.Token, options);
}
}
}
}
static object? FixValue(object? value, QueryToken token, JsonSerializerOptions options)
{
if (value == null)
return null;
var elem = (JsonElement)value;
if (elem.ValueKind == JsonValueKind.Object &&
elem.TryGetProperty(nameof(PredictOutputTuple.original), out var original) &&
elem.TryGetProperty(nameof(PredictOutputTuple.predicted), out var predicted))
{
return new PredictOutputTuple
{
original = FixValue(original, token, options),
predicted = FixValue(predicted, token, options),
};
}
if(elem.ValueKind == JsonValueKind.Array)
{
var list = elem.ToObject<List<AlternativePrediction>>();
var result = list!.Select(val => ReflectionTools.ChangeType(val, token.Type));
return result;
}
return elem.ToObject(token.Type, options);
}
}
public class PredictRequestTS
{
public bool hasOriginal { get; set; }
public int? alternativesCount { get; set; }
public Lite<PredictorEntity> predictor { get; set; }
public List<PredictColumnTS> columns { get; set; }
public List<PredictSubQueryTableTS> subQueries { get; set; }
}
public class PredictColumnTS
{
public QueryTokenTS token { get; set; }
public PredictorColumnUsage usage { get; set; }
public object? value { get; set; }
}
public class PredictSubQueryTableTS
{
public Lite<PredictorSubQueryEntity> subQuery { get; set; }
//Key* (Input|Output)*
public List<PredictSubQueryHeaderTS> columnHeaders { get; set; }
public List<object?[]> rows { get; set; }
}
public class PredictOutputTuple
{
public object? predicted;
public object? original;
}
public class PredictSubQueryHeaderTS
{
public QueryTokenTS token { get; set; }
public PredictorHeaderType headerType { get; set; }
}
public enum PredictorHeaderType
{
Key,
Input,
Output,
}
| |
using System.Collections.Generic;
using JetBrains.Annotations;
using JetBrains.Application;
using JetBrains.Application.CommandProcessing;
using JetBrains.DataFlow;
using JetBrains.DocumentModel;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Feature.Services.CodeCompletion.Infrastructure.AspectLookupItems.BaseInfrastructure;
using JetBrains.ReSharper.Feature.Services.CodeCompletion.Infrastructure.LookupItems;
using JetBrains.ReSharper.Feature.Services.Lookup;
using JetBrains.ReSharper.Feature.Services.Tips;
using JetBrains.ReSharper.Feature.Services.Util;
using JetBrains.ReSharper.PostfixTemplates.Contexts;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.Tree;
using JetBrains.ReSharper.Resources.Shell;
using JetBrains.TextControl;
using JetBrains.Util;
namespace JetBrains.ReSharper.PostfixTemplates.LookupItems
{
public abstract class PostfixTemplateBehavior : LookupItemAspect<PostfixTemplateInfo>, ILookupItemBehavior
{
private int myExpressionIndex;
protected PostfixTemplateBehavior([NotNull] PostfixTemplateInfo info)
: base(info)
{
myExpressionIndex = (info.Images.Count > 1 ? -1 : 0);
}
protected string ExpandCommandName
{
get { return GetType().FullName + " accept"; }
}
protected virtual string ExpressionSelectTitle
{
get { return "Select expression"; }
}
public bool AcceptIfOnlyMatched(LookupItemAcceptanceContext itemAcceptanceContext)
{
return false; // TODO: [R#] test why is this is not working
}
public void Accept(ITextControl textControl, TextRange nameRange, LookupItemInsertType insertType,
Suffix suffix, ISolution solution, bool keepCaretStill)
{
// todo: carefully review and document all of this :\
var reparseString = Info.ReparseString;
// so we inserted '.__' and get '2 + 2.__' just like in code completion reparse
textControl.Document.InsertText(nameRange.EndOffset, reparseString, TextModificationSide.RightSide);
solution.GetPsiServices().Files.CommitAllDocuments();
var executionContext = new PostfixTemplateExecutionContext(
solution, textControl, Info.ExecutionContext.SettingsStore, Info.ReparseString, Info.ExecutionContext.IsPreciseMode);
PostfixTemplateContext postfixContext = null;
foreach (var element in TextControlToPsi.GetElements<ITreeNode>(solution, textControl.Document, nameRange.EndOffset))
{
var contextFactory = LanguageManager.Instance.TryGetService<IPostfixTemplateContextFactory>(element.Language);
if (contextFactory == null) continue;
postfixContext = contextFactory.TryCreate(element, executionContext);
if (postfixContext != null) break;
}
// todo: [R#] good feature id, looks at source templates 'Accept()'
TipsManager.Instance.FeatureIsUsed(
"Plugin.ControlFlow.PostfixTemplates." + Info.Text, textControl.Document, solution);
Assertion.AssertNotNull(postfixContext, "postfixContext != null");
var expressions = FindOriginalContexts(postfixContext);
Assertion.Assert(expressions.Count > 0, "expressions.Count > 0");
if (expressions.Count > 1 && myExpressionIndex == -1)
{
// rollback document changes to hide reparse string from user
var chooser = solution.GetComponent<ExpressionChooser>();
var postfixRange = GetPostfixRange(textControl, nameRange);
var postfixText = textControl.Document.GetText(postfixRange);
textControl.Document.ReplaceText(postfixRange, string.Empty);
chooser.Execute(
EternalLifetime.Instance, textControl, expressions, postfixText,
ExpressionSelectTitle, continuation: index =>
{
myExpressionIndex = index;
// yep, run accept recursively, now with selected item index
var locks = solution.GetComponent<IShellLocks>();
const string commandName = "PostfixTemplates.Accept";
locks.ReentrancyGuard.ExecuteOrQueue(commandName, () =>
{
locks.ExecuteWithReadLock(() =>
{
var processor = solution.GetComponent<ICommandProcessor>();
using (processor.UsingCommand(commandName))
{
var text = postfixText.Substring(0, postfixText.Length - reparseString.Length);
// todo: don't like it very much, is there a better way to solve this?
textControl.Document.InsertText( // bring back ".name__"
postfixRange.StartOffset, text, TextModificationSide.RightSide);
// argh!
Accept(textControl, nameRange, insertType, suffix, solution, keepCaretStill);
}
});
});
});
return;
}
Assertion.Assert(myExpressionIndex >= 0, "myExpressionIndex >= 0");
Assertion.Assert(myExpressionIndex < expressions.Count, "myExpressionIndex < expressions.Count");
var expressionContext = expressions[myExpressionIndex];
ITreeNode newNode;
using (WriteLockCookie.Create())
{
var fixedContext = postfixContext.FixExpression(expressionContext);
var expression = fixedContext.Expression;
Assertion.Assert(expression.IsPhysical(), "expression.IsPhysical()");
newNode = ExpandPostfix(fixedContext);
Assertion.AssertNotNull(newNode, "newNode != null");
Assertion.Assert(newNode.IsPhysical(), "newNode.IsPhysical()");
}
AfterComplete(textControl, newNode);
}
private TextRange GetPostfixRange([NotNull] ITextControl textControl, TextRange nameRange)
{
Assertion.Assert(nameRange.IsValid, "nameRange.IsValid");
var length = nameRange.Length + Info.ReparseString.Length;
var textRange = TextRange.FromLength(nameRange.StartOffset, length);
// find dot before postfix template name
var buffer = textControl.Document.Buffer;
for (var index = nameRange.StartOffset - 1; index > 0; index--)
{
if (buffer[index] == '.') return textRange.SetStartTo(index);
}
return textRange;
}
protected abstract ITreeNode ExpandPostfix([NotNull] PostfixExpressionContext context);
protected virtual void AfterComplete([NotNull] ITextControl textControl, [NotNull] ITreeNode node)
{
}
[NotNull]
private IList<PostfixExpressionContext> FindOriginalContexts([NotNull] PostfixTemplateContext context)
{
var results = new LocalList<PostfixExpressionContext>();
var images = new List<PostfixExpressionContextImage>(Info.Images);
for (var index = 0; index < images.Count; index++) // order is important
{
foreach (var expressionContext in context.AllExpressions)
{
if (images[index].MatchesByRangeAndType(expressionContext))
{
images[index] = null;
results.Add(expressionContext);
break;
}
}
}
if (results.Count == 0)
{
var expressions = context.AllExpressions;
foreach (var image in images)
{
if (image != null && image.ExpressionIndex < expressions.Count)
{
results.Add(expressions[image.ExpressionIndex]);
}
}
}
return results.ResultingList();
}
}
}
| |
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 VSLiveSampleService.Areas.HelpPage.ModelDescriptions;
using VSLiveSampleService.Areas.HelpPage.Models;
namespace VSLiveSampleService.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 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.Analysis
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for ServersOperations.
/// </summary>
public static partial class ServersOperationsExtensions
{
/// <summary>
/// Gets details about the specified Analysis Services server.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure Resource group of which a given Analysis Services
/// server is part. This name must be at least 1 character in length, and no
/// more than 90.
/// </param>
/// <param name='serverName'>
/// The name of the Analysis Services server. It must be a minimum of 3
/// characters, and a maximum of 63.
/// </param>
public static AnalysisServicesServer GetDetails(this IServersOperations operations, string resourceGroupName, string serverName)
{
return operations.GetDetailsAsync(resourceGroupName, serverName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets details about the specified Analysis Services server.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure Resource group of which a given Analysis Services
/// server is part. This name must be at least 1 character in length, and no
/// more than 90.
/// </param>
/// <param name='serverName'>
/// The name of the Analysis Services server. It must be a minimum of 3
/// characters, and a maximum of 63.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<AnalysisServicesServer> GetDetailsAsync(this IServersOperations operations, string resourceGroupName, string serverName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetDetailsWithHttpMessagesAsync(resourceGroupName, serverName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Provisions the specified Analysis Services server based on the
/// configuration specified in the request.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure Resource group of which a given Analysis Services
/// server is part. This name must be at least 1 character in length, and no
/// more than 90.
/// </param>
/// <param name='serverName'>
/// The name of the Analysis Services server. It must be a minimum of 3
/// characters, and a maximum of 63.
/// </param>
/// <param name='serverParameters'>
/// Contains the information used to provision the Analysis Services server.
/// </param>
public static AnalysisServicesServer Create(this IServersOperations operations, string resourceGroupName, string serverName, AnalysisServicesServer serverParameters)
{
return operations.CreateAsync(resourceGroupName, serverName, serverParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Provisions the specified Analysis Services server based on the
/// configuration specified in the request.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure Resource group of which a given Analysis Services
/// server is part. This name must be at least 1 character in length, and no
/// more than 90.
/// </param>
/// <param name='serverName'>
/// The name of the Analysis Services server. It must be a minimum of 3
/// characters, and a maximum of 63.
/// </param>
/// <param name='serverParameters'>
/// Contains the information used to provision the Analysis Services server.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<AnalysisServicesServer> CreateAsync(this IServersOperations operations, string resourceGroupName, string serverName, AnalysisServicesServer serverParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, serverName, serverParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified Analysis Services server.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure Resource group of which a given Analysis Services
/// server is part. This name must be at least 1 character in length, and no
/// more than 90.
/// </param>
/// <param name='serverName'>
/// The name of the Analysis Services server. It must be at least 3 characters
/// in length, and no more than 63.
/// </param>
public static void Delete(this IServersOperations operations, string resourceGroupName, string serverName)
{
operations.DeleteAsync(resourceGroupName, serverName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified Analysis Services server.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure Resource group of which a given Analysis Services
/// server is part. This name must be at least 1 character in length, and no
/// more than 90.
/// </param>
/// <param name='serverName'>
/// The name of the Analysis Services server. It must be at least 3 characters
/// in length, and no more than 63.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IServersOperations operations, string resourceGroupName, string serverName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, serverName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Updates the current state of the specified Analysis Services server.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure Resource group of which a given Analysis Services
/// server is part. This name must be at least 1 character in length, and no
/// more than 90.
/// </param>
/// <param name='serverName'>
/// The name of the Analysis Services server. It must be at least 3 characters
/// in length, and no more than 63.
/// </param>
/// <param name='serverUpdateParameters'>
/// Request object that contains the updated information for the server.
/// </param>
public static AnalysisServicesServer Update(this IServersOperations operations, string resourceGroupName, string serverName, AnalysisServicesServerUpdateParameters serverUpdateParameters)
{
return operations.UpdateAsync(resourceGroupName, serverName, serverUpdateParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Updates the current state of the specified Analysis Services server.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure Resource group of which a given Analysis Services
/// server is part. This name must be at least 1 character in length, and no
/// more than 90.
/// </param>
/// <param name='serverName'>
/// The name of the Analysis Services server. It must be at least 3 characters
/// in length, and no more than 63.
/// </param>
/// <param name='serverUpdateParameters'>
/// Request object that contains the updated information for the server.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<AnalysisServicesServer> UpdateAsync(this IServersOperations operations, string resourceGroupName, string serverName, AnalysisServicesServerUpdateParameters serverUpdateParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, serverName, serverUpdateParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Supends operation of the specified Analysis Services server instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure Resource group of which a given Analysis Services
/// server is part. This name must be at least 1 character in length, and no
/// more than 90.
/// </param>
/// <param name='serverName'>
/// The name of the Analysis Services server. It must be at least 3 characters
/// in length, and no more than 63.
/// </param>
public static void Suspend(this IServersOperations operations, string resourceGroupName, string serverName)
{
operations.SuspendAsync(resourceGroupName, serverName).GetAwaiter().GetResult();
}
/// <summary>
/// Supends operation of the specified Analysis Services server instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure Resource group of which a given Analysis Services
/// server is part. This name must be at least 1 character in length, and no
/// more than 90.
/// </param>
/// <param name='serverName'>
/// The name of the Analysis Services server. It must be at least 3 characters
/// in length, and no more than 63.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task SuspendAsync(this IServersOperations operations, string resourceGroupName, string serverName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.SuspendWithHttpMessagesAsync(resourceGroupName, serverName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Resumes operation of the specified Analysis Services server instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure Resource group of which a given Analysis Services
/// server is part. This name must be at least 1 character in length, and no
/// more than 90.
/// </param>
/// <param name='serverName'>
/// The name of the Analysis Services server. It must be at least 3 characters
/// in length, and no more than 63.
/// </param>
public static void Resume(this IServersOperations operations, string resourceGroupName, string serverName)
{
operations.ResumeAsync(resourceGroupName, serverName).GetAwaiter().GetResult();
}
/// <summary>
/// Resumes operation of the specified Analysis Services server instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure Resource group of which a given Analysis Services
/// server is part. This name must be at least 1 character in length, and no
/// more than 90.
/// </param>
/// <param name='serverName'>
/// The name of the Analysis Services server. It must be at least 3 characters
/// in length, and no more than 63.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task ResumeAsync(this IServersOperations operations, string resourceGroupName, string serverName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.ResumeWithHttpMessagesAsync(resourceGroupName, serverName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets all the Analysis Services servers for the given resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure Resource group of which a given Analysis Services
/// server is part. This name must be at least 1 character in length, and no
/// more than 90.
/// </param>
public static IEnumerable<AnalysisServicesServer> ListByResourceGroup(this IServersOperations operations, string resourceGroupName)
{
return operations.ListByResourceGroupAsync(resourceGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all the Analysis Services servers for the given resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure Resource group of which a given Analysis Services
/// server is part. This name must be at least 1 character in length, and no
/// more than 90.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<AnalysisServicesServer>> ListByResourceGroupAsync(this IServersOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all the Analysis Services servers for the given subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IEnumerable<AnalysisServicesServer> List(this IServersOperations operations)
{
return operations.ListAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all the Analysis Services servers for the given subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<AnalysisServicesServer>> ListAsync(this IServersOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists eligible SKUs for Analysis Services resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static SkuEnumerationForNewResourceResult ListSkusForNew(this IServersOperations operations)
{
return operations.ListSkusForNewAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Lists eligible SKUs for Analysis Services resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SkuEnumerationForNewResourceResult> ListSkusForNewAsync(this IServersOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListSkusForNewWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists eligible SKUs for an Analysis Services resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure Resource group of which a given Analysis Services
/// server is part. This name must be at least 1 character in length, and no
/// more than 90.
/// </param>
/// <param name='serverName'>
/// The name of the Analysis Services server. It must be at least 3 characters
/// in length, and no more than 63.
/// </param>
public static SkuEnumerationForExistingResourceResult ListSkusForExisting(this IServersOperations operations, string resourceGroupName, string serverName)
{
return operations.ListSkusForExistingAsync(resourceGroupName, serverName).GetAwaiter().GetResult();
}
/// <summary>
/// Lists eligible SKUs for an Analysis Services resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure Resource group of which a given Analysis Services
/// server is part. This name must be at least 1 character in length, and no
/// more than 90.
/// </param>
/// <param name='serverName'>
/// The name of the Analysis Services server. It must be at least 3 characters
/// in length, and no more than 63.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SkuEnumerationForExistingResourceResult> ListSkusForExistingAsync(this IServersOperations operations, string resourceGroupName, string serverName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListSkusForExistingWithHttpMessagesAsync(resourceGroupName, serverName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Return the gateway status of the specified Analysis Services server
/// instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure Resource group of which a given Analysis Services
/// server is part. This name must be at least 1 character in length, and no
/// more than 90.
/// </param>
/// <param name='serverName'>
/// The name of the Analysis Services server. It must be at least 3 characters
/// in length, and no more than 63.
/// </param>
public static GatewayListStatusLive ListGatewayStatus(this IServersOperations operations, string resourceGroupName, string serverName)
{
return operations.ListGatewayStatusAsync(resourceGroupName, serverName).GetAwaiter().GetResult();
}
/// <summary>
/// Return the gateway status of the specified Analysis Services server
/// instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure Resource group of which a given Analysis Services
/// server is part. This name must be at least 1 character in length, and no
/// more than 90.
/// </param>
/// <param name='serverName'>
/// The name of the Analysis Services server. It must be at least 3 characters
/// in length, and no more than 63.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<GatewayListStatusLive> ListGatewayStatusAsync(this IServersOperations operations, string resourceGroupName, string serverName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListGatewayStatusWithHttpMessagesAsync(resourceGroupName, serverName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Dissociates a Unified Gateway associated with the server.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure Resource group of which a given Analysis Services
/// server is part. This name must be at least 1 character in length, and no
/// more than 90.
/// </param>
/// <param name='serverName'>
/// The name of the Analysis Services server. It must be at least 3 characters
/// in length, and no more than 63.
/// </param>
public static void DissociateGateway(this IServersOperations operations, string resourceGroupName, string serverName)
{
operations.DissociateGatewayAsync(resourceGroupName, serverName).GetAwaiter().GetResult();
}
/// <summary>
/// Dissociates a Unified Gateway associated with the server.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure Resource group of which a given Analysis Services
/// server is part. This name must be at least 1 character in length, and no
/// more than 90.
/// </param>
/// <param name='serverName'>
/// The name of the Analysis Services server. It must be at least 3 characters
/// in length, and no more than 63.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DissociateGatewayAsync(this IServersOperations operations, string resourceGroupName, string serverName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DissociateGatewayWithHttpMessagesAsync(resourceGroupName, serverName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Check the name availability in the target location.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='location'>
/// The region name which the operation will lookup into.
/// </param>
/// <param name='serverParameters'>
/// Contains the information used to provision the Analysis Services server.
/// </param>
public static CheckServerNameAvailabilityResult CheckNameAvailability(this IServersOperations operations, string location, CheckServerNameAvailabilityParameters serverParameters)
{
return operations.CheckNameAvailabilityAsync(location, serverParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Check the name availability in the target location.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='location'>
/// The region name which the operation will lookup into.
/// </param>
/// <param name='serverParameters'>
/// Contains the information used to provision the Analysis Services server.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<CheckServerNameAvailabilityResult> CheckNameAvailabilityAsync(this IServersOperations operations, string location, CheckServerNameAvailabilityParameters serverParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CheckNameAvailabilityWithHttpMessagesAsync(location, serverParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// List the result of the specified operation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='location'>
/// The region name which the operation will lookup into.
/// </param>
/// <param name='operationId'>
/// The target operation Id.
/// </param>
public static void ListOperationResults(this IServersOperations operations, string location, string operationId)
{
operations.ListOperationResultsAsync(location, operationId).GetAwaiter().GetResult();
}
/// <summary>
/// List the result of the specified operation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='location'>
/// The region name which the operation will lookup into.
/// </param>
/// <param name='operationId'>
/// The target operation Id.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task ListOperationResultsAsync(this IServersOperations operations, string location, string operationId, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.ListOperationResultsWithHttpMessagesAsync(location, operationId, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// List the status of operation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='location'>
/// The region name which the operation will lookup into.
/// </param>
/// <param name='operationId'>
/// The target operation Id.
/// </param>
public static OperationStatus ListOperationStatuses(this IServersOperations operations, string location, string operationId)
{
return operations.ListOperationStatusesAsync(location, operationId).GetAwaiter().GetResult();
}
/// <summary>
/// List the status of operation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='location'>
/// The region name which the operation will lookup into.
/// </param>
/// <param name='operationId'>
/// The target operation Id.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<OperationStatus> ListOperationStatusesAsync(this IServersOperations operations, string location, string operationId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListOperationStatusesWithHttpMessagesAsync(location, operationId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Provisions the specified Analysis Services server based on the
/// configuration specified in the request.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure Resource group of which a given Analysis Services
/// server is part. This name must be at least 1 character in length, and no
/// more than 90.
/// </param>
/// <param name='serverName'>
/// The name of the Analysis Services server. It must be a minimum of 3
/// characters, and a maximum of 63.
/// </param>
/// <param name='serverParameters'>
/// Contains the information used to provision the Analysis Services server.
/// </param>
public static AnalysisServicesServer BeginCreate(this IServersOperations operations, string resourceGroupName, string serverName, AnalysisServicesServer serverParameters)
{
return operations.BeginCreateAsync(resourceGroupName, serverName, serverParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Provisions the specified Analysis Services server based on the
/// configuration specified in the request.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure Resource group of which a given Analysis Services
/// server is part. This name must be at least 1 character in length, and no
/// more than 90.
/// </param>
/// <param name='serverName'>
/// The name of the Analysis Services server. It must be a minimum of 3
/// characters, and a maximum of 63.
/// </param>
/// <param name='serverParameters'>
/// Contains the information used to provision the Analysis Services server.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<AnalysisServicesServer> BeginCreateAsync(this IServersOperations operations, string resourceGroupName, string serverName, AnalysisServicesServer serverParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateWithHttpMessagesAsync(resourceGroupName, serverName, serverParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified Analysis Services server.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure Resource group of which a given Analysis Services
/// server is part. This name must be at least 1 character in length, and no
/// more than 90.
/// </param>
/// <param name='serverName'>
/// The name of the Analysis Services server. It must be at least 3 characters
/// in length, and no more than 63.
/// </param>
public static void BeginDelete(this IServersOperations operations, string resourceGroupName, string serverName)
{
operations.BeginDeleteAsync(resourceGroupName, serverName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified Analysis Services server.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure Resource group of which a given Analysis Services
/// server is part. This name must be at least 1 character in length, and no
/// more than 90.
/// </param>
/// <param name='serverName'>
/// The name of the Analysis Services server. It must be at least 3 characters
/// in length, and no more than 63.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IServersOperations operations, string resourceGroupName, string serverName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, serverName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Updates the current state of the specified Analysis Services server.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure Resource group of which a given Analysis Services
/// server is part. This name must be at least 1 character in length, and no
/// more than 90.
/// </param>
/// <param name='serverName'>
/// The name of the Analysis Services server. It must be at least 3 characters
/// in length, and no more than 63.
/// </param>
/// <param name='serverUpdateParameters'>
/// Request object that contains the updated information for the server.
/// </param>
public static AnalysisServicesServer BeginUpdate(this IServersOperations operations, string resourceGroupName, string serverName, AnalysisServicesServerUpdateParameters serverUpdateParameters)
{
return operations.BeginUpdateAsync(resourceGroupName, serverName, serverUpdateParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Updates the current state of the specified Analysis Services server.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure Resource group of which a given Analysis Services
/// server is part. This name must be at least 1 character in length, and no
/// more than 90.
/// </param>
/// <param name='serverName'>
/// The name of the Analysis Services server. It must be at least 3 characters
/// in length, and no more than 63.
/// </param>
/// <param name='serverUpdateParameters'>
/// Request object that contains the updated information for the server.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<AnalysisServicesServer> BeginUpdateAsync(this IServersOperations operations, string resourceGroupName, string serverName, AnalysisServicesServerUpdateParameters serverUpdateParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(resourceGroupName, serverName, serverUpdateParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Supends operation of the specified Analysis Services server instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure Resource group of which a given Analysis Services
/// server is part. This name must be at least 1 character in length, and no
/// more than 90.
/// </param>
/// <param name='serverName'>
/// The name of the Analysis Services server. It must be at least 3 characters
/// in length, and no more than 63.
/// </param>
public static void BeginSuspend(this IServersOperations operations, string resourceGroupName, string serverName)
{
operations.BeginSuspendAsync(resourceGroupName, serverName).GetAwaiter().GetResult();
}
/// <summary>
/// Supends operation of the specified Analysis Services server instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure Resource group of which a given Analysis Services
/// server is part. This name must be at least 1 character in length, and no
/// more than 90.
/// </param>
/// <param name='serverName'>
/// The name of the Analysis Services server. It must be at least 3 characters
/// in length, and no more than 63.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginSuspendAsync(this IServersOperations operations, string resourceGroupName, string serverName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginSuspendWithHttpMessagesAsync(resourceGroupName, serverName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Resumes operation of the specified Analysis Services server instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure Resource group of which a given Analysis Services
/// server is part. This name must be at least 1 character in length, and no
/// more than 90.
/// </param>
/// <param name='serverName'>
/// The name of the Analysis Services server. It must be at least 3 characters
/// in length, and no more than 63.
/// </param>
public static void BeginResume(this IServersOperations operations, string resourceGroupName, string serverName)
{
operations.BeginResumeAsync(resourceGroupName, serverName).GetAwaiter().GetResult();
}
/// <summary>
/// Resumes operation of the specified Analysis Services server instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure Resource group of which a given Analysis Services
/// server is part. This name must be at least 1 character in length, and no
/// more than 90.
/// </param>
/// <param name='serverName'>
/// The name of the Analysis Services server. It must be at least 3 characters
/// in length, and no more than 63.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginResumeAsync(this IServersOperations operations, string resourceGroupName, string serverName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginResumeWithHttpMessagesAsync(resourceGroupName, serverName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
}
}
| |
/*
Copyright (c) 2005 Poderosa Project, All Rights Reserved.
This file is a part of the Granados SSH Client Library that is subject to
the license included in the distributed package.
You may not use this file except in compliance with the license.
I implemented this algorithm with reference to following products and books though the algorithm is known publicly.
* MindTerm ( AppGate Network Security )
* Applied Cryptography ( Bruce Schneier )
$Id: Blowfish.cs,v 1.4 2011/10/27 23:21:56 kzmi Exp $
*/
using System;
using Granados.Crypto;
namespace Granados.Algorithms {
/// <summary>
///
/// </summary>
/// <exclude/>
public class Blowfish {
byte[] IV;
byte[] enc;
byte[] dec;
private const int BLOCK_SIZE = 8; // bytes in a data-block
protected uint[] S0;
protected uint[] S1;
protected uint[] S2;
protected uint[] S3;
protected uint[] P;
public Blowfish() {
S0 = new uint[256];
S1 = new uint[256];
S2 = new uint[256];
S3 = new uint[256];
P = new uint[18];
IV = new byte[8];
enc = new byte[8];
dec = new byte[8];
}
public void SetIV(byte[] newiv) {
Array.Copy(newiv, 0, IV, 0, IV.Length);
}
public void initializeKey(byte[] key) {
int i, j, len = key.Length;
uint temp;
Array.Copy(blowfish_pbox, 0, P, 0, 18);
Array.Copy(blowfish_sbox, 0, S0, 0, 256);
Array.Copy(blowfish_sbox, 256, S1, 0, 256);
Array.Copy(blowfish_sbox, 512, S2, 0, 256);
Array.Copy(blowfish_sbox, 768, S3, 0, 256);
for (j = 0, i = 0; i < 16 + 2; i++) {
temp = (((uint)(key[j]) << 24) |
((uint)(key[(j + 1) % len]) << 16) |
((uint)(key[(j + 2) % len]) << 8) |
((uint)(key[(j + 3) % len])));
P[i] = P[i] ^ temp;
j = (j + 4) % len;
}
byte[] LR = new byte[8];
for (i = 0; i < 16 + 2; i += 2) {
blockEncrypt(LR, 0, LR, 0);
P[i] = CipherUtil.GetIntBE(LR, 0);
P[i + 1] = CipherUtil.GetIntBE(LR, 4);
}
for (j = 0; j < 256; j += 2) {
blockEncrypt(LR, 0, LR, 0);
S0[j] = CipherUtil.GetIntBE(LR, 0);
S0[j + 1] = CipherUtil.GetIntBE(LR, 4);
}
for (j = 0; j < 256; j += 2) {
blockEncrypt(LR, 0, LR, 0);
S1[j] = CipherUtil.GetIntBE(LR, 0);
S1[j + 1] = CipherUtil.GetIntBE(LR, 4);
}
for (j = 0; j < 256; j += 2) {
blockEncrypt(LR, 0, LR, 0);
S2[j] = CipherUtil.GetIntBE(LR, 0);
S2[j + 1] = CipherUtil.GetIntBE(LR, 4);
}
for (j = 0; j < 256; j += 2) {
blockEncrypt(LR, 0, LR, 0);
S3[j] = CipherUtil.GetIntBE(LR, 0);
S3[j + 1] = CipherUtil.GetIntBE(LR, 4);
}
}
public void blockEncrypt(byte[] input, int inOffset, byte[] output, int outOffset) {
uint L, R;
L = CipherUtil.GetIntBE(input, inOffset);
R = CipherUtil.GetIntBE(input, inOffset + 4);
L ^= P[0];
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[1]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[2]);
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[3]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[4]);
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[5]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[6]);
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[7]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[8]);
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[9]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[10]);
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[11]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[12]);
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[13]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[14]);
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[15]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[16]);
R ^= P[17];
CipherUtil.PutIntBE(R, output, outOffset);
CipherUtil.PutIntBE(L, output, outOffset + 4);
}
public void blockDecrypt(byte[] input, int inOffset, byte[] output, int outOffset) {
uint L, R;
L = CipherUtil.GetIntBE(input, inOffset);
R = CipherUtil.GetIntBE(input, inOffset + 4);
L ^= P[17];
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[16]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[15]);
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[14]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[13]);
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[12]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[11]);
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[10]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[9]);
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[8]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[7]);
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[6]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[5]);
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[4]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[3]);
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[2]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[1]);
R ^= P[0];
CipherUtil.PutIntBE(R, output, outOffset);
CipherUtil.PutIntBE(L, output, outOffset + 4);
}
public void encryptSSH1Style(byte[] src, int srcOff, int len, byte[] dest, int destOff) {
int end = srcOff + len;
int i, j;
for (int si = srcOff, di = destOff; si < end; si += 8, di += 8) {
for (i = 0; i < 4; i++) {
j = 3 - i;
IV[i] ^= src[si + j];
IV[i + 4] ^= src[si + 4 + j];
}
blockEncrypt(IV, 0, IV, 0);
for (i = 0; i < 4; i++) {
j = 3 - i;
dest[di + i] = IV[j];
dest[di + i + 4] = IV[4 + j];
}
}
}
public void decryptSSH1Style(byte[] src, int srcOff, int len, byte[] dest, int destOff) {
int end = srcOff + len;
int i, j;
for (int si = srcOff, di = destOff; si < end; si += 8, di += 8) {
for (i = 0; i < 4; i++) {
j = (3 - i);
enc[i] = src[si + j];
enc[i + 4] = src[si + 4 + j];
}
blockDecrypt(enc, 0, dec, 0);
for (i = 0; i < 4; i++) {
j = 3 - i;
dest[di + i] = (byte)((IV[j] ^ dec[j]) & 0xff);
IV[j] = enc[j];
dest[di + i + 4] = (byte)((IV[4 + j] ^ dec[4 + j]) & 0xff);
IV[4 + j] = enc[4 + j];
}
}
}
public void encryptCBC(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) {
int nBlocks = inputLen / BLOCK_SIZE;
for (int bc = 0; bc < nBlocks; bc++) {
CipherUtil.BlockXor(input, inputOffset, BLOCK_SIZE, IV, 0);
blockEncrypt(IV, 0, output, outputOffset);
Array.Copy(output, outputOffset, IV, 0, BLOCK_SIZE);
inputOffset += BLOCK_SIZE;
outputOffset += BLOCK_SIZE;
}
}
public void decryptCBC(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) {
byte[] tmpBlk = new byte[BLOCK_SIZE];
int nBlocks = inputLen / BLOCK_SIZE;
for (int bc = 0; bc < nBlocks; bc++) {
blockDecrypt(input, inputOffset, tmpBlk, 0);
for (int i = 0; i < BLOCK_SIZE; i++) {
tmpBlk[i] ^= IV[i];
IV[i] = input[inputOffset + i];
output[outputOffset + i] = tmpBlk[i];
}
inputOffset += BLOCK_SIZE;
outputOffset += BLOCK_SIZE;
}
}
private static readonly uint[] blowfish_pbox = new uint[] {
0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,
0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
0x9216d5d9, 0x8979fb1b
};
private static readonly uint[] blowfish_sbox = new uint[] {
0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,
0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,
0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,
0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,
0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,
0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,
0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,
0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,
0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,
0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,
0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,
0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,
0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,
0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,
0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,
0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,
0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,
0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,
0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,
0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,
0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,
0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,
0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,
0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,
0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,
0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,
0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,
0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,
0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,
0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,
0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,
0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,
0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,
0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,
0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,
0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,
0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,
0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,
0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,
0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,
0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,
0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,
0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,
0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,
0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,
0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,
0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,
0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,
0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,
0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,
0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,
0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,
0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,
0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,
0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,
0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,
0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,
0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,
0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,
0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,
0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,
0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,
0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,
0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,
0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,
0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,
0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,
0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,
0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,
0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,
0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,
0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,
0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,
0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,
0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,
0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,
0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
};
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Linq.Expressions;
using System.Reactive.Linq;
using System.Reflection;
using System.Web;
using Linq2Rest.Parser;
namespace Pushqa.Server {
/// <summary>
/// Deserializes URI oData queries into IQbservables
/// </summary>
public class UriQueryDeserializer {
/// <summary>
/// Deserializes the specified query.
/// </summary>
/// <param name="query">The query.</param>
/// <param name="uri">The URI.</param>
/// <returns></returns>
public IQbservable<T> Deserialize<T>(IQbservable<T> query, Uri uri) {
Contract.Requires(query != null);
Contract.Requires(uri != null);
ServiceQuery serviceQuery = GetServiceQuery(uri);
return Deserialize<T>(query, serviceQuery.QueryParts);
}
/// <summary>
/// Deserializes the specified query.
/// </summary>
/// <param name="query">The query.</param>
/// <param name="itemType">Type of the item.</param>
/// <param name="uri">The URI.</param>
/// <returns></returns>
public IQbservable Deserialize(IQbservable query, Type itemType, Uri uri) {
Contract.Requires(query != null);
Contract.Requires(uri != null);
ServiceQuery serviceQuery = GetServiceQuery(uri);
return Deserialize(query, itemType, serviceQuery.QueryParts);
}
/// <summary>
/// Gets the name of the resource.
/// </summary>
/// <param name="uri">The URI.</param>
/// <returns></returns>
public string GetResourceName(Uri uri) {
return uri.Segments.Last().Trim('/');
}
internal static ServiceQuery GetServiceQuery(Uri uri) {
Contract.Requires(uri != null);
NameValueCollection queryPartCollection = HttpUtility.ParseQueryString(uri.Query);
List<ServiceQueryPart> serviceQueryParts = new List<ServiceQueryPart>();
foreach (string queryPart in queryPartCollection) {
if (queryPart == null || !queryPart.StartsWith("$", StringComparison.Ordinal)) {
// not a special query string
continue;
}
foreach (string value in queryPartCollection.GetValues(queryPart)) {
ServiceQueryPart serviceQueryPart = new ServiceQueryPart(queryPart.Substring(1), value);
serviceQueryParts.Add(serviceQueryPart);
}
}
// Query parts for OData need to be ordered $filter, $orderby, $skip, $top. For this
// set of query operators, they are already in alphabetical order, so it suffices to
// order by operator name. In the future if we support other operators, this may need
// to be reexamined.
serviceQueryParts = serviceQueryParts.OrderBy(p => p.QueryOperator).ToList();
ServiceQuery serviceQuery = new ServiceQuery() {
QueryParts = serviceQueryParts,
};
return serviceQuery;
}
internal static IQbservable<T> Deserialize<T>(IQbservable<T> query, IEnumerable<ServiceQueryPart> queryParts) {
Contract.Requires(query != null);
Contract.Requires(queryParts != null);
int? skip = null;
int? top = null;
foreach (ServiceQueryPart part in queryParts) {
switch (part.QueryOperator) {
case "filter":
FilterExpressionFactory filterExpressionFactory = new FilterExpressionFactory();
Expression<Func<T, bool>> expression = filterExpressionFactory.Create<T>(part.Expression);
query = query.Where(expression);
break;
case "orderby":
throw new NotSupportedException("The query operator 'orderby' is not supported for event streams");
case "skip":
int skipValue;
if (int.TryParse(part.Expression, out skipValue)) {
skip = skipValue;
}
break;
case "top":
int topValue;
if (int.TryParse(part.Expression, out topValue)) {
top = topValue;
}
break;
}
}
if(skip != null) {
query = query.Skip(skip.Value);
}
if (top != null) {
query = query.Take(top.Value);
}
return query;
}
internal static IQbservable Deserialize(IQbservable messageSource, Type itemType, IEnumerable<ServiceQueryPart> queryParts) {
if (!typeof(IQbservable<>).MakeGenericType(new[] { itemType }).IsInstanceOfType(messageSource)) {
throw new NotImplementedException("CUstom exception handling");
}
Func<IQbservable<int>, IEnumerable<ServiceQueryPart>, IQbservable<int>> dummyAction = Deserialize<int>;
MethodInfo methodInfo = dummyAction.Method.GetGenericMethodDefinition().MakeGenericMethod(new[] {itemType});
return methodInfo.Invoke(null, new object[] {messageSource, queryParts}) as IQbservable;
}
}
/// <summary>
/// Represents an <see cref="System.Linq.IQueryable"/>.
/// </summary>
internal class ServiceQuery
{
/// <summary>
/// Gets or sets a list of query parts.
/// </summary>
public IEnumerable<ServiceQueryPart> QueryParts
{
get;
set;
}
}
/// <summary>
/// Represents a single query operator to be applied to a query
/// </summary>
internal class ServiceQueryPart
{
private string _queryOperator;
private string _expression;
/// <summary>
/// Public constructor
/// </summary>
public ServiceQueryPart()
{
}
/// <summary>
/// Public constructor
/// </summary>
/// <param name="queryOperator">The query operator</param>
/// <param name="expression">The query expression</param>
public ServiceQueryPart(string queryOperator, string expression)
{
if (queryOperator == null)
{
throw new ArgumentNullException("queryOperator");
}
if (expression == null)
{
throw new ArgumentNullException("expression");
}
if (queryOperator != "filter" && queryOperator != "orderby" &&
queryOperator != "skip" && queryOperator != "top")
{
throw new ArgumentException("Invalid Query Operator '{0}'", "queryOperator");
}
this._queryOperator = queryOperator;
this._expression = expression;
}
/// <summary>
/// Gets or sets the query operator. Must be one of the supported operators : "where", "orderby", "skip", or "take".
/// </summary>
public string QueryOperator
{
get
{
return this._queryOperator;
}
set
{
this._queryOperator = value;
}
}
/// <summary>
/// Gets or sets the query expression.
/// </summary>
public string Expression
{
get
{
return this._expression;
}
set
{
this._expression = value;
}
}
/// <summary>
/// Returns a string representation of this <see cref="ServiceQueryPart"/>
/// </summary>
/// <returns>The string representation of this <see cref="ServiceQueryPart"/></returns>
public override string ToString()
{
return string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}={1}", this.QueryOperator, this.Expression);
}
}
}
| |
using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace PersonalCheckDigit
{
/// <summary>
/// Represents an identification number where the rightmost digit is the check digit.
/// </summary>
public class LuhnCheckDigit : IComparable, IComparable<LuhnCheckDigit>,
IEquatable<LuhnCheckDigit>
{
/// <summary>
/// Initializes a new instance of the LuhnCheckDigit class.
/// </summary>
/// <param name="significantNumberOfDigits">
/// A number used to determin the number of digits,
/// counted from right to left, to be a part of the validation.
/// </param>
/// <param name="number">The number to be validated.</param>
public LuhnCheckDigit(string number = "", uint significantNumberOfDigits = 0)
{
Number = number;
SignificantNumberOfDigits = significantNumberOfDigits;
}
/// <summary>
/// Gets or sets the identification number.
/// </summary>
public string Number { get; set; }
/// <summary>
/// Gets a value indicating whether the identification number is valid.
/// </summary>
public virtual bool IsValid
{
get
{
var digits = ToIntArray();
if (!digits.Any())
{
return false;
}
var multiplier = 1;
var sum = 0;
foreach (var digit in digits.Reverse())
{
var digitProduct = digit * multiplier;
sum += digitProduct / 10 + digitProduct % 10;
multiplier ^= 3; // Toggles between 1 and 2 (1 XOR 3 = 2, 2 XOR 3 = 1)
}
return sum % 10 == 0;
}
}
/// <summary>
/// Gets the identification number containing only digits.
/// </summary>
protected string SanitizedNumber =>
Regex.Replace(Number ?? string.Empty, @"\D", string.Empty);
/// <summary>
/// Gets or sets the number of digits, counted from right to left,
/// to be validated.
/// </summary>
public uint SignificantNumberOfDigits { get; set; }
/// <summary>
/// Compares the current instance with another object of the same type.
/// </summary>
/// <param name="obj">An object to compare with this instance.</param>
/// <returns>
/// A signed number indicating the relative values of this
/// instance and the value parameter.Less than zero: this instance is
/// less than value. Zero: this instance is equal to value.
/// Greater than zero: this instance is greater than value.
/// </returns>
public virtual int CompareTo(object obj)
{
if (ReferenceEquals(obj, null))
{
return 1;
}
var other = obj as LuhnCheckDigit;
if (other == null)
{
throw new ArgumentException("Object is not a LuhnCheckDigit.");
}
return CompareTo(other);
}
/// <summary>
/// Compares the current instance with another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this instance.</param>
/// <returns>
/// A signed number indicating the relative values of this
/// instance and the value parameter.Less than zero: this instance is
/// less than value. Zero: this instance is equal to value.
/// Greater than zero: this instance is greater than value.
/// </returns>
public int CompareTo(LuhnCheckDigit other)
{
if (ReferenceEquals(other, null))
{
return 1;
}
if (Equals(other))
{
return 0;
}
var result = string.CompareOrdinal(Number, other.Number);
if (result == 0)
{
result = SignificantNumberOfDigits.CompareTo(other.SignificantNumberOfDigits);
}
return result;
}
/// <summary>
/// Determines whether this instance and another specified
/// LuhnCheckDigit object have the same value.
/// </summary>
/// <param name="other">A LuhnCheckDigit.</param>
/// <returns>
/// true if the value of the value parameter is the
/// same as this instance; otherwise, false.
/// </returns>
public bool Equals(LuhnCheckDigit other)
{
if (other == null || GetType() != other.GetType())
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
if (GetHashCode() != other.GetHashCode())
{
return false;
}
return string.Equals(Number, other.Number) &&
SignificantNumberOfDigits.Equals(other.SignificantNumberOfDigits);
}
/// <summary>
/// Creates a new object that is a deep copy of the current instance.
/// </summary>
/// <returns>A new object that is a deep copy of this instance.</returns>
public LuhnCheckDigit Copy() => (LuhnCheckDigit) MemberwiseClone();
/// <summary>
/// Returns an array of integers containing the rightmost significant digits of this instance.
/// </summary>
/// <returns>An int array.</returns>
protected virtual int[] ToIntArray()
{
var digits = SanitizedNumber.ToArray();
// If specified take the rightmost significant digits.
if (SignificantNumberOfDigits > 0)
{
digits = digits.Skip(Math.Max(0, digits.Count() - (int) SignificantNumberOfDigits)).ToArray();
}
return digits.Select(x => (int) char.GetNumericValue(x)).ToArray();
}
/// <summary>
/// Determines whether this instance of IdentificationNumber and a specified object,
/// which must also be a IdentificationNumber object, have the same value.
/// </summary>
/// <param name="obj">An Object.</param>
/// <returns>
/// true if obj is a IdentificationNumber and its value is the same as this
/// instance; otherwise, false.
/// </returns>
public override bool Equals(object obj) => Equals(obj as LuhnCheckDigit);
/// <summary>
/// Returns the hash code for this object.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
unchecked // "overflow" is ok
{
var hash = (int) 2166136261;
hash = (hash * 16777619) ^ Number?.GetHashCode() ?? 0;
hash = (hash * 16777619) ^ SignificantNumberOfDigits.GetHashCode();
return hash;
}
}
/// <summary>
/// Converts the attributes of this IdentificationNumber to a human-readable string.
/// </summary>
/// <returns></returns>
public override string ToString()
=> $"{Number} [{SignificantNumberOfDigits} => {string.Join(string.Empty, ToIntArray())}]";
/// <summary>
/// Determines whether two specified LuhnCheckDigit objects have the same value.
/// </summary>
/// <param name="a">A LuhnCheckDigit or null.</param>
/// <param name="b">A LuhnCheckDigit or null.</param>
/// <returns>true if the value of objA is the same as the value of objB; otherwise, false.</returns>
public static bool operator ==(LuhnCheckDigit a, LuhnCheckDigit b)
=> a?.Equals(b) ?? ReferenceEquals(b, null);
/// <summary>
/// Determines whether two specified LuhnCheckDigit objects have different values.
/// </summary>
/// <param name="a">A LuhnCheckDigit or null.</param>
/// <param name="b">A LuhnCheckDigit or null.</param>
/// <returns>true if the value of objA is different from the value of objB; otherwise, false.</returns>
public static bool operator !=(LuhnCheckDigit a, LuhnCheckDigit b) => !(a == b);
}
}
| |
// 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.ComponentModel.Composition.Hosting;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using EnvDTE;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Storage;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions;
using Microsoft.VisualStudio.LanguageServices.Utilities;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.TextManager.Interop;
using Roslyn.Utilities;
using Roslyn.VisualStudio.ProjectSystem;
using VSLangProj;
using VSLangProj140;
using OLEServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
using OleInterop = Microsoft.VisualStudio.OLE.Interop;
using Microsoft.CodeAnalysis.Esent;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
/// <summary>
/// The Workspace for running inside Visual Studio.
/// </summary>
internal abstract partial class VisualStudioWorkspaceImpl : VisualStudioWorkspace
{
private static readonly IntPtr s_docDataExisting_Unknown = new IntPtr(-1);
private const string AppCodeFolderName = "App_Code";
// document worker coordinator
private ISolutionCrawlerRegistrationService _registrationService;
/// <summary>
/// A <see cref="ForegroundThreadAffinitizedObject"/> to make assertions that stuff is on the right thread.
/// This is Lazy because it might be created on a background thread when nothing is initialized yet.
/// </summary>
private readonly Lazy<ForegroundThreadAffinitizedObject> _foregroundObject
= new Lazy<ForegroundThreadAffinitizedObject>(() => new ForegroundThreadAffinitizedObject());
/// <summary>
/// The <see cref="DeferredInitializationState"/> that consists of the <see cref="VisualStudioProjectTracker" />
/// and other UI-initialized types. It will be created as long as a single project has been created.
/// </summary>
internal DeferredInitializationState DeferredState { get; private set; }
public VisualStudioWorkspaceImpl(ExportProvider exportProvider)
: base(
MefV1HostServices.Create(exportProvider),
backgroundWork: WorkspaceBackgroundWork.ParseAndCompile)
{
PrimaryWorkspace.Register(this);
}
/// <summary>
/// Ensures the workspace is fully hooked up to the host by subscribing to all sorts of VS
/// UI thread affinitized events.
/// </summary>
internal VisualStudioProjectTracker GetProjectTrackerAndInitializeIfNecessary(IServiceProvider serviceProvider)
{
if (DeferredState == null)
{
_foregroundObject.Value.AssertIsForeground();
DeferredState = new DeferredInitializationState(this, serviceProvider);
}
return DeferredState.ProjectTracker;
}
/// <summary>
/// A compatibility shim to ensure that F# and TypeScript continue to work after the deferred work goes in. This will be
/// removed once they move to calling <see cref="GetProjectTrackerAndInitializeIfNecessary"/>.
/// </summary>
internal VisualStudioProjectTracker ProjectTracker
{
get
{
return GetProjectTrackerAndInitializeIfNecessary(ServiceProvider.GlobalProvider);
}
}
internal void ClearReferenceCache()
{
DeferredState?.ProjectTracker.MetadataReferenceProvider.ClearCache();
}
internal IVisualStudioHostDocument GetHostDocument(DocumentId documentId)
{
var project = GetHostProject(documentId.ProjectId);
if (project != null)
{
return project.GetDocumentOrAdditionalDocument(documentId);
}
return null;
}
internal IVisualStudioHostProject GetHostProject(ProjectId projectId)
{
return DeferredState?.ProjectTracker.GetProject(projectId);
}
private bool TryGetHostProject(ProjectId projectId, out IVisualStudioHostProject project)
{
project = GetHostProject(projectId);
return project != null;
}
internal override bool TryApplyChanges(
Microsoft.CodeAnalysis.Solution newSolution,
IProgressTracker progressTracker)
{
if (_foregroundObject.IsValueCreated && !_foregroundObject.Value.IsForeground())
{
throw new InvalidOperationException(ServicesVSResources.VisualStudioWorkspace_TryApplyChanges_cannot_be_called_from_a_background_thread);
}
var projectChanges = newSolution.GetChanges(this.CurrentSolution).GetProjectChanges().ToList();
var projectsToLoad = new HashSet<Guid>();
foreach (var pc in projectChanges)
{
if (pc.GetAddedAdditionalDocuments().Any() ||
pc.GetAddedAnalyzerReferences().Any() ||
pc.GetAddedDocuments().Any() ||
pc.GetAddedMetadataReferences().Any() ||
pc.GetAddedProjectReferences().Any() ||
pc.GetRemovedAdditionalDocuments().Any() ||
pc.GetRemovedAnalyzerReferences().Any() ||
pc.GetRemovedDocuments().Any() ||
pc.GetRemovedMetadataReferences().Any() ||
pc.GetRemovedProjectReferences().Any())
{
projectsToLoad.Add(GetHostProject(pc.ProjectId).Guid);
}
}
if (projectsToLoad.Any())
{
var vsSolution4 = (IVsSolution4)DeferredState.ServiceProvider.GetService(typeof(SVsSolution));
vsSolution4.EnsureProjectsAreLoaded(
(uint)projectsToLoad.Count,
projectsToLoad.ToArray(),
(uint)__VSBSLFLAGS.VSBSLFLAGS_None);
}
// first make sure we can edit the document we will be updating (check them out from source control, etc)
var changedDocs = projectChanges.SelectMany(pd => pd.GetChangedDocuments()).ToList();
if (changedDocs.Count > 0)
{
this.EnsureEditableDocuments(changedDocs);
}
return base.TryApplyChanges(newSolution, progressTracker);
}
public override bool CanOpenDocuments
{
get
{
return true;
}
}
internal override bool CanChangeActiveContextDocument
{
get
{
return true;
}
}
internal override bool CanRenameFilesDuringCodeActions(CodeAnalysis.Project project)
{
if (this.TryGetHierarchy(project.Id, out var hierarchy))
{
// Currently renaming files in CPS projects (i.e. .Net Core) doesn't work proprey.
// This is because the remove/add of the documents in CPS is not synchronous
// (despite the DTE interfaces being synchronous). So Roslyn calls the methods
// expecting the changes to happen immediately. Because they are deferred in CPS
// this causes problems.
return !hierarchy.IsCapabilityMatch("CPS");
}
return true;
}
protected override bool CanApplyParseOptionChange(ParseOptions oldOptions, ParseOptions newOptions, CodeAnalysis.Project project)
{
var parseOptionsService = project.LanguageServices.GetService<IParseOptionsService>();
if (parseOptionsService == null)
{
return false;
}
// Currently, only changes to the LanguageVersion of parse options are supported.
var newLanguageVersion = parseOptionsService.GetLanguageVersion(newOptions);
var updated = parseOptionsService.WithLanguageVersion(oldOptions, newLanguageVersion);
return newOptions == updated;
}
public override bool CanApplyChange(ApplyChangesKind feature)
{
switch (feature)
{
case ApplyChangesKind.AddDocument:
case ApplyChangesKind.RemoveDocument:
case ApplyChangesKind.ChangeDocument:
case ApplyChangesKind.AddMetadataReference:
case ApplyChangesKind.RemoveMetadataReference:
case ApplyChangesKind.AddProjectReference:
case ApplyChangesKind.RemoveProjectReference:
case ApplyChangesKind.AddAnalyzerReference:
case ApplyChangesKind.RemoveAnalyzerReference:
case ApplyChangesKind.AddAdditionalDocument:
case ApplyChangesKind.RemoveAdditionalDocument:
case ApplyChangesKind.ChangeAdditionalDocument:
case ApplyChangesKind.ChangeParseOptions:
return true;
default:
return false;
}
}
private bool TryGetProjectData(ProjectId projectId, out IVisualStudioHostProject hostProject, out IVsHierarchy hierarchy, out EnvDTE.Project project)
{
hierarchy = null;
project = null;
return this.TryGetHostProject(projectId, out hostProject)
&& this.TryGetHierarchy(projectId, out hierarchy)
&& hierarchy.TryGetProject(out project);
}
internal void GetProjectData(ProjectId projectId, out IVisualStudioHostProject hostProject, out IVsHierarchy hierarchy, out EnvDTE.Project project)
{
if (!TryGetProjectData(projectId, out hostProject, out hierarchy, out project))
{
throw new ArgumentException(string.Format(ServicesVSResources.Could_not_find_project_0, projectId));
}
}
internal EnvDTE.Project TryGetDTEProject(ProjectId projectId)
{
return TryGetProjectData(projectId, out var hostProject, out var hierarchy, out var project) ? project : null;
}
internal bool TryAddReferenceToProject(ProjectId projectId, string assemblyName)
{
EnvDTE.Project project;
try
{
GetProjectData(projectId, out var hostProject, out var hierarchy, out project);
}
catch (ArgumentException)
{
return false;
}
var vsProject = (VSProject)project.Object;
try
{
vsProject.References.Add(assemblyName);
}
catch (Exception)
{
return false;
}
return true;
}
private string GetAnalyzerPath(AnalyzerReference analyzerReference)
{
return analyzerReference.FullPath;
}
protected override void ApplyParseOptionsChanged(ProjectId projectId, ParseOptions options)
{
if (projectId == null)
{
throw new ArgumentNullException(nameof(projectId));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
var parseOptionsService = CurrentSolution.GetProject(projectId).LanguageServices.GetService<IParseOptionsService>();
Contract.ThrowIfNull(parseOptionsService, nameof(parseOptionsService));
string newVersion = parseOptionsService.GetLanguageVersion(options);
GetProjectData(projectId, out var hostProject, out var hierarchy, out var project);
foreach (string configurationName in (object[])project.ConfigurationManager.ConfigurationRowNames)
{
switch (hostProject.Language)
{
case LanguageNames.CSharp:
var csharpProperties = (VSLangProj80.CSharpProjectConfigurationProperties3)project.ConfigurationManager
.ConfigurationRow(configurationName).Item(1).Object;
if (newVersion != csharpProperties.LanguageVersion)
{
csharpProperties.LanguageVersion = newVersion;
}
break;
case LanguageNames.VisualBasic:
throw new InvalidOperationException(ServicesVSResources.This_workspace_does_not_support_updating_Visual_Basic_parse_options);
}
}
}
protected override void ApplyAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference)
{
if (projectId == null)
{
throw new ArgumentNullException(nameof(projectId));
}
if (analyzerReference == null)
{
throw new ArgumentNullException(nameof(analyzerReference));
}
GetProjectData(projectId, out var hostProject, out var hierarchy, out var project);
string filePath = GetAnalyzerPath(analyzerReference);
if (filePath != null)
{
VSProject3 vsProject = (VSProject3)project.Object;
vsProject.AnalyzerReferences.Add(filePath);
}
}
protected override void ApplyAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference)
{
if (projectId == null)
{
throw new ArgumentNullException(nameof(projectId));
}
if (analyzerReference == null)
{
throw new ArgumentNullException(nameof(analyzerReference));
}
GetProjectData(projectId, out var hostProject, out var hierarchy, out var project);
string filePath = GetAnalyzerPath(analyzerReference);
if (filePath != null)
{
VSProject3 vsProject = (VSProject3)project.Object;
vsProject.AnalyzerReferences.Remove(filePath);
}
}
private string GetMetadataPath(MetadataReference metadataReference)
{
var fileMetadata = metadataReference as PortableExecutableReference;
if (fileMetadata != null)
{
return fileMetadata.FilePath;
}
return null;
}
protected override void ApplyMetadataReferenceAdded(
ProjectId projectId, MetadataReference metadataReference)
{
if (projectId == null)
{
throw new ArgumentNullException(nameof(projectId));
}
if (metadataReference == null)
{
throw new ArgumentNullException(nameof(metadataReference));
}
GetProjectData(projectId, out var hostProject, out var hierarchy, out var project);
string filePath = GetMetadataPath(metadataReference);
if (filePath != null)
{
VSProject vsProject = (VSProject)project.Object;
vsProject.References.Add(filePath);
var undoManager = TryGetUndoManager();
undoManager?.Add(new RemoveMetadataReferenceUndoUnit(this, projectId, filePath));
}
}
protected override void ApplyMetadataReferenceRemoved(
ProjectId projectId, MetadataReference metadataReference)
{
if (projectId == null)
{
throw new ArgumentNullException(nameof(projectId));
}
if (metadataReference == null)
{
throw new ArgumentNullException(nameof(metadataReference));
}
GetProjectData(projectId, out var hostProject, out var hierarchy, out var project);
string filePath = GetMetadataPath(metadataReference);
if (filePath != null)
{
VSProject vsProject = (VSProject)project.Object;
foreach (Reference reference in vsProject.References)
{
if (StringComparer.OrdinalIgnoreCase.Equals(reference.Path, filePath))
{
reference.Remove();
var undoManager = TryGetUndoManager();
undoManager?.Add(new AddMetadataReferenceUndoUnit(this, projectId, filePath));
break;
}
}
}
}
protected override void ApplyProjectReferenceAdded(
ProjectId projectId, ProjectReference projectReference)
{
if (projectId == null)
{
throw new ArgumentNullException(nameof(projectId));
}
if (projectReference == null)
{
throw new ArgumentNullException(nameof(projectReference));
}
GetProjectData(projectId, out var hostProject, out var hierarchy, out var project);
GetProjectData(projectReference.ProjectId, out var refHostProject, out var refHierarchy, out var refProject);
var vsProject = (VSProject)project.Object;
vsProject.References.AddProject(refProject);
var undoManager = TryGetUndoManager();
undoManager?.Add(new RemoveProjectReferenceUndoUnit(
this, projectId, projectReference.ProjectId));
}
private OleInterop.IOleUndoManager TryGetUndoManager()
{
var documentTrackingService = this.Services.GetService<IDocumentTrackingService>();
if (documentTrackingService != null)
{
var documentId = documentTrackingService.GetActiveDocument() ?? documentTrackingService.GetVisibleDocuments().FirstOrDefault();
if (documentId != null)
{
var composition = (IComponentModel)this.DeferredState.ServiceProvider.GetService(typeof(SComponentModel));
var exportProvider = composition.DefaultExportProvider;
var editorAdaptersService = exportProvider.GetExportedValue<IVsEditorAdaptersFactoryService>();
return editorAdaptersService.TryGetUndoManager(this, documentId, CancellationToken.None);
}
}
return null;
}
protected override void ApplyProjectReferenceRemoved(
ProjectId projectId, ProjectReference projectReference)
{
if (projectId == null)
{
throw new ArgumentNullException(nameof(projectId));
}
if (projectReference == null)
{
throw new ArgumentNullException(nameof(projectReference));
}
GetProjectData(projectId, out var hostProject, out var hierarchy, out var project);
GetProjectData(projectReference.ProjectId, out var refHostProject, out var refHierarchy, out var refProject);
var vsProject = (VSProject)project.Object;
foreach (Reference reference in vsProject.References)
{
if (reference.SourceProject == refProject)
{
reference.Remove();
var undoManager = TryGetUndoManager();
undoManager?.Add(new AddProjectReferenceUndoUnit(this, projectId, projectReference.ProjectId));
}
}
}
protected override void ApplyDocumentAdded(DocumentInfo info, SourceText text)
{
AddDocumentCore(info, text, isAdditionalDocument: false);
}
protected override void ApplyAdditionalDocumentAdded(DocumentInfo info, SourceText text)
{
AddDocumentCore(info, text, isAdditionalDocument: true);
}
private void AddDocumentCore(DocumentInfo info, SourceText initialText, bool isAdditionalDocument)
{
GetProjectData(info.Id.ProjectId, out var hostProject, out var hierarchy, out var project);
// If the first namespace name matches the name of the project, then we don't want to
// generate a folder for that. The project is implicitly a folder with that name.
var folders = info.Folders.AsEnumerable();
if (folders.FirstOrDefault() == project.Name)
{
folders = folders.Skip(1);
}
folders = FilterFolderForProjectType(project, folders);
if (IsWebsite(project))
{
AddDocumentToFolder(hostProject, project, info.Id, SpecializedCollections.SingletonEnumerable(AppCodeFolderName), info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument);
}
else if (folders.Any())
{
AddDocumentToFolder(hostProject, project, info.Id, folders, info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument);
}
else
{
AddDocumentToProject(hostProject, project, info.Id, info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument);
}
var undoManager = TryGetUndoManager();
if (isAdditionalDocument)
{
undoManager?.Add(new RemoveAdditionalDocumentUndoUnit(this, info.Id));
}
else
{
undoManager?.Add(new RemoveDocumentUndoUnit(this, info.Id));
}
}
private bool IsWebsite(EnvDTE.Project project)
{
return project.Kind == VsWebSite.PrjKind.prjKindVenusProject;
}
private IEnumerable<string> FilterFolderForProjectType(EnvDTE.Project project, IEnumerable<string> folders)
{
foreach (var folder in folders)
{
var items = GetAllItems(project.ProjectItems);
var folderItem = items.FirstOrDefault(p => StringComparer.OrdinalIgnoreCase.Compare(p.Name, folder) == 0);
if (folderItem == null || folderItem.Kind != EnvDTE.Constants.vsProjectItemKindPhysicalFile)
{
yield return folder;
}
}
}
private IEnumerable<ProjectItem> GetAllItems(ProjectItems projectItems)
{
if (projectItems == null)
{
return SpecializedCollections.EmptyEnumerable<ProjectItem>();
}
var items = projectItems.OfType<ProjectItem>();
return items.Concat(items.SelectMany(i => GetAllItems(i.ProjectItems)));
}
#if false
protected override void AddExistingDocument(DocumentId documentId, string filePath, IEnumerable<string> folders)
{
IVsHierarchy hierarchy;
EnvDTE.Project project;
IVisualStudioHostProject hostProject;
GetProjectData(documentId.ProjectId, out hostProject, out hierarchy, out project);
// If the first namespace name matches the name of the project, then we don't want to
// generate a folder for that. The project is implicitly a folder with that name.
if (folders.FirstOrDefault() == project.Name)
{
folders = folders.Skip(1);
}
var name = Path.GetFileName(filePath);
if (folders.Any())
{
AddDocumentToFolder(hostProject, project, documentId, folders, name, SourceCodeKind.Regular, initialText: null, filePath: filePath);
}
else
{
AddDocumentToProject(hostProject, project, documentId, name, SourceCodeKind.Regular, initialText: null, filePath: filePath);
}
}
#endif
private ProjectItem AddDocumentToProject(
IVisualStudioHostProject hostProject,
EnvDTE.Project project,
DocumentId documentId,
string documentName,
SourceCodeKind sourceCodeKind,
SourceText initialText = null,
string filePath = null,
bool isAdditionalDocument = false)
{
if (!project.TryGetFullPath(out var folderPath))
{
// TODO(cyrusn): Throw an appropriate exception here.
throw new Exception(ServicesVSResources.Could_not_find_location_of_folder_on_disk);
}
return AddDocumentToProjectItems(hostProject, project.ProjectItems, documentId, folderPath, documentName, sourceCodeKind, initialText, filePath, isAdditionalDocument);
}
private ProjectItem AddDocumentToFolder(
IVisualStudioHostProject hostProject,
EnvDTE.Project project,
DocumentId documentId,
IEnumerable<string> folders,
string documentName,
SourceCodeKind sourceCodeKind,
SourceText initialText = null,
string filePath = null,
bool isAdditionalDocument = false)
{
var folder = project.FindOrCreateFolder(folders);
if (!folder.TryGetFullPath(out var folderPath))
{
// TODO(cyrusn): Throw an appropriate exception here.
throw new Exception(ServicesVSResources.Could_not_find_location_of_folder_on_disk);
}
return AddDocumentToProjectItems(hostProject, folder.ProjectItems, documentId, folderPath, documentName, sourceCodeKind, initialText, filePath, isAdditionalDocument);
}
private ProjectItem AddDocumentToProjectItems(
IVisualStudioHostProject hostProject,
ProjectItems projectItems,
DocumentId documentId,
string folderPath,
string documentName,
SourceCodeKind sourceCodeKind,
SourceText initialText,
string filePath,
bool isAdditionalDocument)
{
if (filePath == null)
{
var baseName = Path.GetFileNameWithoutExtension(documentName);
var extension = isAdditionalDocument ? Path.GetExtension(documentName) : GetPreferredExtension(hostProject, sourceCodeKind);
var uniqueName = projectItems.GetUniqueName(baseName, extension);
filePath = Path.Combine(folderPath, uniqueName);
}
if (initialText != null)
{
using (var writer = new StreamWriter(filePath, append: false, encoding: initialText.Encoding ?? Encoding.UTF8))
{
initialText.Write(writer);
}
}
using (var documentIdHint = DeferredState.ProjectTracker.DocumentProvider.ProvideDocumentIdHint(filePath, documentId))
{
return projectItems.AddFromFile(filePath);
}
}
protected void RemoveDocumentCore(
DocumentId documentId, bool isAdditionalDocument)
{
if (documentId == null)
{
throw new ArgumentNullException(nameof(documentId));
}
var hostDocument = this.GetHostDocument(documentId);
if (hostDocument != null)
{
var document = this.CurrentSolution.GetDocument(documentId);
var text = this.GetTextForced(document);
var project = hostDocument.Project.Hierarchy as IVsProject3;
var itemId = hostDocument.GetItemId();
if (itemId == (uint)VSConstants.VSITEMID.Nil)
{
// it is no longer part of the solution
return;
}
project.RemoveItem(0, itemId, out var result);
var undoManager = TryGetUndoManager();
var docInfo = CreateDocumentInfoWithoutText(document);
if (isAdditionalDocument)
{
undoManager?.Add(new AddAdditionalDocumentUndoUnit(this, docInfo, text));
}
else
{
undoManager?.Add(new AddDocumentUndoUnit(this, docInfo, text));
}
}
}
protected override void ApplyDocumentRemoved(DocumentId documentId)
{
RemoveDocumentCore(documentId, isAdditionalDocument: false);
}
protected override void ApplyAdditionalDocumentRemoved(DocumentId documentId)
{
RemoveDocumentCore(documentId, isAdditionalDocument: true);
}
public override void OpenDocument(DocumentId documentId, bool activate = true)
{
OpenDocumentCore(documentId, activate);
}
public override void OpenAdditionalDocument(DocumentId documentId, bool activate = true)
{
OpenDocumentCore(documentId, activate);
}
public override void CloseDocument(DocumentId documentId)
{
CloseDocumentCore(documentId);
}
public override void CloseAdditionalDocument(DocumentId documentId)
{
CloseDocumentCore(documentId);
}
public void OpenDocumentCore(DocumentId documentId, bool activate = true)
{
if (documentId == null)
{
throw new ArgumentNullException(nameof(documentId));
}
if (!_foregroundObject.Value.IsForeground())
{
throw new InvalidOperationException(ServicesVSResources.This_workspace_only_supports_opening_documents_on_the_UI_thread);
}
var document = this.GetHostDocument(documentId);
if (document != null && document.Project != null)
{
if (TryGetFrame(document, out var frame))
{
if (activate)
{
frame.Show();
}
else
{
frame.ShowNoActivate();
}
}
}
}
private bool TryGetFrame(IVisualStudioHostDocument document, out IVsWindowFrame frame)
{
frame = null;
var itemId = document.GetItemId();
if (itemId == (uint)VSConstants.VSITEMID.Nil)
{
// If the ItemId is Nil, then IVsProject would not be able to open the
// document using its ItemId. Thus, we must use OpenDocumentViaProject, which only
// depends on the file path.
return ErrorHandler.Succeeded(DeferredState.ShellOpenDocumentService.OpenDocumentViaProject(
document.FilePath,
VSConstants.LOGVIEWID.TextView_guid,
out var oleServiceProvider,
out var uiHierarchy,
out var itemid,
out frame));
}
else
{
// If the ItemId is not Nil, then we should not call IVsUIShellDocument
// .OpenDocumentViaProject here because that simply takes a file path and opens the
// file within the context of the first project it finds. That would cause problems
// if the document we're trying to open is actually a linked file in another
// project. So, we get the project's hierarchy and open the document using its item
// ID.
// It's conceivable that IVsHierarchy might not implement IVsProject. However,
// OpenDocumentViaProject itself relies upon this QI working, so it should be OK to
// use here.
var vsProject = document.Project.Hierarchy as IVsProject;
return vsProject != null &&
ErrorHandler.Succeeded(vsProject.OpenItem(itemId, VSConstants.LOGVIEWID.TextView_guid, s_docDataExisting_Unknown, out frame));
}
}
public void CloseDocumentCore(DocumentId documentId)
{
if (documentId == null)
{
throw new ArgumentNullException(nameof(documentId));
}
if (this.IsDocumentOpen(documentId))
{
var document = this.GetHostDocument(documentId);
if (document != null)
{
if (ErrorHandler.Succeeded(DeferredState.ShellOpenDocumentService.IsDocumentOpen(null, 0, document.FilePath, Guid.Empty, 0, out var uiHierarchy, null, out var frame, out var isOpen)))
{
// TODO: do we need save argument for CloseDocument?
frame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave);
}
}
}
}
protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText newText)
{
EnsureEditableDocuments(documentId);
var hostDocument = GetHostDocument(documentId);
hostDocument.UpdateText(newText);
}
protected override void ApplyAdditionalDocumentTextChanged(DocumentId documentId, SourceText newText)
{
EnsureEditableDocuments(documentId);
var hostDocument = GetHostDocument(documentId);
hostDocument.UpdateText(newText);
}
private static string GetPreferredExtension(IVisualStudioHostProject hostProject, SourceCodeKind sourceCodeKind)
{
// No extension was provided. Pick a good one based on the type of host project.
switch (hostProject.Language)
{
case LanguageNames.CSharp:
// TODO: uncomment when fixing https://github.com/dotnet/roslyn/issues/5325
//return sourceCodeKind == SourceCodeKind.Regular ? ".cs" : ".csx";
return ".cs";
case LanguageNames.VisualBasic:
// TODO: uncomment when fixing https://github.com/dotnet/roslyn/issues/5325
//return sourceCodeKind == SourceCodeKind.Regular ? ".vb" : ".vbx";
return ".vb";
default:
throw new InvalidOperationException();
}
}
public override IVsHierarchy GetHierarchy(ProjectId projectId)
{
var project = this.GetHostProject(projectId);
if (project == null)
{
return null;
}
return project.Hierarchy;
}
internal override void SetDocumentContext(DocumentId documentId)
{
var hostDocument = GetHostDocument(documentId);
if (hostDocument == null)
{
// the document or project is not being tracked
return;
}
var itemId = hostDocument.GetItemId();
if (itemId == (uint)VSConstants.VSITEMID.Nil)
{
// the document has been removed from the solution
return;
}
var hierarchy = hostDocument.Project.Hierarchy;
var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hierarchy, itemId);
if (sharedHierarchy != null)
{
if (sharedHierarchy.SetProperty(
(uint)VSConstants.VSITEMID.Root,
(int)__VSHPROPID8.VSHPROPID_ActiveIntellisenseProjectContext,
DeferredState.ProjectTracker.GetProject(documentId.ProjectId).ProjectSystemName) == VSConstants.S_OK)
{
// The ASP.NET 5 intellisense project is now updated.
return;
}
else
{
// Universal Project shared files
// Change the SharedItemContextHierarchy of the project's parent hierarchy, then
// hierarchy events will trigger the workspace to update.
var hr = sharedHierarchy.SetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID7.VSHPROPID_SharedItemContextHierarchy, hierarchy);
}
}
else
{
// Regular linked files
// Transfer the item (open buffer) to the new hierarchy, and then hierarchy events
// will trigger the workspace to update.
var vsproj = hierarchy as IVsProject3;
var hr = vsproj.TransferItem(hostDocument.FilePath, hostDocument.FilePath, punkWindowFrame: null);
}
}
internal void UpdateDocumentContextIfContainsDocument(IVsHierarchy sharedHierarchy, DocumentId documentId)
{
// TODO: This is a very roundabout way to update the context
// The sharedHierarchy passed in has a new context, but we don't know what it is.
// The documentId passed in is associated with this sharedHierarchy, and this method
// will be called once for each such documentId. During this process, one of these
// documentIds will actually belong to the new SharedItemContextHierarchy. Once we
// find that one, we can map back to the open buffer and set its active context to
// the appropriate project.
// Note that if there is a single head project and it's in the process of being unloaded
// there might not be a host project.
var hostProject = LinkedFileUtilities.GetContextHostProject(sharedHierarchy, DeferredState.ProjectTracker);
if (hostProject?.Hierarchy == sharedHierarchy)
{
return;
}
if (hostProject.Id != documentId.ProjectId)
{
// While this documentId is associated with one of the head projects for this
// sharedHierarchy, it is not associated with the new context hierarchy. Another
// documentId will be passed to this method and update the context.
return;
}
// This documentId belongs to the new SharedItemContextHierarchy. Update the associated
// buffer.
OnDocumentContextUpdated(documentId);
}
/// <summary>
/// Finds the <see cref="DocumentId"/> related to the given <see cref="DocumentId"/> that
/// is in the current context. For regular files (non-shared and non-linked) and closed
/// linked files, this is always the provided <see cref="DocumentId"/>. For open linked
/// files and open shared files, the active context is already tracked by the
/// <see cref="Workspace"/> and can be looked up directly. For closed shared files, the
/// document in the shared project's <see cref="__VSHPROPID7.VSHPROPID_SharedItemContextHierarchy"/>
/// is preferred.
/// </summary>
internal override DocumentId GetDocumentIdInCurrentContext(DocumentId documentId)
{
// If the document is open, then the Workspace knows the current context for both
// linked and shared files
if (IsDocumentOpen(documentId))
{
return base.GetDocumentIdInCurrentContext(documentId);
}
var hostDocument = GetHostDocument(documentId);
var itemId = hostDocument.GetItemId();
if (itemId == (uint)VSConstants.VSITEMID.Nil)
{
// An itemid is required to determine whether the file belongs to a Shared Project
return base.GetDocumentIdInCurrentContext(documentId);
}
// If this is a regular document or a closed linked (non-shared) document, then use the
// default logic for determining current context.
var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hostDocument.Project.Hierarchy, itemId);
if (sharedHierarchy == null)
{
return base.GetDocumentIdInCurrentContext(documentId);
}
// This is a closed shared document, so we must determine the correct context.
var hostProject = LinkedFileUtilities.GetContextHostProject(sharedHierarchy, DeferredState.ProjectTracker);
var matchingProject = CurrentSolution.GetProject(hostProject.Id);
if (matchingProject == null || hostProject.Hierarchy == sharedHierarchy)
{
return base.GetDocumentIdInCurrentContext(documentId);
}
if (matchingProject.ContainsDocument(documentId))
{
// The provided documentId is in the current context project
return documentId;
}
// The current context document is from another project.
var linkedDocumentIds = CurrentSolution.GetDocument(documentId).GetLinkedDocumentIds();
var matchingDocumentId = linkedDocumentIds.FirstOrDefault(id => id.ProjectId == matchingProject.Id);
return matchingDocumentId ?? base.GetDocumentIdInCurrentContext(documentId);
}
internal bool TryGetHierarchy(ProjectId projectId, out IVsHierarchy hierarchy)
{
hierarchy = this.GetHierarchy(projectId);
return hierarchy != null;
}
public override string GetFilePath(DocumentId documentId)
{
var document = this.GetHostDocument(documentId);
if (document == null)
{
return null;
}
else
{
return document.FilePath;
}
}
internal void StartSolutionCrawler()
{
if (_registrationService == null)
{
lock (this)
{
if (_registrationService == null)
{
_registrationService = this.Services.GetService<ISolutionCrawlerRegistrationService>();
_registrationService.Register(this);
}
}
}
}
internal void StopSolutionCrawler()
{
if (_registrationService != null)
{
lock (this)
{
if (_registrationService != null)
{
_registrationService.Unregister(this, blockingShutdown: true);
_registrationService = null;
}
}
}
}
protected override void Dispose(bool finalize)
{
// workspace is going away. unregister this workspace from work coordinator
StopSolutionCrawler();
// We should consider calling this here. It is commented out because Solution event tracking was
// moved from VisualStudioProjectTracker, which is never Dispose()'d. Rather than risk the
// UnadviseSolutionEvents causing another issue (calling into dead COM objects, etc), we'll just
// continue to skip it for now.
// UnadviseSolutionEvents();
base.Dispose(finalize);
}
public void EnsureEditableDocuments(IEnumerable<DocumentId> documents)
{
var queryEdit = (IVsQueryEditQuerySave2)DeferredState.ServiceProvider.GetService(typeof(SVsQueryEditQuerySave));
var fileNames = documents.Select(GetFilePath).ToArray();
// TODO: meditate about the flags we can pass to this and decide what is most appropriate for Roslyn
int result = queryEdit.QueryEditFiles(
rgfQueryEdit: 0,
cFiles: fileNames.Length,
rgpszMkDocuments: fileNames,
rgrgf: new uint[fileNames.Length],
rgFileInfo: new VSQEQS_FILE_ATTRIBUTE_DATA[fileNames.Length],
pfEditVerdict: out var editVerdict,
prgfMoreInfo: out var editResultFlags);
if (ErrorHandler.Failed(result) ||
editVerdict != (uint)tagVSQueryEditResult.QER_EditOK)
{
throw new Exception("Unable to check out the files from source control.");
}
if ((editResultFlags & (uint)(tagVSQueryEditResultFlags2.QER_Changed | tagVSQueryEditResultFlags2.QER_Reloaded)) != 0)
{
throw new Exception("A file was reloaded during the source control checkout.");
}
}
public void EnsureEditableDocuments(params DocumentId[] documents)
{
this.EnsureEditableDocuments((IEnumerable<DocumentId>)documents);
}
internal void OnDocumentTextUpdatedOnDisk(DocumentId documentId)
{
var vsDoc = this.GetHostDocument(documentId);
this.OnDocumentTextLoaderChanged(documentId, vsDoc.Loader);
}
internal void OnAdditionalDocumentTextUpdatedOnDisk(DocumentId documentId)
{
var vsDoc = this.GetHostDocument(documentId);
this.OnAdditionalDocumentTextLoaderChanged(documentId, vsDoc.Loader);
}
internal override bool CanAddProjectReference(ProjectId referencingProject, ProjectId referencedProject)
{
_foregroundObject.Value.AssertIsForeground();
if (!TryGetHierarchy(referencingProject, out var referencingHierarchy) ||
!TryGetHierarchy(referencedProject, out var referencedHierarchy))
{
// Couldn't even get a hierarchy for this project. So we have to assume
// that adding a reference is disallowed.
return false;
}
// First we have to see if either project disallows the reference being added.
const int ContextFlags = (int)__VSQUERYFLAVORREFERENCESCONTEXT.VSQUERYFLAVORREFERENCESCONTEXT_RefreshReference;
uint canAddProjectReference = (uint)__VSREFERENCEQUERYRESULT.REFERENCE_UNKNOWN;
uint canBeReferenced = (uint)__VSREFERENCEQUERYRESULT.REFERENCE_UNKNOWN;
var referencingProjectFlavor3 = referencingHierarchy as IVsProjectFlavorReferences3;
if (referencingProjectFlavor3 != null)
{
if (ErrorHandler.Failed(referencingProjectFlavor3.QueryAddProjectReferenceEx(referencedHierarchy, ContextFlags, out canAddProjectReference, out var unused)))
{
// Something went wrong even trying to see if the reference would be allowed.
// Assume it won't be allowed.
return false;
}
if (canAddProjectReference == (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY)
{
// Adding this project reference is not allowed.
return false;
}
}
var referencedProjectFlavor3 = referencedHierarchy as IVsProjectFlavorReferences3;
if (referencedProjectFlavor3 != null)
{
if (ErrorHandler.Failed(referencedProjectFlavor3.QueryCanBeReferencedEx(referencingHierarchy, ContextFlags, out canBeReferenced, out var unused)))
{
// Something went wrong even trying to see if the reference would be allowed.
// Assume it won't be allowed.
return false;
}
if (canBeReferenced == (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY)
{
// Adding this project reference is not allowed.
return false;
}
}
// Neither project denied the reference being added. At this point, if either project
// allows the reference to be added, and the other doesn't block it, then we can add
// the reference.
if (canAddProjectReference == (int)__VSREFERENCEQUERYRESULT.REFERENCE_ALLOW ||
canBeReferenced == (int)__VSREFERENCEQUERYRESULT.REFERENCE_ALLOW)
{
return true;
}
// In both directions things are still unknown. Fallback to the reference manager
// to make the determination here.
var referenceManager = (IVsReferenceManager)DeferredState.ServiceProvider.GetService(typeof(SVsReferenceManager));
if (referenceManager == null)
{
// Couldn't get the reference manager. Have to assume it's not allowed.
return false;
}
// As long as the reference manager does not deny things, then we allow the
// reference to be added.
var result = referenceManager.QueryCanReferenceProject(referencingHierarchy, referencedHierarchy);
return result != (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY;
}
/// <summary>
/// A trivial implementation of <see cref="IVisualStudioWorkspaceHost" /> that just
/// forwards the calls down to the underlying Workspace.
/// </summary>
protected sealed class VisualStudioWorkspaceHost : IVisualStudioWorkspaceHost, IVisualStudioWorkspaceHost2, IVisualStudioWorkingFolder
{
private readonly VisualStudioWorkspaceImpl _workspace;
private readonly Dictionary<DocumentId, uint> _documentIdToHierarchyEventsCookieMap = new Dictionary<DocumentId, uint>();
public VisualStudioWorkspaceHost(VisualStudioWorkspaceImpl workspace)
{
_workspace = workspace;
}
void IVisualStudioWorkspaceHost.OnOptionsChanged(ProjectId projectId, CompilationOptions compilationOptions, ParseOptions parseOptions)
{
_workspace.OnCompilationOptionsChanged(projectId, compilationOptions);
_workspace.OnParseOptionsChanged(projectId, parseOptions);
}
void IVisualStudioWorkspaceHost.OnDocumentAdded(DocumentInfo documentInfo)
{
_workspace.OnDocumentAdded(documentInfo);
}
void IVisualStudioWorkspaceHost.OnDocumentClosed(DocumentId documentId, ITextBuffer textBuffer, TextLoader loader, bool updateActiveContext)
{
// TODO: Move this out to DocumentProvider. As is, this depends on being able to
// access the host document which will already be deleted in some cases, causing
// a crash. Until this is fixed, we will leak a HierarchyEventsSink every time a
// Mercury shared document is closed.
// UnsubscribeFromSharedHierarchyEvents(documentId);
using (_workspace.Services.GetService<IGlobalOperationNotificationService>().Start("Document Closed"))
{
_workspace.OnDocumentClosed(documentId, loader, updateActiveContext);
}
}
void IVisualStudioWorkspaceHost.OnDocumentOpened(DocumentId documentId, ITextBuffer textBuffer, bool currentContext)
{
SubscribeToSharedHierarchyEvents(documentId);
_workspace.OnDocumentOpened(documentId, textBuffer.AsTextContainer(), currentContext);
}
private void SubscribeToSharedHierarchyEvents(DocumentId documentId)
{
// Todo: maybe avoid double alerts.
var hostDocument = _workspace.GetHostDocument(documentId);
if (hostDocument == null)
{
return;
}
var hierarchy = hostDocument.Project.Hierarchy;
var itemId = hostDocument.GetItemId();
if (itemId == (uint)VSConstants.VSITEMID.Nil)
{
// the document has been removed from the solution
return;
}
var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hierarchy, itemId);
if (sharedHierarchy != null)
{
var eventSink = new HierarchyEventsSink(_workspace, sharedHierarchy, documentId);
var hr = sharedHierarchy.AdviseHierarchyEvents(eventSink, out var cookie);
if (hr == VSConstants.S_OK && !_documentIdToHierarchyEventsCookieMap.ContainsKey(documentId))
{
_documentIdToHierarchyEventsCookieMap.Add(documentId, cookie);
}
}
}
private void UnsubscribeFromSharedHierarchyEvents(DocumentId documentId)
{
var hostDocument = _workspace.GetHostDocument(documentId);
var itemId = hostDocument.GetItemId();
if (itemId == (uint)VSConstants.VSITEMID.Nil)
{
// the document has been removed from the solution
return;
}
var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hostDocument.Project.Hierarchy, itemId);
if (sharedHierarchy != null)
{
if (_documentIdToHierarchyEventsCookieMap.TryGetValue(documentId, out var cookie))
{
var hr = sharedHierarchy.UnadviseHierarchyEvents(cookie);
_documentIdToHierarchyEventsCookieMap.Remove(documentId);
}
}
}
private void RegisterPrimarySolutionForPersistentStorage(
SolutionId solutionId)
{
var service = _workspace.Services.GetService<IPersistentStorageService>() as AbstractPersistentStorageService;
if (service == null)
{
return;
}
service.RegisterPrimarySolution(solutionId);
}
private void UnregisterPrimarySolutionForPersistentStorage(
SolutionId solutionId, bool synchronousShutdown)
{
var service = _workspace.Services.GetService<IPersistentStorageService>() as AbstractPersistentStorageService;
if (service == null)
{
return;
}
service.UnregisterPrimarySolution(solutionId, synchronousShutdown);
}
void IVisualStudioWorkspaceHost.OnDocumentRemoved(DocumentId documentId)
{
_workspace.OnDocumentRemoved(documentId);
}
void IVisualStudioWorkspaceHost.OnMetadataReferenceAdded(ProjectId projectId, PortableExecutableReference metadataReference)
{
_workspace.OnMetadataReferenceAdded(projectId, metadataReference);
}
void IVisualStudioWorkspaceHost.OnMetadataReferenceRemoved(ProjectId projectId, PortableExecutableReference metadataReference)
{
_workspace.OnMetadataReferenceRemoved(projectId, metadataReference);
}
void IVisualStudioWorkspaceHost.OnProjectAdded(ProjectInfo projectInfo)
{
using (_workspace.Services.GetService<IGlobalOperationNotificationService>()?.Start("Add Project"))
{
_workspace.OnProjectAdded(projectInfo);
}
}
void IVisualStudioWorkspaceHost.OnProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference)
{
_workspace.OnProjectReferenceAdded(projectId, projectReference);
}
void IVisualStudioWorkspaceHost.OnProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference)
{
_workspace.OnProjectReferenceRemoved(projectId, projectReference);
}
void IVisualStudioWorkspaceHost.OnProjectRemoved(ProjectId projectId)
{
using (_workspace.Services.GetService<IGlobalOperationNotificationService>()?.Start("Remove Project"))
{
_workspace.OnProjectRemoved(projectId);
}
}
void IVisualStudioWorkspaceHost.OnSolutionAdded(SolutionInfo solutionInfo)
{
RegisterPrimarySolutionForPersistentStorage(solutionInfo.Id);
_workspace.OnSolutionAdded(solutionInfo);
}
void IVisualStudioWorkspaceHost.OnSolutionRemoved()
{
var solutionId = _workspace.CurrentSolution.Id;
_workspace.OnSolutionRemoved();
_workspace.ClearReferenceCache();
UnregisterPrimarySolutionForPersistentStorage(solutionId, synchronousShutdown: false);
}
void IVisualStudioWorkspaceHost.ClearSolution()
{
_workspace.ClearSolution();
_workspace.ClearReferenceCache();
}
void IVisualStudioWorkspaceHost.OnDocumentTextUpdatedOnDisk(DocumentId id)
{
_workspace.OnDocumentTextUpdatedOnDisk(id);
}
void IVisualStudioWorkspaceHost.OnAssemblyNameChanged(ProjectId id, string assemblyName)
{
_workspace.OnAssemblyNameChanged(id, assemblyName);
}
void IVisualStudioWorkspaceHost.OnOutputFilePathChanged(ProjectId id, string outputFilePath)
{
_workspace.OnOutputFilePathChanged(id, outputFilePath);
}
void IVisualStudioWorkspaceHost.OnProjectNameChanged(ProjectId projectId, string name, string filePath)
{
_workspace.OnProjectNameChanged(projectId, name, filePath);
}
void IVisualStudioWorkspaceHost.OnAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference)
{
_workspace.OnAnalyzerReferenceAdded(projectId, analyzerReference);
}
void IVisualStudioWorkspaceHost.OnAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference)
{
_workspace.OnAnalyzerReferenceRemoved(projectId, analyzerReference);
}
void IVisualStudioWorkspaceHost.OnAdditionalDocumentAdded(DocumentInfo documentInfo)
{
_workspace.OnAdditionalDocumentAdded(documentInfo);
}
void IVisualStudioWorkspaceHost.OnAdditionalDocumentRemoved(DocumentId documentInfo)
{
_workspace.OnAdditionalDocumentRemoved(documentInfo);
}
void IVisualStudioWorkspaceHost.OnAdditionalDocumentOpened(DocumentId documentId, ITextBuffer textBuffer, bool isCurrentContext)
{
_workspace.OnAdditionalDocumentOpened(documentId, textBuffer.AsTextContainer(), isCurrentContext);
}
void IVisualStudioWorkspaceHost.OnAdditionalDocumentClosed(DocumentId documentId, ITextBuffer textBuffer, TextLoader loader)
{
_workspace.OnAdditionalDocumentClosed(documentId, loader);
}
void IVisualStudioWorkspaceHost.OnAdditionalDocumentTextUpdatedOnDisk(DocumentId id)
{
_workspace.OnAdditionalDocumentTextUpdatedOnDisk(id);
}
void IVisualStudioWorkspaceHost2.OnHasAllInformation(ProjectId projectId, bool hasAllInformation)
{
_workspace.OnHasAllInformationChanged(projectId, hasAllInformation);
}
void IVisualStudioWorkingFolder.OnBeforeWorkingFolderChange()
{
UnregisterPrimarySolutionForPersistentStorage(_workspace.CurrentSolution.Id, synchronousShutdown: true);
}
void IVisualStudioWorkingFolder.OnAfterWorkingFolderChange()
{
var solutionId = _workspace.CurrentSolution.Id;
_workspace.DeferredState.ProjectTracker.UpdateSolutionProperties(solutionId);
RegisterPrimarySolutionForPersistentStorage(solutionId);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using Encoding = System.Text.Encoding;
using Microsoft.Reflection;
using System.Diagnostics.CodeAnalysis;
#if ES_BUILD_STANDALONE
using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment;
namespace Microsoft.Diagnostics.Tracing
#else
namespace System.Diagnostics.Tracing
#endif
{
/// <summary>
/// TraceLogging: Constants and utility functions.
/// </summary>
internal static class Statics
{
#region Constants
public const byte DefaultLevel = 5;
public const byte TraceLoggingChannel = 0xb;
public const byte InTypeMask = 31;
public const byte InTypeFixedCountFlag = 32;
public const byte InTypeVariableCountFlag = 64;
public const byte InTypeCustomCountFlag = 96;
public const byte InTypeCountMask = 96;
public const byte InTypeChainFlag = 128;
public const byte OutTypeMask = 127;
public const byte OutTypeChainFlag = 128;
public const EventTags EventTagsMask = (EventTags)0xfffffff;
public static readonly TraceLoggingDataType IntPtrType = IntPtr.Size == 8
? TraceLoggingDataType.Int64
: TraceLoggingDataType.Int32;
public static readonly TraceLoggingDataType UIntPtrType = IntPtr.Size == 8
? TraceLoggingDataType.UInt64
: TraceLoggingDataType.UInt32;
public static readonly TraceLoggingDataType HexIntPtrType = IntPtr.Size == 8
? TraceLoggingDataType.HexInt64
: TraceLoggingDataType.HexInt32;
#endregion
#region Metadata helpers
/// <summary>
/// A complete metadata chunk can be expressed as:
/// length16 + prefix + null-terminated-utf8-name + suffix + additionalData.
/// We assume that excludedData will be provided by some other means,
/// but that its size is known. This function returns a blob containing
/// length16 + prefix + name + suffix, with prefix and suffix initialized
/// to 0's. The length16 value is initialized to the length of the returned
/// blob plus additionalSize, so that the concatenation of the returned blob
/// plus a blob of size additionalSize constitutes a valid metadata blob.
/// </summary>
/// <param name="name">
/// The name to include in the blob.
/// </param>
/// <param name="prefixSize">
/// Amount of space to reserve before name. For provider or field blobs, this
/// should be 0. For event blobs, this is used for the tags field and will vary
/// from 1 to 4, depending on how large the tags field needs to be.
/// </param>
/// <param name="suffixSize">
/// Amount of space to reserve after name. For example, a provider blob with no
/// traits would reserve 0 extra bytes, but a provider blob with a single GroupId
/// field would reserve 19 extra bytes.
/// </param>
/// <param name="additionalSize">
/// Amount of additional data in another blob. This value will be counted in the
/// blob's length field, but will not be included in the returned byte[] object.
/// The complete blob would then be the concatenation of the returned byte[] object
/// with another byte[] object of length additionalSize.
/// </param>
/// <returns>
/// A byte[] object with the length and name fields set, with room reserved for
/// prefix and suffix. If additionalSize was 0, the byte[] object is a complete
/// blob. Otherwise, another byte[] of size additionalSize must be concatenated
/// with this one to form a complete blob.
/// </returns>
public static byte[] MetadataForString(
string name,
int prefixSize,
int suffixSize,
int additionalSize)
{
Statics.CheckName(name);
int metadataSize = Encoding.UTF8.GetByteCount(name) + 3 + prefixSize + suffixSize;
var metadata = new byte[metadataSize];
ushort totalSize = checked((ushort)(metadataSize + additionalSize));
metadata[0] = unchecked((byte)totalSize);
metadata[1] = unchecked((byte)(totalSize >> 8));
Encoding.UTF8.GetBytes(name, 0, name.Length, metadata, 2 + prefixSize);
return metadata;
}
/// <summary>
/// Serialize the low 28 bits of the tags value into the metadata stream,
/// starting at the index given by pos. Updates pos. Writes 1 to 4 bytes,
/// depending on the value of the tags variable. Usable for event tags and
/// field tags.
///
/// Note that 'metadata' can be null, in which case it only updates 'pos'.
/// This is useful for a two pass approach where you figure out how big to
/// make the array, and then you fill it in.
/// </summary>
public static void EncodeTags(int tags, ref int pos, byte[]? metadata)
{
// We transmit the low 28 bits of tags, high bits first, 7 bits at a time.
var tagsLeft = tags & 0xfffffff;
bool more;
do
{
byte current = (byte)((tagsLeft >> 21) & 0x7f);
more = (tagsLeft & 0x1fffff) != 0;
current |= (byte)(more ? 0x80 : 0x00);
tagsLeft = tagsLeft << 7;
if (metadata != null)
{
metadata[pos] = current;
}
pos += 1;
}
while (more);
}
public static byte Combine(
int settingValue,
byte defaultValue)
{
unchecked
{
return (byte)settingValue == settingValue
? (byte)settingValue
: defaultValue;
}
}
public static byte Combine(
int settingValue1,
int settingValue2,
byte defaultValue)
{
unchecked
{
return (byte)settingValue1 == settingValue1
? (byte)settingValue1
: (byte)settingValue2 == settingValue2
? (byte)settingValue2
: defaultValue;
}
}
public static int Combine(
int settingValue1,
int settingValue2)
{
unchecked
{
return (byte)settingValue1 == settingValue1
? settingValue1
: settingValue2;
}
}
public static void CheckName(string? name)
{
if (name != null && 0 <= name.IndexOf('\0'))
{
throw new ArgumentOutOfRangeException(nameof(name));
}
}
public static bool ShouldOverrideFieldName(string fieldName)
{
return (fieldName.Length <= 2 && fieldName[0] == '_');
}
public static TraceLoggingDataType MakeDataType(
TraceLoggingDataType baseType,
EventFieldFormat format)
{
return (TraceLoggingDataType)(((int)baseType & 0x1f) | ((int)format << 8));
}
/// <summary>
/// Adjusts the native type based on format.
/// - If format is default, return native.
/// - If format is recognized, return the canonical type for that format.
/// - Otherwise remove existing format from native and apply the requested format.
/// </summary>
public static TraceLoggingDataType Format8(
EventFieldFormat format,
TraceLoggingDataType native)
{
switch (format)
{
case EventFieldFormat.Default:
return native;
case EventFieldFormat.String:
return TraceLoggingDataType.Char8;
case EventFieldFormat.Boolean:
return TraceLoggingDataType.Boolean8;
case EventFieldFormat.Hexadecimal:
return TraceLoggingDataType.HexInt8;
#if false
case EventSourceFieldFormat.Signed:
return TraceLoggingDataType.Int8;
case EventSourceFieldFormat.Unsigned:
return TraceLoggingDataType.UInt8;
#endif
default:
return MakeDataType(native, format);
}
}
/// <summary>
/// Adjusts the native type based on format.
/// - If format is default, return native.
/// - If format is recognized, return the canonical type for that format.
/// - Otherwise remove existing format from native and apply the requested format.
/// </summary>
public static TraceLoggingDataType Format16(
EventFieldFormat format,
TraceLoggingDataType native)
{
switch (format)
{
case EventFieldFormat.Default:
return native;
case EventFieldFormat.String:
return TraceLoggingDataType.Char16;
case EventFieldFormat.Hexadecimal:
return TraceLoggingDataType.HexInt16;
#if false
case EventSourceFieldFormat.Port:
return TraceLoggingDataType.Port;
case EventSourceFieldFormat.Signed:
return TraceLoggingDataType.Int16;
case EventSourceFieldFormat.Unsigned:
return TraceLoggingDataType.UInt16;
#endif
default:
return MakeDataType(native, format);
}
}
/// <summary>
/// Adjusts the native type based on format.
/// - If format is default, return native.
/// - If format is recognized, return the canonical type for that format.
/// - Otherwise remove existing format from native and apply the requested format.
/// </summary>
public static TraceLoggingDataType Format32(
EventFieldFormat format,
TraceLoggingDataType native)
{
switch (format)
{
case EventFieldFormat.Default:
return native;
case EventFieldFormat.Boolean:
return TraceLoggingDataType.Boolean32;
case EventFieldFormat.Hexadecimal:
return TraceLoggingDataType.HexInt32;
#if false
case EventSourceFieldFormat.Ipv4Address:
return TraceLoggingDataType.Ipv4Address;
case EventSourceFieldFormat.ProcessId:
return TraceLoggingDataType.ProcessId;
case EventSourceFieldFormat.ThreadId:
return TraceLoggingDataType.ThreadId;
case EventSourceFieldFormat.Win32Error:
return TraceLoggingDataType.Win32Error;
case EventSourceFieldFormat.NTStatus:
return TraceLoggingDataType.NTStatus;
#endif
case EventFieldFormat.HResult:
return TraceLoggingDataType.HResult;
#if false
case EventSourceFieldFormat.Signed:
return TraceLoggingDataType.Int32;
case EventSourceFieldFormat.Unsigned:
return TraceLoggingDataType.UInt32;
#endif
default:
return MakeDataType(native, format);
}
}
/// <summary>
/// Adjusts the native type based on format.
/// - If format is default, return native.
/// - If format is recognized, return the canonical type for that format.
/// - Otherwise remove existing format from native and apply the requested format.
/// </summary>
public static TraceLoggingDataType Format64(
EventFieldFormat format,
TraceLoggingDataType native)
{
switch (format)
{
case EventFieldFormat.Default:
return native;
case EventFieldFormat.Hexadecimal:
return TraceLoggingDataType.HexInt64;
#if false
case EventSourceFieldFormat.FileTime:
return TraceLoggingDataType.FileTime;
case EventSourceFieldFormat.Signed:
return TraceLoggingDataType.Int64;
case EventSourceFieldFormat.Unsigned:
return TraceLoggingDataType.UInt64;
#endif
default:
return MakeDataType(native, format);
}
}
/// <summary>
/// Adjusts the native type based on format.
/// - If format is default, return native.
/// - If format is recognized, return the canonical type for that format.
/// - Otherwise remove existing format from native and apply the requested format.
/// </summary>
public static TraceLoggingDataType FormatPtr(
EventFieldFormat format,
TraceLoggingDataType native)
{
switch (format)
{
case EventFieldFormat.Default:
return native;
case EventFieldFormat.Hexadecimal:
return HexIntPtrType;
#if false
case EventSourceFieldFormat.Signed:
return IntPtrType;
case EventSourceFieldFormat.Unsigned:
return UIntPtrType;
#endif
default:
return MakeDataType(native, format);
}
}
#endregion
#region Reflection helpers
/*
All TraceLogging use of reflection APIs should go through wrappers here.
This helps with portability, and it also makes it easier to audit what
kinds of reflection operations are being done.
*/
public static object? CreateInstance(Type type, params object?[]? parameters)
{
return Activator.CreateInstance(type, parameters);
}
public static bool IsValueType(Type type)
{
bool result = type.IsValueType();
return result;
}
public static bool IsEnum(Type type)
{
bool result = type.IsEnum();
return result;
}
public static IEnumerable<PropertyInfo> GetProperties(Type type)
{
IEnumerable<PropertyInfo> result = type.GetProperties();
return result;
}
public static MethodInfo? GetGetMethod(PropertyInfo propInfo)
{
MethodInfo? result = propInfo.GetGetMethod();
return result;
}
public static MethodInfo? GetDeclaredStaticMethod(Type declaringType, string name)
{
MethodInfo? result;
#if (ES_BUILD_PCL || ES_BUILD_PN)
result = declaringType.GetTypeInfo().GetDeclaredMethod(name);
#else
result = declaringType.GetMethod(
name,
BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.NonPublic);
#endif
return result;
}
public static bool HasCustomAttribute(
PropertyInfo propInfo,
Type attributeType)
{
bool result;
#if (ES_BUILD_PCL || ES_BUILD_PN)
result = propInfo.IsDefined(attributeType);
#else
var attributes = propInfo.GetCustomAttributes(
attributeType,
false);
result = attributes.Length != 0;
#endif
return result;
}
public static AttributeType? GetCustomAttribute<AttributeType>(PropertyInfo propInfo)
where AttributeType : Attribute
{
AttributeType? result = null;
#if (ES_BUILD_PCL || ES_BUILD_PN)
foreach (var attrib in propInfo.GetCustomAttributes<AttributeType>(false))
{
result = attrib;
break;
}
#else
var attributes = propInfo.GetCustomAttributes(typeof(AttributeType), false);
if (attributes.Length != 0)
{
result = (AttributeType)attributes[0];
}
#endif
return result;
}
public static AttributeType? GetCustomAttribute<AttributeType>(Type type)
where AttributeType : Attribute
{
AttributeType? result = null;
#if (ES_BUILD_PCL || ES_BUILD_PN)
foreach (var attrib in type.GetTypeInfo().GetCustomAttributes<AttributeType>(false))
{
result = attrib;
break;
}
#else
var attributes = type.GetCustomAttributes(typeof(AttributeType), false);
if (attributes.Length != 0)
{
result = (AttributeType)attributes[0];
}
#endif
return result;
}
public static Type[] GetGenericArguments(Type type)
{
return type.GetGenericArguments();
}
public static Type? FindEnumerableElementType(Type type)
{
Type? elementType = null;
if (IsGenericMatch(type, typeof(IEnumerable<>)))
{
elementType = GetGenericArguments(type)[0];
}
else
{
#if (ES_BUILD_PCL || ES_BUILD_PN)
var ifaceTypes = type.GetTypeInfo().ImplementedInterfaces;
#else
var ifaceTypes = type.FindInterfaces(IsGenericMatch, typeof(IEnumerable<>));
#endif
foreach (var ifaceType in ifaceTypes)
{
#if (ES_BUILD_PCL || ES_BUILD_PN)
if (!IsGenericMatch(ifaceType, typeof(IEnumerable<>)))
{
continue;
}
#endif
if (elementType != null)
{
// ambiguous match. report no match at all.
elementType = null;
break;
}
elementType = GetGenericArguments(ifaceType)[0];
}
}
return elementType;
}
public static bool IsGenericMatch(Type type, object? openType)
{
return type.IsGenericType() && type.GetGenericTypeDefinition() == (Type?)openType;
}
public static Delegate CreateDelegate(Type delegateType, MethodInfo methodInfo)
{
Delegate result;
#if (ES_BUILD_PCL || ES_BUILD_PN)
result = methodInfo.CreateDelegate(
delegateType);
#else
result = Delegate.CreateDelegate(
delegateType,
methodInfo);
#endif
return result;
}
public static TraceLoggingTypeInfo CreateDefaultTypeInfo(
Type dataType,
List<Type> recursionCheck)
{
TraceLoggingTypeInfo result;
if (recursionCheck.Contains(dataType))
{
throw new NotSupportedException(SR.EventSource_RecursiveTypeDefinition);
}
recursionCheck.Add(dataType);
var eventAttrib = Statics.GetCustomAttribute<EventDataAttribute>(dataType);
if (eventAttrib != null ||
Statics.GetCustomAttribute<CompilerGeneratedAttribute>(dataType) != null ||
IsGenericMatch(dataType, typeof(KeyValuePair<,>)))
{
var analysis = new TypeAnalysis(dataType, eventAttrib, recursionCheck);
result = new InvokeTypeInfo(dataType, analysis);
}
else if (dataType.IsArray)
{
Type elementType = dataType.GetElementType()!;
if (elementType == typeof(bool))
{
result = ScalarArrayTypeInfo.Boolean();
}
else if (elementType == typeof(byte))
{
result = ScalarArrayTypeInfo.Byte();
}
else if (elementType == typeof(sbyte))
{
result = ScalarArrayTypeInfo.SByte();
}
else if (elementType == typeof(short))
{
result = ScalarArrayTypeInfo.Int16();
}
else if (elementType == typeof(ushort))
{
result = ScalarArrayTypeInfo.UInt16();
}
else if (elementType == typeof(int))
{
result = ScalarArrayTypeInfo.Int32();
}
else if (elementType == typeof(uint))
{
result = ScalarArrayTypeInfo.UInt32();
}
else if (elementType == typeof(long))
{
result = ScalarArrayTypeInfo.Int64();
}
else if (elementType == typeof(ulong))
{
result = ScalarArrayTypeInfo.UInt64();
}
else if (elementType == typeof(char))
{
result = ScalarArrayTypeInfo.Char();
}
else if (elementType == typeof(double))
{
result = ScalarArrayTypeInfo.Double();
}
else if (elementType == typeof(float))
{
result = ScalarArrayTypeInfo.Single();
}
else if (elementType == typeof(IntPtr))
{
result = ScalarArrayTypeInfo.IntPtr();
}
else if (elementType == typeof(UIntPtr))
{
result = ScalarArrayTypeInfo.UIntPtr();
}
else if (elementType == typeof(Guid))
{
result = ScalarArrayTypeInfo.Guid();
}
else
{
result = new ArrayTypeInfo(dataType, TraceLoggingTypeInfo.GetInstance(elementType, recursionCheck));
}
}
else
{
if (Statics.IsEnum(dataType))
dataType = Enum.GetUnderlyingType(dataType);
if (dataType == typeof(string))
{
result = new StringTypeInfo();
}
else if (dataType == typeof(bool))
{
result = ScalarTypeInfo.Boolean();
}
else if (dataType == typeof(byte))
{
result = ScalarTypeInfo.Byte();
}
else if (dataType == typeof(sbyte))
{
result = ScalarTypeInfo.SByte();
}
else if (dataType == typeof(short))
{
result = ScalarTypeInfo.Int16();
}
else if (dataType == typeof(ushort))
{
result = ScalarTypeInfo.UInt16();
}
else if (dataType == typeof(int))
{
result = ScalarTypeInfo.Int32();
}
else if (dataType == typeof(uint))
{
result = ScalarTypeInfo.UInt32();
}
else if (dataType == typeof(long))
{
result = ScalarTypeInfo.Int64();
}
else if (dataType == typeof(ulong))
{
result = ScalarTypeInfo.UInt64();
}
else if (dataType == typeof(char))
{
result = ScalarTypeInfo.Char();
}
else if (dataType == typeof(double))
{
result = ScalarTypeInfo.Double();
}
else if (dataType == typeof(float))
{
result = ScalarTypeInfo.Single();
}
else if (dataType == typeof(DateTime))
{
result = new DateTimeTypeInfo();
}
else if (dataType == typeof(decimal))
{
result = new DecimalTypeInfo();
}
else if (dataType == typeof(IntPtr))
{
result = ScalarTypeInfo.IntPtr();
}
else if (dataType == typeof(UIntPtr))
{
result = ScalarTypeInfo.UIntPtr();
}
else if (dataType == typeof(Guid))
{
result = ScalarTypeInfo.Guid();
}
else if (dataType == typeof(TimeSpan))
{
result = new TimeSpanTypeInfo();
}
else if (dataType == typeof(DateTimeOffset))
{
result = new DateTimeOffsetTypeInfo();
}
else if (dataType == typeof(EmptyStruct))
{
result = new NullTypeInfo();
}
else if (IsGenericMatch(dataType, typeof(Nullable<>)))
{
result = new NullableTypeInfo(dataType, recursionCheck);
}
else
{
var elementType = FindEnumerableElementType(dataType);
if (elementType != null)
{
result = new EnumerableTypeInfo(dataType, TraceLoggingTypeInfo.GetInstance(elementType, recursionCheck));
}
else
{
throw new ArgumentException(SR.Format(SR.EventSource_NonCompliantTypeError, dataType.Name));
}
}
}
return result;
}
#endregion
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Collections.Generic;
using System.IO;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using Mono.CompilerServices.SymbolWriter;
namespace Mono.Cecil.Mdb {
#if !READ_ONLY
public class MdbWriterProvider : ISymbolWriterProvider {
public ISymbolWriter GetSymbolWriter (ModuleDefinition module, string fileName)
{
return new MdbWriter (module.Mvid, fileName);
}
public ISymbolWriter GetSymbolWriter (ModuleDefinition module, Stream symbolStream)
{
throw new NotImplementedException ();
}
}
public class MdbWriter : ISymbolWriter {
readonly Guid mvid;
readonly MonoSymbolWriter writer;
readonly Dictionary<string, SourceFile> source_files;
public MdbWriter (Guid mvid, string assembly)
{
this.mvid = mvid;
this.writer = new MonoSymbolWriter (assembly);
this.source_files = new Dictionary<string, SourceFile> ();
}
static Collection<Instruction> GetInstructions (MethodBody body)
{
var instructions = new Collection<Instruction> ();
foreach (var instruction in body.Instructions)
if (instruction.SequencePoint != null)
instructions.Add (instruction);
return instructions;
}
SourceFile GetSourceFile (Document document)
{
var url = document.Url;
SourceFile source_file;
if (source_files.TryGetValue (url, out source_file))
return source_file;
var entry = writer.DefineDocument (url);
var compile_unit = writer.DefineCompilationUnit (entry);
source_file = new SourceFile (compile_unit, entry);
source_files.Add (url, source_file);
return source_file;
}
void Populate (Collection<Instruction> instructions, int [] offsets,
int [] startRows, int [] endRows, int [] startCols, int [] endCols, out SourceFile file)
{
SourceFile source_file = null;
for (int i = 0; i < instructions.Count; i++) {
var instruction = instructions [i];
offsets [i] = instruction.Offset;
var sequence_point = instruction.SequencePoint;
if (source_file == null)
source_file = GetSourceFile (sequence_point.Document);
startRows [i] = sequence_point.StartLine;
endRows [i] = sequence_point.EndLine;
startCols [i] = sequence_point.StartColumn;
endCols [i] = sequence_point.EndColumn;
}
file = source_file;
}
public void Write (MethodBody body)
{
var method = new SourceMethod (body.Method);
var instructions = GetInstructions (body);
int count = instructions.Count;
if (count == 0)
return;
var offsets = new int [count];
var start_rows = new int [count];
var end_rows = new int [count];
var start_cols = new int [count];
var end_cols = new int [count];
SourceFile file;
Populate (instructions, offsets, start_rows, end_rows, start_cols, end_cols, out file);
var builder = writer.OpenMethod (file.CompilationUnit, 0, method);
for (int i = 0; i < count; i++) {
builder.MarkSequencePoint (
offsets [i],
file.CompilationUnit.SourceFile,
start_rows [i],
end_rows [i],
start_cols [i],
end_cols [i],
false);
}
if (body.Scope != null && body.Scope.HasScopes)
WriteScope (body.Scope, true);
else
if (body.HasVariables)
AddVariables (body.Variables);
writer.CloseMethod ();
}
private void WriteScope (Scope scope, bool root)
{
if (scope.Start.Offset == scope.End.Offset) return;
writer.OpenScope (scope.Start.Offset);
if (scope.HasVariables)
{
foreach (var el in scope.Variables)
{
if (!String.IsNullOrEmpty (el.Name))
writer.DefineLocalVariable (el.Index, el.Name);
}
}
if (scope.HasScopes)
{
foreach (var el in scope.Scopes)
WriteScope (el, false);
}
writer.CloseScope (scope.End.Offset + scope.End.GetSize());
}
readonly static byte [] empty_header = new byte [0];
public bool GetDebugHeader (out ImageDebugDirectory directory, out byte [] header)
{
directory = new ImageDebugDirectory ();
header = empty_header;
return false;
}
void AddVariables (IList<VariableDefinition> variables)
{
for (int i = 0; i < variables.Count; i++) {
var variable = variables [i];
writer.DefineLocalVariable (i, variable.Name);
}
}
public void Write (MethodSymbols symbols)
{
var method = new SourceMethodSymbol (symbols);
var file = GetSourceFile (symbols.Instructions [0].SequencePoint.Document);
var builder = writer.OpenMethod (file.CompilationUnit, 0, method);
var count = symbols.Instructions.Count;
for (int i = 0; i < count; i++) {
var instruction = symbols.Instructions [i];
var sequence_point = instruction.SequencePoint;
builder.MarkSequencePoint (
instruction.Offset,
GetSourceFile (sequence_point.Document).CompilationUnit.SourceFile,
sequence_point.StartLine,
sequence_point.EndLine,
sequence_point.StartColumn,
sequence_point.EndColumn,
false);
}
if (symbols.HasVariables)
AddVariables (symbols.Variables);
writer.CloseMethod ();
}
public void Dispose ()
{
writer.WriteSymbolFile (mvid);
}
class SourceFile : ISourceFile {
readonly CompileUnitEntry compilation_unit;
readonly SourceFileEntry entry;
public SourceFileEntry Entry {
get { return entry; }
}
public CompileUnitEntry CompilationUnit {
get { return compilation_unit; }
}
public SourceFile (CompileUnitEntry comp_unit, SourceFileEntry entry)
{
this.compilation_unit = comp_unit;
this.entry = entry;
}
}
class SourceMethodSymbol : IMethodDef {
readonly string name;
readonly int token;
public string Name {
get { return name;}
}
public int Token {
get { return token; }
}
public SourceMethodSymbol (MethodSymbols symbols)
{
name = symbols.MethodName;
token = symbols.MethodToken.ToInt32 ();
}
}
class SourceMethod : IMethodDef {
readonly MethodDefinition method;
public string Name {
get { return method.Name; }
}
public int Token {
get { return method.MetadataToken.ToInt32 (); }
}
public SourceMethod (MethodDefinition method)
{
this.method = method;
}
}
}
#endif
}
| |
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Windows.Forms;
using Oranikle.Studio.Controls.Properties;
namespace Oranikle.Studio.Controls
{
public class CtrlSplitButton : Oranikle.Studio.Controls.StyledButton
{
private bool _AlwaysDropDown;
private bool _AlwaysHoverChange;
private bool _CalculateSplitRect;
private string _ClickedImage;
private System.Windows.Forms.ImageList _DefaultSplitImages;
private string _DisabledImage;
private bool _DoubleClickedEnabled;
private bool _FillSplitHeight;
private string _FocusedImage;
private string _HoverImage;
private string _NormalImage;
private bool _OnlyShowTriangle;
private int _SplitHeight;
private int _SplitWidth;
private System.ComponentModel.IContainer components;
[System.ComponentModel.Category("Action")]
[System.ComponentModel.Description("Occurs when the button part of the SplitButton is clicked.")]
[System.ComponentModel.Browsable(true)]
public event System.EventHandler ButtonClick;
[System.ComponentModel.Description("Occurs when the button part of the SplitButton is clicked.")]
[System.ComponentModel.Category("Action")]
[System.ComponentModel.Browsable(true)]
public event System.EventHandler ButtonDoubleClick;
[System.ComponentModel.Category("Split Button")]
[System.ComponentModel.Description("Indicates whether the SplitButton always shows the drop down menu even if the button part of the SplitButton is clicked.")]
[System.ComponentModel.DefaultValue(false)]
public bool AlwaysDropDown
{
get
{
return _AlwaysDropDown;
}
set
{
_AlwaysDropDown = value;
}
}
[System.ComponentModel.DefaultValue(false)]
[System.ComponentModel.Category("Split Button")]
[System.ComponentModel.Description("Indicates whether the SplitButton always shows the Hover image status in the split part even if the button part of the SplitButton is hovered.")]
public bool AlwaysHoverChange
{
get
{
return _AlwaysHoverChange;
}
set
{
_AlwaysHoverChange = value;
}
}
[System.ComponentModel.Category("Split Button")]
[System.ComponentModel.DefaultValue(true)]
[System.ComponentModel.Description("Indicates whether the split rectange must be calculated (basing on Split image size)")]
public bool CalculateSplitRect
{
get
{
return _CalculateSplitRect;
}
set
{
bool flag = _CalculateSplitRect;
_CalculateSplitRect = value;
if ((flag != _CalculateSplitRect) && (_SplitWidth > 0) && (_SplitHeight > 0))
InitDefaultSplitImages(true);
}
}
[System.ComponentModel.Localizable(true)]
[System.ComponentModel.TypeConverter(typeof(System.Windows.Forms.ImageKeyConverter))]
[System.ComponentModel.Category("Split Button Images")]
[System.ComponentModel.Description("The Clicked status image name in the ImageList.")]
[System.ComponentModel.DefaultValue("")]
[System.ComponentModel.Editor("System.Windows.Forms.Design.ImageIndexEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(System.Drawing.Design.UITypeEditor))]
[System.ComponentModel.RefreshProperties(System.ComponentModel.RefreshProperties.Repaint)]
public string ClickedImage
{
get
{
return _ClickedImage;
}
set
{
_ClickedImage = value;
}
}
[System.ComponentModel.Category("Split Button Images")]
[System.ComponentModel.DefaultValue("")]
[System.ComponentModel.Editor("System.Windows.Forms.Design.ImageIndexEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(System.Drawing.Design.UITypeEditor))]
[System.ComponentModel.Localizable(true)]
[System.ComponentModel.RefreshProperties(System.ComponentModel.RefreshProperties.Repaint)]
[System.ComponentModel.TypeConverter(typeof(System.Windows.Forms.ImageKeyConverter))]
[System.ComponentModel.Description("The Disabled status image name in the ImageList.")]
public string DisabledImage
{
get
{
return _DisabledImage;
}
set
{
_DisabledImage = value;
}
}
[System.ComponentModel.Description("Indicates whether the double click event is raised on the SplitButton")]
[System.ComponentModel.DefaultValue(false)]
[System.ComponentModel.Category("Behavior")]
public bool DoubleClickedEnabled
{
get
{
return _DoubleClickedEnabled;
}
set
{
_DoubleClickedEnabled = value;
}
}
[System.ComponentModel.Category("Split Button")]
[System.ComponentModel.DefaultValue(true)]
[System.ComponentModel.Description("Indicates whether the split height must be filled to the button height even if the split image height is lower.")]
public bool FillSplitHeight
{
get
{
return _FillSplitHeight;
}
set
{
_FillSplitHeight = value;
}
}
[System.ComponentModel.Localizable(true)]
[System.ComponentModel.Description("The Focused status image name in the ImageList.")]
[System.ComponentModel.Category("Split Button Images")]
[System.ComponentModel.DefaultValue("")]
[System.ComponentModel.TypeConverter(typeof(System.Windows.Forms.ImageKeyConverter))]
[System.ComponentModel.Editor("System.Windows.Forms.Design.ImageIndexEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(System.Drawing.Design.UITypeEditor))]
[System.ComponentModel.RefreshProperties(System.ComponentModel.RefreshProperties.Repaint)]
public string FocusedImage
{
get
{
return _FocusedImage;
}
set
{
_FocusedImage = value;
}
}
[System.ComponentModel.Description("The Hover status image name in the ImageList.")]
[System.ComponentModel.DefaultValue("")]
[System.ComponentModel.Editor("System.Windows.Forms.Design.ImageIndexEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(System.Drawing.Design.UITypeEditor))]
[System.ComponentModel.Localizable(true)]
[System.ComponentModel.RefreshProperties(System.ComponentModel.RefreshProperties.Repaint)]
[System.ComponentModel.TypeConverter(typeof(System.Windows.Forms.ImageKeyConverter))]
[System.ComponentModel.Category("Split Button Images")]
public string HoverImage
{
get
{
return _HoverImage;
}
set
{
_HoverImage = value;
}
}
[System.ComponentModel.TypeConverter(typeof(System.Windows.Forms.ImageKeyConverter))]
[System.ComponentModel.Description("The Normal status image name in the ImageList.")]
[System.ComponentModel.Editor("System.Windows.Forms.Design.ImageIndexEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(System.Drawing.Design.UITypeEditor))]
[System.ComponentModel.Localizable(true)]
[System.ComponentModel.RefreshProperties(System.ComponentModel.RefreshProperties.Repaint)]
[System.ComponentModel.Category("Split Button Images")]
[System.ComponentModel.DefaultValue("")]
public string NormalImage
{
get
{
return _NormalImage;
}
set
{
_NormalImage = value;
}
}
[System.ComponentModel.DefaultValue(false)]
[System.ComponentModel.Description("Whether it should only show the triangle")]
[System.ComponentModel.Category("Split Button")]
public bool OnlyShowTriangle
{
get
{
return _OnlyShowTriangle;
}
set
{
_OnlyShowTriangle = value;
}
}
[System.ComponentModel.DefaultValue(0)]
[System.ComponentModel.Description("The split height (ignored if CalculateSplitRect is setted to true).")]
[System.ComponentModel.Category("Split Button")]
public int SplitHeight
{
get
{
return _SplitHeight;
}
set
{
_SplitHeight = value;
if (!_CalculateSplitRect && (_SplitWidth > 0) && (_SplitHeight > 0))
InitDefaultSplitImages(true);
}
}
[System.ComponentModel.Category("Split Button")]
[System.ComponentModel.Description("The split width (ignored if CalculateSplitRect is setted to true).")]
[System.ComponentModel.DefaultValue(0)]
public int SplitWidth
{
get
{
return _SplitWidth;
}
set
{
_SplitWidth = value;
if (!_CalculateSplitRect && (_SplitWidth > 0) && (_SplitHeight > 0))
InitDefaultSplitImages(true);
}
}
public CtrlSplitButton()
{
_CalculateSplitRect = true;
_FillSplitHeight = true;
InitializeComponent();
ImageAlign = System.Drawing.ContentAlignment.MiddleRight;
TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
TextImageRelation = System.Windows.Forms.TextImageRelation.TextBeforeImage;
CalculateSplitRect = true;
FillSplitHeight = true;
}
private System.Drawing.Image GetImage(string imageName)
{
if ((ImageList != null) && ImageList.Images.ContainsKey(imageName))
return ImageList.Images[imageName];
return null;
}
public System.Drawing.Rectangle GetImageRect(string imageKey)
{
System.Drawing.Image image = GetImage(imageKey);
if (image == null)
goto label_2;
int i1 = 0, i2 = 0;
int i3 = image.Width + 1;
int i4 = image.Height + 1;
if (i3 > Width)
i3 = Width;
if (i4 > Width)
i4 = Width;
switch (ImageAlign)
{
case System.Drawing.ContentAlignment.TopLeft:
i1 = i2 = 0;
break;
case System.Drawing.ContentAlignment.TopCenter:
i1 = (Width - i3) / 2;
i2 = 0;
if (((Width - i3) % 2) <= 0)
goto label_1;
i1++;
break;
case System.Drawing.ContentAlignment.TopRight:
i1 = Width - i3;
i2 = 0;
break;
case System.Drawing.ContentAlignment.MiddleLeft:
i1 = 0;
i2 = (Height - i4) / 2;
if (((Height - i4) % 2) <= 0)
goto label_1;
i2++;
break;
case System.Drawing.ContentAlignment.MiddleCenter:
i1 = (Width - i3) / 2;
i2 = (Height - i4) / 2;
if (((Width - i3) % 2) > 0)
i1++;
if (((Height - i4) % 2) <= 0)
goto label_1;//goto label_0;
i2++;
break;
case System.Drawing.ContentAlignment.MiddleRight:
i1 = Width - i3;
i2 = (Height - i4) / 2;
if (((Height - i4) % 2) <= 0)
goto label_1;
i2++;
break;
case System.Drawing.ContentAlignment.BottomLeft:
i1 = 0;
i2 = Height - i4;
if (((Height - i4) % 2) <= 0)
goto label_1;
i2++;
break;
case System.Drawing.ContentAlignment.BottomCenter:
i1 = (Width - i3) / 2;
i2 = Height - i4;
if (((Width - i3) % 2) <= 0)
goto label_1;
i1++;
break;
case System.Drawing.ContentAlignment.BottomRight:
i1 = Width - i3;
i2 = Height - i4;
break;
case System.Drawing.ContentAlignment.TopLeft | System.Drawing.ContentAlignment.TopCenter:
goto label_1;
}
label_1:
if (_FillSplitHeight && (i4 < Height))
i4 = Height;
if (i1 > 0)
i1--;
if (i2 > 0)
i2--;
return new System.Drawing.Rectangle(i1, i2, i3, i4);
label_2:
return System.Drawing.Rectangle.Empty;
}
private void InitDefaultSplitImages()
{
InitDefaultSplitImages(false);
}
private void InitDefaultSplitImages(bool refresh)
{
if (System.String.IsNullOrEmpty(_NormalImage))
_NormalImage = "Normal";
if (System.String.IsNullOrEmpty(_HoverImage))
_HoverImage = "Hover";
if (System.String.IsNullOrEmpty(_ClickedImage))
_ClickedImage = "Clicked";
if (System.String.IsNullOrEmpty(_DisabledImage))
_DisabledImage = "Disabled";
if (System.String.IsNullOrEmpty(_FocusedImage))
_FocusedImage = "Focused";
if (_DefaultSplitImages == null)
{
_DefaultSplitImages = new System.Windows.Forms.ImageList();
components.Add(_DefaultSplitImages);
}
if ((_DefaultSplitImages.Images.Count == 0) || refresh)
{
if (_DefaultSplitImages.Images.Count > 0)
_DefaultSplitImages.Images.Clear();
try
{
int i1 = 0, i2 = 0;
if (!_CalculateSplitRect && (_SplitWidth > 0))
i1 = _SplitWidth;
else
i1 = 18;
if (!CalculateSplitRect && (SplitHeight > 0))
i2 = SplitHeight;
else
i2 = Height;
i2 -= 8;
_DefaultSplitImages.ImageSize = new System.Drawing.Size(i1, i2);
int i3 = i1 / 2;
i3 += i3 % 2;
int i4 = i2 / 2;
System.Drawing.Pen pen = new System.Drawing.Pen(ForeColor, 1.0F);
System.Drawing.SolidBrush solidBrush = new System.Drawing.SolidBrush(ForeColor);
System.Drawing.Bitmap bitmap1 = new System.Drawing.Bitmap(i1, i2);
System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap1);
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.DrawLine(System.Drawing.SystemPens.ButtonShadow, new System.Drawing.Point(1, 1), new System.Drawing.Point(1, i2 - 2));
graphics.DrawLine(System.Drawing.SystemPens.ButtonFace, new System.Drawing.Point(2, 1), new System.Drawing.Point(2, i2));
System.Drawing.Point[] pointArr1 = new System.Drawing.Point[3];
pointArr1[0] = new System.Drawing.Point(i3 - 2, i4 - 1);
pointArr1[1] = new System.Drawing.Point(i3 + 3, i4 - 1);
pointArr1[2] = new System.Drawing.Point(i3, i4 + 2);
graphics.FillPolygon(solidBrush, pointArr1);
graphics.Dispose();
System.Drawing.Bitmap bitmap2 = new System.Drawing.Bitmap(i1, i2);
graphics = System.Drawing.Graphics.FromImage(bitmap2);
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.DrawLine(System.Drawing.SystemPens.ButtonShadow, new System.Drawing.Point(1, 1), new System.Drawing.Point(1, i2 - 2));
graphics.DrawLine(System.Drawing.SystemPens.ButtonFace, new System.Drawing.Point(2, 1), new System.Drawing.Point(2, i2));
System.Drawing.Point[] pointArr2 = new System.Drawing.Point[3];
pointArr2[0] = new System.Drawing.Point(i3 - 3, i4 - 2);
pointArr2[1] = new System.Drawing.Point(i3 + 4, i4 - 2);
pointArr2[2] = new System.Drawing.Point(i3, i4 + 2);
graphics.FillPolygon(solidBrush, pointArr2);
graphics.Dispose();
System.Drawing.Bitmap bitmap3 = new System.Drawing.Bitmap(i1, i2);
graphics = System.Drawing.Graphics.FromImage(bitmap3);
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.DrawLine(System.Drawing.SystemPens.ButtonShadow, new System.Drawing.Point(1, 1), new System.Drawing.Point(1, i2 - 2));
graphics.DrawLine(System.Drawing.SystemPens.ButtonFace, new System.Drawing.Point(2, 1), new System.Drawing.Point(2, i2));
System.Drawing.Point[] pointArr3 = new System.Drawing.Point[3];
pointArr3[0] = new System.Drawing.Point(i3 - 2, i4 - 1);
pointArr3[1] = new System.Drawing.Point(i3 + 3, i4 - 1);
pointArr3[2] = new System.Drawing.Point(i3, i4 + 2);
graphics.FillPolygon(solidBrush, pointArr3);
graphics.Dispose();
System.Drawing.Bitmap bitmap4 = new System.Drawing.Bitmap(i1, i2);
graphics = System.Drawing.Graphics.FromImage(bitmap4);
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.DrawLine(System.Drawing.SystemPens.GrayText, new System.Drawing.Point(1, 1), new System.Drawing.Point(1, i2 - 2));
System.Drawing.Point[] pointArr4 = new System.Drawing.Point[3];
pointArr4[0] = new System.Drawing.Point(i3 - 2, i4 - 1);
pointArr4[1] = new System.Drawing.Point(i3 + 3, i4 - 1);
pointArr4[2] = new System.Drawing.Point(i3, i4 + 2);
graphics.FillPolygon(new System.Drawing.SolidBrush(System.Drawing.SystemColors.GrayText), pointArr4);
graphics.Dispose();
System.Drawing.Bitmap bitmap5 = new System.Drawing.Bitmap(i1, i2);
graphics = System.Drawing.Graphics.FromImage(bitmap5);
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.DrawLine(System.Drawing.SystemPens.ButtonShadow, new System.Drawing.Point(1, 1), new System.Drawing.Point(1, i2 - 2));
graphics.DrawLine(System.Drawing.SystemPens.ButtonFace, new System.Drawing.Point(2, 1), new System.Drawing.Point(2, i2));
System.Drawing.Point[] pointArr5 = new System.Drawing.Point[3];
pointArr5[0] = new System.Drawing.Point(i3 - 2, i4 - 1);
pointArr5[1] = new System.Drawing.Point(i3 + 3, i4 - 1);
pointArr5[2] = new System.Drawing.Point(i3, i4 + 2);
graphics.FillPolygon(solidBrush, pointArr5);
graphics.Dispose();
pen.Dispose();
solidBrush.Dispose();
_DefaultSplitImages.Images.Add(_NormalImage, bitmap1);
_DefaultSplitImages.Images.Add(_HoverImage, bitmap2);
_DefaultSplitImages.Images.Add(_ClickedImage, bitmap3);
_DefaultSplitImages.Images.Add(_DisabledImage, bitmap4);
_DefaultSplitImages.Images.Add(_FocusedImage, bitmap5);
}
catch
{
}
}
}
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
public bool MouseInSplit()
{
return PointInSplit(PointToClient(System.Windows.Forms.Control.MousePosition));
}
public bool PointInSplit(System.Drawing.Point pt)
{
System.Drawing.Rectangle rectangle = GetImageRect(_NormalImage);
if (!_CalculateSplitRect)
{
rectangle.Width = _SplitWidth;
rectangle.Height = _SplitHeight;
}
return rectangle.Contains(pt);
}
private void SetSplit(string imageName)
{
if ((imageName != null) && (ImageList != null) && ImageList.Images.ContainsKey(imageName))
ImageKey = imageName;
}
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
components.Dispose();
base.Dispose(disposing);
}
protected override void OnClick(System.EventArgs e)
{
if (!MouseInSplit() && !_AlwaysDropDown)
{
base.OnClick(e);
if (ButtonClick == null)
return;
ButtonClick(this, e);
return;
}
if ((ContextMenuStrip != null) && (ContextMenuStrip.Items.Count > 0))
ContextMenuStrip.Show(this, new System.Drawing.Point(0, Height));
}
protected override void OnCreateControl()
{
InitDefaultSplitImages();
if (ImageList == null)
ImageList = _DefaultSplitImages;
if (Enabled)
SetSplit(_NormalImage);
else
SetSplit(_DisabledImage);
base.OnCreateControl();
}
protected override void OnDoubleClick(System.EventArgs e)
{
if (_DoubleClickedEnabled)
{
base.OnDoubleClick(e);
if (!MouseInSplit() && !_AlwaysDropDown && (ButtonClick != null))
ButtonDoubleClick(this, e);
}
}
protected override void OnEnabledChanged(System.EventArgs e)
{
if (!Enabled)
SetSplit(_DisabledImage);
else if (MouseInSplit())
SetSplit(_HoverImage);
else
SetSplit(_NormalImage);
base.OnEnabledChanged(e);
}
protected override void OnGotFocus(System.EventArgs e)
{
if (Enabled)
SetSplit(_FocusedImage);
base.OnGotFocus(e);
}
protected override void OnLostFocus(System.EventArgs e)
{
if (Enabled)
SetSplit(_NormalImage);
base.OnLostFocus(e);
}
protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs mevent)
{
if (_AlwaysDropDown || MouseInSplit())
{
if (Enabled)
{
SetSplit(_ClickedImage);
if ((ContextMenuStrip != null) && (ContextMenuStrip.Items.Count > 0))
ContextMenuStrip.Show(this, new System.Drawing.Point(0, Height));
}
}
else if (Enabled)
{
SetSplit(_NormalImage);
}
base.OnMouseDown(mevent);
}
protected override void OnMouseLeave(System.EventArgs e)
{
if (Enabled)
SetSplit(_NormalImage);
base.OnMouseLeave(e);
}
protected override void OnMouseMove(System.Windows.Forms.MouseEventArgs mevent)
{
if (_AlwaysDropDown || _AlwaysHoverChange || MouseInSplit())
{
if (Enabled)
SetSplit(_HoverImage);
}
else if (Enabled)
{
SetSplit(_NormalImage);
}
base.OnMouseMove(mevent);
}
protected override void OnMouseUp(System.Windows.Forms.MouseEventArgs mevent)
{
if (_AlwaysDropDown || _AlwaysHoverChange || MouseInSplit())
{
if (Enabled)
SetSplit(_HoverImage);
}
else if (Enabled)
{
SetSplit(_NormalImage);
}
base.OnMouseUp(mevent);
}
protected override void OnPaint(System.Windows.Forms.PaintEventArgs pevent)
{
pevent.Graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.Invalid;
pevent.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low;
pevent.Graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.None;
pevent.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
System.Drawing.Rectangle rectangle3 = ClientRectangle;
int i = rectangle3.Width - 18;
if (!_OnlyShowTriangle)
{
pevent.Graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
pevent.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
pevent.Graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
pevent.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
System.Drawing.Brush brush1 = new System.Drawing.Drawing2D.LinearGradientBrush(ClientRectangle, BackColor, BackColor2, BackFillMode);
pevent.Graphics.FillRectangle(brush1, ClientRectangle);
brush1.Dispose();
System.Drawing.Pen pen1 = new System.Drawing.Pen(BorderColor, 1.0F);
System.Drawing.Rectangle rectangle4 = ClientRectangle;
System.Drawing.Rectangle rectangle5 = ClientRectangle;
System.Drawing.Rectangle rectangle6 = ClientRectangle;
System.Drawing.Rectangle rectangle1 = new System.Drawing.Rectangle(rectangle4.Location, new System.Drawing.Size(rectangle5.Width, rectangle6.Height));
pevent.Graphics.DrawRectangle(pen1, rectangle1);
pen1.Dispose();
System.Drawing.Pen pen2 = new System.Drawing.Pen(BorderColor, 1.0F);
System.Drawing.Rectangle rectangle7 = ClientRectangle;
pevent.Graphics.DrawLine(pen2, new System.Drawing.Point(i, 0), new System.Drawing.Point(i, rectangle7.Height));
pen2.Dispose();
System.Drawing.StringFormat stringFormat = new System.Drawing.StringFormat();
System.Drawing.Rectangle rectangle8 = ClientRectangle;
System.Drawing.Rectangle rectangle9 = ClientRectangle;
System.Drawing.Rectangle rectangle2 = new System.Drawing.Rectangle(rectangle8.Location, new System.Drawing.Size(i, rectangle9.Height));
System.Drawing.ContentAlignment contentAlignment = TextAlign;
if ((contentAlignment == System.Drawing.ContentAlignment.TopLeft) || (contentAlignment == System.Drawing.ContentAlignment.MiddleLeft) || (contentAlignment == System.Drawing.ContentAlignment.BottomLeft))
{
stringFormat.Alignment = System.Drawing.StringAlignment.Near;
rectangle2.X += 4;
}
else
{
stringFormat.Alignment = System.Drawing.StringAlignment.Center;
}
stringFormat.LineAlignment = System.Drawing.StringAlignment.Center;
stringFormat.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.Hide;
System.Drawing.Brush brush2 = new System.Drawing.SolidBrush(ForeColor);
pevent.Graphics.DrawString(Text, Font, brush2, rectangle2, stringFormat);
}
else
{
System.Drawing.Color color = System.Drawing.Color.White;
System.Windows.Forms.Control control = Parent;
while ((control != null) && control.BackColor == System.Drawing.Color.Transparent)
{
control = control.Parent;
}
if (control != null)
color = control.BackColor;
System.Drawing.Brush brush3 = new System.Drawing.SolidBrush(color);
pevent.Graphics.FillRectangle(brush3, ClientRectangle);
brush3.Dispose();
}
System.Drawing.Image image = Oranikle.Studio.Controls.Properties.Resources.ComboBoxTransparent;
pevent.Graphics.DrawImage(image, new System.Drawing.Point(i, 0));
}
} // class CtrlSplitButton
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Linq.Expressions;
using Signum.Utilities;
using Signum.Entities;
using Signum.Entities.Reflection;
using Signum.Utilities.Reflection;
using Signum.Utilities.ExpressionTrees;
using Signum.Engine.Maps;
using Signum.Entities.Basics;
using Signum.Entities.Internal;
using Signum.Utilities.DataStructures;
namespace Signum.Engine.Linq
{
internal static class TranslatorBuilder
{
internal static ITranslateResult Build(ProjectionExpression proj)
{
Type type = proj.UniqueFunction == null ? proj.Type.ElementType()! : proj.Type;
return miBuildPrivate.GetInvoker(type)(proj);
}
static GenericInvoker<Func<ProjectionExpression, ITranslateResult>> miBuildPrivate = new GenericInvoker<Func<ProjectionExpression, ITranslateResult>>(pe => BuildPrivate<int>(pe));
static TranslateResult<T> BuildPrivate<T>(ProjectionExpression proj)
{
var eagerChildProjections = EagerChildProjectionGatherer.Gatherer(proj).Select(cp => BuildChild(cp)).ToList();
var lazyChildProjections = LazyChildProjectionGatherer.Gatherer(proj).Select(cp => BuildChild(cp)).ToList();
Scope scope = new Scope(
alias :proj.Select.Alias,
positions: proj.Select.Columns.Select((c, i) => new { c.Name, i }).ToDictionary(p => p.Name!, p => p.i) /*CSBUG*/
);
Expression<Func<IProjectionRow, T>> lambda = ProjectionBuilder.Build<T>(proj.Projector, scope);
var command = QueryFormatter.Format(proj.Select);
var result = new TranslateResult<T>(
eagerProjections: eagerChildProjections,
lazyChildProjections: lazyChildProjections,
mainCommand: command,
projectorExpression: lambda,
unique: proj.UniqueFunction
);
return result;
}
static IChildProjection BuildChild(ChildProjectionExpression childProj)
{
var proj = childProj.Projection;
Type type = proj.UniqueFunction == null ? proj.Type.ElementType()! : proj.Type;
if(!type.IsInstantiationOf(typeof(KeyValuePair<,>)))
throw new InvalidOperationException("All child projections should create KeyValuePairs");
Scope scope = new Scope(
alias: proj.Select.Alias,
positions: proj.Select.Columns.Select((c, i) => new { c.Name, i }).ToDictionary(p => p.Name!, p => p.i) /*CSBUG*/
);
var types = type.GetGenericArguments();
var command = QueryFormatter.Format(proj.Select);
if (childProj.IsLazyMList)
{
types[1] = types[1].GetGenericArguments()[0];
return giLazyChild.GetInvoker(types)(proj.Projector, scope, childProj.Token, command);
}
else
{
return giEagerChild.GetInvoker(types)(proj.Projector, scope, childProj.Token, command);
}
}
static readonly GenericInvoker<Func<Expression, Scope, LookupToken, SqlPreCommandSimple, IChildProjection>> giLazyChild =
new GenericInvoker<Func<Expression, Scope, LookupToken, SqlPreCommandSimple, IChildProjection>>((proj, scope, token, sql) => LazyChild<int, bool>(proj, scope, token, sql));
static IChildProjection LazyChild<K, V>(Expression projector, Scope scope, LookupToken token, SqlPreCommandSimple command)
where K : notnull
{
var proj = ProjectionBuilder.Build<KeyValuePair<K, MList<V>.RowIdElement>>(projector, scope);
return new LazyChildProjection<K, V>(token, command, proj);
}
static readonly GenericInvoker<Func<Expression, Scope, LookupToken, SqlPreCommandSimple, IChildProjection>> giEagerChild =
new GenericInvoker<Func<Expression, Scope, LookupToken, SqlPreCommandSimple, IChildProjection>>((proj, scope, token, sql) => EagerChild<int, bool>(proj, scope, token, sql));
static IChildProjection EagerChild<K, V>(Expression projector, Scope scope, LookupToken token, SqlPreCommandSimple command)
{
var proj = ProjectionBuilder.Build<KeyValuePair<K, V>>(projector, scope);
return new EagerChildProjection<K, V>(token, command, proj);
}
public static SqlPreCommandSimple BuildCommandResult(CommandExpression command)
{
return QueryFormatter.Format(command);
}
public class LazyChildProjectionGatherer : DbExpressionVisitor
{
List<ChildProjectionExpression> list = new List<ChildProjectionExpression>();
public static List<ChildProjectionExpression> Gatherer(ProjectionExpression proj)
{
LazyChildProjectionGatherer pg = new LazyChildProjectionGatherer();
pg.Visit(proj);
return pg.list;
}
protected internal override Expression VisitChildProjection(ChildProjectionExpression child)
{
if (child.IsLazyMList)
list.Add(child);
var result = base.VisitChildProjection(child);
return result;
}
}
public class EagerChildProjectionGatherer : DbExpressionVisitor
{
List<ChildProjectionExpression> list = new List<ChildProjectionExpression>();
public static List<ChildProjectionExpression> Gatherer(ProjectionExpression proj)
{
EagerChildProjectionGatherer pg = new EagerChildProjectionGatherer();
pg.Visit(proj);
return pg.list;
}
protected internal override Expression VisitChildProjection(ChildProjectionExpression child)
{
var result = base.VisitChildProjection(child);
if (!child.IsLazyMList)
list.Add(child);
return result;
}
}
/// <summary>
/// ProjectionBuilder is a visitor that converts an projector expression
/// that constructs result objects out of ColumnExpressions into an actual
/// LambdaExpression that constructs result objects out of accessing fields
/// of a ProjectionRow
/// </summary>
public class ProjectionBuilder : DbExpressionVisitor
{
static readonly ParameterExpression row = Expression.Parameter(typeof(IProjectionRow), "row");
static readonly PropertyInfo piRetriever = ReflectionTools.GetPropertyInfo((IProjectionRow r) => r.Retriever);
static readonly MemberExpression retriever = Expression.Property(row, piRetriever);
static readonly FieldInfo fiId = ReflectionTools.GetFieldInfo((Entity i) => i.id);
static readonly MethodInfo miCached = ReflectionTools.GetMethodInfo((IRetriever r) => r.Complete<TypeEntity>(null, null!)).GetGenericMethodDefinition();
static readonly MethodInfo miRequest = ReflectionTools.GetMethodInfo((IRetriever r) => r.Request<TypeEntity>(null)).GetGenericMethodDefinition();
static readonly MethodInfo miRequestIBA = ReflectionTools.GetMethodInfo((IRetriever r) => r.RequestIBA<TypeEntity>(null, null)).GetGenericMethodDefinition();
static readonly MethodInfo miRequestLite = ReflectionTools.GetMethodInfo((IRetriever r) => r.RequestLite<TypeEntity>(null)).GetGenericMethodDefinition();
static readonly MethodInfo miModifiablePostRetrieving = ReflectionTools.GetMethodInfo((IRetriever r) => r.ModifiablePostRetrieving<EmbeddedEntity>(null)).GetGenericMethodDefinition();
Scope scope;
public ProjectionBuilder(Scope scope)
{
this.scope = scope;
}
static internal Expression<Func<IProjectionRow, T>> Build<T>(Expression expression, Scope scope)
{
ProjectionBuilder pb = new ProjectionBuilder(scope);
Expression body = pb.Visit(expression);
return Expression.Lambda<Func<IProjectionRow, T>>(body, row);
}
Expression NullifyColumn(Expression exp)
{
if (!(exp is ColumnExpression ce))
return exp;
if (ce.Type.IsNullable() || ce.Type.IsClass)
return ce;
return new ColumnExpression(ce.Type.Nullify(), ce.Alias, ce.Name);
}
protected override Expression VisitUnary(UnaryExpression u)
{
var col = GetInnerColumn(u);
if(col != null)
return scope.GetColumnExpression(row, col.Alias, col.Name!, u.Type);
return base.VisitUnary(u);
}
public ColumnExpression? GetInnerColumn(UnaryExpression u)
{
if(u.NodeType == ExpressionType.Convert && DiffersInNullability(u.Type, u.Operand.Type))
{
if (u.Operand is ColumnExpression c)
return c;
if (u.Operand is UnaryExpression u2)
return GetInnerColumn(u2);
}
return null;
}
bool DiffersInNullability(Type a, Type b)
{
if (a.IsValueType && a.Nullify() == b ||
b.IsValueType && b.Nullify() == a)
return true;
if (a == typeof(Date) && b == typeof(DateTime) ||
a == typeof(DateTime) && b == typeof(Date))
return true;
return false;
}
protected internal override Expression VisitColumn(ColumnExpression column)
{
return scope.GetColumnExpression(row, column.Alias, column.Name!, column.Type);
}
protected internal override Expression VisitChildProjection(ChildProjectionExpression child)
{
Expression outer = Visit(child.OuterKey);
if (outer != child.OuterKey)
child = new ChildProjectionExpression(child.Projection, outer, child.IsLazyMList, child.Type, child.Token);
return scope.LookupEager(row, child);
}
protected Expression VisitMListChildProjection(ChildProjectionExpression child, MemberExpression field)
{
Expression outer = Visit(child.OuterKey);
if (outer != child.OuterKey)
child = new ChildProjectionExpression(child.Projection, outer, child.IsLazyMList, child.Type, child.Token);
return scope.LookupMList(row, child, field);
}
protected internal override Expression VisitProjection(ProjectionExpression proj)
{
throw new InvalidOperationException("No ProjectionExpressions expected at this stage");
}
protected internal override MixinEntityExpression VisitMixinEntity(MixinEntityExpression me)
{
throw new InvalidOperationException("Impossible to retrieve MixinEntity {0} without their main entity".FormatWith(me.Type.Name));
}
protected internal override Expression VisitEntity(EntityExpression entityExpr)
{
Expression id = Visit(NullifyColumn(entityExpr.ExternalId));
if (entityExpr.TableAlias == null)
return Expression.Call(retriever, miRequest.MakeGenericMethod(entityExpr.Type), id);
ParameterExpression e = Expression.Parameter(entityExpr.Type, entityExpr.Type.Name.ToLower().Substring(0, 1));
var bindings =
entityExpr.Bindings
.Where(a => !ReflectionTools.FieldEquals(EntityExpression.IdField, a.FieldInfo))
.Select(b =>
{
var field = Expression.Field(e, b.FieldInfo);
var value = b.Binding is ChildProjectionExpression ?
VisitMListChildProjection((ChildProjectionExpression)b.Binding, field) :
Convert(Visit(b.Binding), b.FieldInfo.FieldType);
return (Expression)Expression.Assign(field, value);
}).ToList();
if (entityExpr.Mixins != null)
{
var blocks = entityExpr.Mixins.Select(m => AssignMixin(e, m)).ToList();
bindings.AddRange(blocks);
}
LambdaExpression lambda = Expression.Lambda(typeof(Action<>).MakeGenericType(entityExpr.Type), Expression.Block(bindings), e);
return Expression.Call(retriever, miCached.MakeGenericMethod(entityExpr.Type), id.Nullify(), lambda);
}
BlockExpression AssignMixin(ParameterExpression e, MixinEntityExpression m)
{
var mixParam = Expression.Parameter(m.Type);
var mixBindings = new List<Expression>();
mixBindings.Add(Expression.Assign(mixParam, Expression.Call(e, MixinDeclarations.miMixin.MakeGenericMethod(m.Type))));
mixBindings.Add(Expression.Call(retriever, miModifiablePostRetrieving.MakeGenericMethod(m.Type), mixParam));
mixBindings.AddRange(m.Bindings.Select(b =>
{
var field = Expression.Field(mixParam, b.FieldInfo);
var value = b.Binding is ChildProjectionExpression ?
VisitMListChildProjection((ChildProjectionExpression)b.Binding, field) :
Convert(Visit(b.Binding), b.FieldInfo.FieldType);
return (Expression)Expression.Assign(field, value);
}));
return Expression.Block(new[] { mixParam }, mixBindings);
}
private Expression Convert(Expression expression, Type type)
{
if (expression.Type == type)
return expression;
return Expression.Convert(expression, type);
}
protected internal override Expression VisitEmbeddedEntity(EmbeddedEntityExpression eee)
{
var embeddedParam = Expression.Parameter(eee.Type);
var embeddedBindings = new List<Expression>();
embeddedBindings.Add(Expression.Assign(embeddedParam, Expression.New(eee.Type)));
if (typeof(EmbeddedEntity).IsAssignableFrom(eee.Type))
embeddedBindings.Add(Expression.Call(retriever, miModifiablePostRetrieving.MakeGenericMethod(eee.Type), embeddedParam));
embeddedBindings.AddRange(eee.Bindings.Select(b =>
{
var field = Expression.Field(embeddedParam, b.FieldInfo);
var value = b.Binding is ChildProjectionExpression ?
VisitMListChildProjection((ChildProjectionExpression)b.Binding, field) :
Convert(Visit(b.Binding), b.FieldInfo.FieldType);
return Expression.Assign(field, value);
}));
if (eee.Mixins != null)
{
var blocks = eee.Mixins.Select(m => AssignMixin(embeddedParam, m)).ToList();
embeddedBindings.AddRange(blocks);
}
embeddedBindings.Add(embeddedParam);
var block = Expression.Block(eee.Type, new[] { embeddedParam }, embeddedBindings);
return Expression.Condition(Expression.Equal(Visit(eee.HasValue.Nullify()), Expression.Constant(true, typeof(bool?))),
block,
Expression.Constant(null, block.Type));
}
protected internal override Expression VisitImplementedBy(ImplementedByExpression rb)
{
return rb.Implementations.Select(ee => new When(Visit(ee.Value.ExternalId).NotEqualsNulll(), Visit(ee.Value))).ToCondition(rb.Type);
}
protected internal override Expression VisitImplementedByAll(ImplementedByAllExpression rba)
{
return Expression.Call(retriever, miRequestIBA.MakeGenericMethod(rba.Type),
Visit(NullifyColumn(rba.TypeId.TypeColumn)),
Visit(NullifyColumn(rba.Id)));
}
static readonly ConstantExpression NullType = Expression.Constant(null, typeof(Type));
static readonly ConstantExpression NullId = Expression.Constant(null, typeof(int?));
protected internal override Expression VisitTypeEntity(TypeEntityExpression typeFie)
{
return Expression.Condition(
Expression.NotEqual(Visit(NullifyColumn(typeFie.ExternalId)), NullId),
Expression.Constant(typeFie.TypeValue, typeof(Type)),
NullType);
}
protected internal override Expression VisitTypeImplementedBy(TypeImplementedByExpression typeIb)
{
return typeIb.TypeImplementations.Reverse().Aggregate((Expression)NullType, (acum, imp) => Expression.Condition(
Expression.NotEqual(Visit(NullifyColumn(imp.Value)), NullId),
Expression.Constant(imp.Key, typeof(Type)),
acum));
}
static MethodInfo miGetType = ReflectionTools.GetMethodInfo((Schema s) => s.GetType(1));
protected internal override Expression VisitTypeImplementedByAll(TypeImplementedByAllExpression typeIba)
{
return Expression.Condition(
Expression.NotEqual(Visit(NullifyColumn(typeIba.TypeColumn)), NullId),
SchemaGetType(typeIba),
NullType);
}
private MethodCallExpression SchemaGetType(TypeImplementedByAllExpression typeIba)
{
return Expression.Call(Expression.Constant(Schema.Current), miGetType, Visit(typeIba.TypeColumn).UnNullify());
}
protected internal override Expression VisitLiteReference(LiteReferenceExpression lite)
{
var reference = Visit(lite.Reference);
var toStr = Visit(lite.CustomToStr);
return Lite.ToLiteFatInternalExpression(reference, toStr ?? Expression.Constant(null, typeof(string)));
}
protected internal override Expression VisitLiteValue(LiteValueExpression lite)
{
var id = Visit(NullifyColumn(lite.Id));
if (id == null)
return Expression.Constant(null, lite.Type);
var toStr = Visit(lite.ToStr);
var typeId = lite.TypeId;
var toStringOrNull = toStr ?? Expression.Constant(null, typeof(string));
Expression nothing = Expression.Constant(null, lite.Type);
Expression liteConstructor;
if (typeId is TypeEntityExpression)
{
Type type = ((TypeEntityExpression)typeId).TypeValue;
liteConstructor = Expression.Condition(Expression.NotEqual(id, NullId),
Expression.Convert(Lite.NewExpression(type, id, toStringOrNull), lite.Type),
nothing);
}
else if (typeId is TypeImplementedByExpression tib)
{
liteConstructor = tib.TypeImplementations.Aggregate(nothing,
(acum, ti) =>
{
var visitId = Visit(NullifyColumn(ti.Value));
return Expression.Condition(Expression.NotEqual(visitId, NullId),
Expression.Convert(Lite.NewExpression(ti.Key, visitId, toStringOrNull), lite.Type), acum);
});
}
else if (typeId is TypeImplementedByAllExpression tiba)
{
var tid = Visit(NullifyColumn(tiba.TypeColumn));
liteConstructor = Expression.Convert(Expression.Call(miLiteCreateParse, Expression.Constant(Schema.Current), tid, id.UnNullify(), toStringOrNull), lite.Type);
}
else
{
liteConstructor = Expression.Condition(Expression.NotEqual(id.Nullify(), NullId),
Expression.Convert(Expression.Call(miLiteCreate, Visit(typeId), id.UnNullify(), toStringOrNull), lite.Type),
nothing);
}
if (toStr != null)
return Expression.Call(retriever, miModifiablePostRetrieving.MakeGenericMethod(typeof(LiteImp)), liteConstructor.TryConvert(typeof(LiteImp))).TryConvert(liteConstructor.Type);
else
return Expression.Call(retriever, miRequestLite.MakeGenericMethod(Lite.Extract(lite.Type)!), liteConstructor);
}
static readonly MethodInfo miLiteCreateParse = ReflectionTools.GetMethodInfo(() => LiteCreateParse(null!, null, null!, null!));
static Lite<Entity>? LiteCreateParse(Schema schema, PrimaryKey? typeId, string id, string toString)
{
if (typeId == null)
return null;
Type type = schema.GetType(typeId.Value);
return Lite.Create(type, PrimaryKey.Parse(id, type), toString);
}
static MethodInfo miLiteCreate = ReflectionTools.GetMethodInfo(() => Lite.Create(null!, 0, null));
protected internal override Expression VisitMListElement(MListElementExpression mle)
{
Type type = mle.Type;
var bindings = new List<MemberAssignment>
{
Expression.Bind(type.GetProperty("RowId"), Visit(mle.RowId.UnNullify())),
Expression.Bind(type.GetProperty("Parent"), Visit(mle.Parent)),
};
if (mle.Order != null)
bindings.Add(Expression.Bind(type.GetProperty("Order"), Visit(mle.Order)));
bindings.Add(Expression.Bind(type.GetProperty("Element"), Visit(mle.Element)));
var init = Expression.MemberInit(Expression.New(type), bindings);
return Expression.Condition(SmartEqualizer.NotEqualNullable(Visit(mle.RowId.Nullify()), NullId),
init,
Expression.Constant(null, init.Type));
}
private Type? ConstantType(Expression typeId)
{
if (typeId.NodeType == ExpressionType.Convert)
typeId = ((UnaryExpression)typeId).Operand;
if (typeId.NodeType == ExpressionType.Constant)
return (Type)((ConstantExpression)typeId).Value;
return null;
}
protected internal override Expression VisitSqlConstant(SqlConstantExpression sce)
{
return Expression.Constant(sce.Value, sce.Type);
}
protected internal override Expression VisitPrimaryKey(PrimaryKeyExpression pk)
{
var val = Visit(pk.Value);
return Expression.Call(miWrap, Expression.Convert(val, typeof(IComparable)));
}
static readonly MethodInfo miWrap = ReflectionTools.GetMethodInfo(() => PrimaryKey.Wrap(1));
protected internal override Expression VisitPrimaryKeyString(PrimaryKeyStringExpression pk)
{
var id = this.Visit(pk.Id);
var type = this.Visit(pk.TypeId);
return Expression.Call(miTryParse, type, id);
}
static readonly MethodInfo miTryParse = ReflectionTools.GetMethodInfo(() => TryParse(null!, null!));
static PrimaryKey? TryParse(Type type, string id)
{
if (type == null)
return null;
return PrimaryKey.Parse(id, type);
}
protected internal override Expression VisitToDayOfWeek(ToDayOfWeekExpression toDayOfWeek)
{
var result = this.Visit(toDayOfWeek.Expression);
if (Schema.Current.Settings.IsPostgres)
{
return Expression.Call(ToDayOfWeekExpression.miToDayOfWeekPostgres, result);
}
else
{
var dateFirst = ((SqlServerConnector)Connector.Current).DateFirst;
return Expression.Call(ToDayOfWeekExpression.miToDayOfWeekSql, result, Expression.Constant(dateFirst, typeof(byte)));
}
}
static MethodInfo miToInterval = ReflectionTools.GetMethodInfo(() => ToInterval<int>(new NpgsqlTypes.NpgsqlRange<int>())).GetGenericMethodDefinition();
static Interval<T> ToInterval<T>(NpgsqlTypes.NpgsqlRange<T> range) where T : struct, IComparable<T>, IEquatable<T>
=> new Interval<T>(range.LowerBound, range.UpperBound);
protected internal override Expression VisitInterval(IntervalExpression interval)
{
var intervalType = interval.Type.GetGenericArguments()[0];
if (Schema.Current.Settings.IsPostgres)
{
return Expression.Call(miToInterval.MakeGenericMethod(intervalType), Visit(interval.PostgresRange));
}
else
{
return Expression.New(typeof(Interval<>).MakeGenericType(intervalType).GetConstructor(new[] { intervalType, intervalType })!, Visit(interval.Min), Visit(interval.Max));
}
}
protected override Expression VisitNew(NewExpression node)
{
var expressions = this.Visit(node.Arguments);
if (node.Members != null)
{
for (int i = 0; i < node.Members.Count; i++)
{
var m = node.Members[i];
var e = expressions[i];
if (m is PropertyInfo pi && !pi.PropertyType.IsAssignableFrom(e.Type))
{
throw new InvalidOperationException(
$"Impossible to assign a '{e.Type.TypeName()}' to the member '{m.Name}' of type '{pi.PropertyType.TypeName()}'." +
(e.Type.IsInstantiationOf(typeof(IEnumerable<>)) ? "\nConsider adding '.ToList()' at the end of your sub-query" : null)
);
}
}
}
return (Expression)node.Update(expressions);
}
}
}
internal class Scope
{
public Alias Alias;
public Dictionary<string, int> Positions;
public Scope(Alias alias, Dictionary<string, int> positions)
{
Alias = alias;
Positions = positions;
}
static readonly PropertyInfo miReader = ReflectionTools.GetPropertyInfo((IProjectionRow row) => row.Reader);
public Expression GetColumnExpression(Expression row, Alias alias, string name, Type type)
{
if (alias != Alias)
throw new InvalidOperationException("alias '{0}' not found".FormatWith(alias));
int position = Positions.GetOrThrow(name, "column name '{0}' not found in alias '" + alias + "'");
return FieldReader.GetExpression(Expression.Property(row, miReader), position, type);
}
static readonly MethodInfo miLookupRequest = ReflectionTools.GetMethodInfo((IProjectionRow row) => row.LookupRequest<int, double>(null!, 0, null!)).GetGenericMethodDefinition();
static readonly MethodInfo miLookup = ReflectionTools.GetMethodInfo((IProjectionRow row) => row.Lookup<int, double>(null!, 0)).GetGenericMethodDefinition();
public Expression LookupEager(Expression row, ChildProjectionExpression cProj)
{
if (cProj.IsLazyMList)
throw new InvalidOperationException("IsLazyMList not expected at this stage");
Type type = cProj.Projection.UniqueFunction == null ? cProj.Type.ElementType()! : cProj.Type;
MethodInfo mi = miLookup.MakeGenericMethod(cProj.OuterKey.Type, type);
Expression call = Expression.Call(row, mi, Expression.Constant(cProj.Token), cProj.OuterKey);
if (cProj.Projection.UniqueFunction != null)
throw new InvalidOperationException("Eager ChildProyection with UniqueFunction '{0}' not expected at this stage".FormatWith(cProj.Projection.UniqueFunction));
return call;
}
public Expression LookupMList(Expression row, ChildProjectionExpression cProj, MemberExpression field)
{
if (!cProj.IsLazyMList)
throw new InvalidOperationException("Not IsLazyMList not expected at this stage");
if (!cProj.Type.IsMList())
throw new InvalidOperationException("Lazy ChildProyection of type '{0}' instead of MList".FormatWith(cProj.Type.TypeName()));
if (cProj.Projection.UniqueFunction != null)
throw new InvalidOperationException("Lazy ChildProyection with UniqueFunction '{0}'".FormatWith(cProj.Projection.UniqueFunction));
MethodInfo mi = miLookupRequest.MakeGenericMethod(cProj.OuterKey.Type, cProj.Type.ElementType()!);
return Expression.Call(row, mi, Expression.Constant(cProj.Token), cProj.OuterKey, field);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.IO.Tests
{
public class Directory_Delete_str : FileSystemTest
{
#region Utilities
public virtual void Delete(string path)
{
Directory.Delete(path);
}
#endregion
#region UniversalTests
[Fact]
public void NullParameters()
{
Assert.Throws<ArgumentNullException>(() => Delete(null));
}
[Fact]
public void InvalidParameters()
{
Assert.Throws<ArgumentException>(() => Delete(string.Empty));
}
[Fact]
public void ShouldThrowIOExceptionIfContainedFileInUse()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
using (File.Create(Path.Combine(testDir.FullName, GetTestFileName())))
{
Assert.Throws<IOException>(() => Delete(testDir.FullName));
}
Assert.True(testDir.Exists);
}
[Fact]
public void ShouldThrowIOExceptionForDirectoryWithFiles()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
File.Create(Path.Combine(testDir.FullName, GetTestFileName())).Dispose();
Assert.Throws<IOException>(() => Delete(testDir.FullName));
Assert.True(testDir.Exists);
}
[Fact]
public void DirectoryWithSubdirectories()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.CreateSubdirectory(GetTestFileName());
Assert.Throws<IOException>(() => Delete(testDir.FullName));
Assert.True(testDir.Exists);
}
[Fact]
[OuterLoop]
public void DeleteRoot()
{
Assert.Throws<IOException>(() => Delete(Path.GetPathRoot(Directory.GetCurrentDirectory())));
}
[Fact]
public void PositiveTest()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Delete(testDir.FullName);
Assert.False(testDir.Exists);
}
[Theory, MemberData(nameof(TrailingCharacters))]
public void MissingFile_ThrowsDirectoryNotFound(char trailingChar)
{
string path = GetTestFilePath() + trailingChar;
Assert.Throws<DirectoryNotFoundException>(() => Delete(path));
}
[Theory, MemberData(nameof(TrailingCharacters))]
public void MissingDirectory_ThrowsDirectoryNotFound(char trailingChar)
{
string path = Path.Combine(GetTestFilePath(), "file" + trailingChar);
Assert.Throws<DirectoryNotFoundException>(() => Delete(path));
}
[Fact]
public void ShouldThrowIOExceptionDeletingCurrentDirectory()
{
Assert.Throws<IOException>(() => Delete(Directory.GetCurrentDirectory()));
}
[ConditionalFact(nameof(CanCreateSymbolicLinks))]
public void DeletingSymLinkDoesntDeleteTarget()
{
var path = GetTestFilePath();
var linkPath = GetTestFilePath();
Directory.CreateDirectory(path);
Assert.True(MountHelper.CreateSymbolicLink(linkPath, path, isDirectory: true));
// Both the symlink and the target exist
Assert.True(Directory.Exists(path), "path should exist");
Assert.True(Directory.Exists(linkPath), "linkPath should exist");
// Delete the symlink
Directory.Delete(linkPath);
// Target should still exist
Assert.True(Directory.Exists(path), "path should still exist");
Assert.False(Directory.Exists(linkPath), "linkPath should no longer exist");
}
[ConditionalFact(nameof(UsingNewNormalization))]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap | TargetFrameworkMonikers.UapAot)]
public void ExtendedDirectoryWithSubdirectories()
{
DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath());
testDir.CreateSubdirectory(GetTestFileName());
Assert.Throws<IOException>(() => Delete(testDir.FullName));
Assert.True(testDir.Exists);
}
[ConditionalFact(nameof(LongPathsAreNotBlocked), nameof(UsingNewNormalization))]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap | TargetFrameworkMonikers.UapAot)]
public void LongPathExtendedDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(IOServices.GetPath(IOInputs.ExtendedPrefix + TestDirectory, characterCount: 500).FullPath);
Delete(testDir.FullName);
Assert.False(testDir.Exists);
}
#endregion
#region PlatformSpecific
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Deleting readonly directory throws IOException
public void WindowsDeleteReadOnlyDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.Attributes = FileAttributes.ReadOnly;
Assert.Throws<IOException>(() => Delete(testDir.FullName));
Assert.True(testDir.Exists);
testDir.Attributes = FileAttributes.Normal;
}
[ConditionalFact(nameof(UsingNewNormalization))]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap | TargetFrameworkMonikers.UapAot)]
[PlatformSpecific(TestPlatforms.Windows)] // Deleting extended readonly directory throws IOException
public void WindowsDeleteExtendedReadOnlyDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath());
testDir.Attributes = FileAttributes.ReadOnly;
Assert.Throws<IOException>(() => Delete(testDir.FullName));
Assert.True(testDir.Exists);
testDir.Attributes = FileAttributes.Normal;
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Deleting readOnly directory succeeds
public void UnixDeleteReadOnlyDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.Attributes = FileAttributes.ReadOnly;
Delete(testDir.FullName);
Assert.False(testDir.Exists);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Deleting hidden directory succeeds
public void WindowsShouldBeAbleToDeleteHiddenDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.Attributes = FileAttributes.Hidden;
Delete(testDir.FullName);
Assert.False(testDir.Exists);
}
[ConditionalFact(nameof(UsingNewNormalization))]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap | TargetFrameworkMonikers.UapAot)]
[PlatformSpecific(TestPlatforms.Windows)] // Deleting extended hidden directory succeeds
public void WindowsShouldBeAbleToDeleteExtendedHiddenDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath());
testDir.Attributes = FileAttributes.Hidden;
Delete(testDir.FullName);
Assert.False(testDir.Exists);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Deleting hidden directory succeeds
public void UnixShouldBeAbleToDeleteHiddenDirectory()
{
string testDir = "." + GetTestFileName();
Directory.CreateDirectory(Path.Combine(TestDirectory, testDir));
Assert.True(0 != (new DirectoryInfo(Path.Combine(TestDirectory, testDir)).Attributes & FileAttributes.Hidden));
Delete(Path.Combine(TestDirectory, testDir));
Assert.False(Directory.Exists(testDir));
}
#endregion
}
public class Directory_Delete_str_bool : Directory_Delete_str
{
#region Utilities
public override void Delete(string path)
{
Directory.Delete(path, false);
}
public virtual void Delete(string path, bool recursive)
{
Directory.Delete(path, recursive);
}
#endregion
[Fact]
public void RecursiveDelete()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
File.Create(Path.Combine(testDir.FullName, GetTestFileName())).Dispose();
testDir.CreateSubdirectory(GetTestFileName());
Delete(testDir.FullName, true);
Assert.False(testDir.Exists);
}
[Fact]
public void RecursiveDeleteWithTrailingSlash()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Delete(testDir.FullName + Path.DirectorySeparatorChar, true);
Assert.False(testDir.Exists);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Recursive delete throws IOException if directory contains in-use file
public void RecursiveDelete_ShouldThrowIOExceptionIfContainedFileInUse()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
using (File.Create(Path.Combine(testDir.FullName, GetTestFileName())))
{
Assert.Throws<IOException>(() => Delete(testDir.FullName, true));
}
Assert.True(testDir.Exists);
}
}
}
| |
// 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal sealed partial class SolutionCrawlerRegistrationService
{
private sealed partial class WorkCoordinator
{
private sealed partial class IncrementalAnalyzerProcessor
{
private sealed class LowPriorityProcessor : AbstractPriorityProcessor
{
private readonly AsyncProjectWorkItemQueue _workItemQueue;
public LowPriorityProcessor(
IAsynchronousOperationListener listener,
IncrementalAnalyzerProcessor processor,
Lazy<ImmutableArray<IIncrementalAnalyzer>> lazyAnalyzers,
IGlobalOperationNotificationService globalOperationNotificationService,
int backOffTimeSpanInMs,
CancellationToken shutdownToken) :
base(listener, processor, lazyAnalyzers, globalOperationNotificationService, backOffTimeSpanInMs, shutdownToken)
{
_workItemQueue = new AsyncProjectWorkItemQueue(processor._registration.ProgressReporter, processor._registration.Workspace);
Start();
}
protected override Task WaitAsync(CancellationToken cancellationToken)
{
return _workItemQueue.WaitAsync(cancellationToken);
}
protected override async Task ExecuteAsync()
{
try
{
// we wait for global operation, higher and normal priority processor to finish its working
await WaitForHigherPriorityOperationsAsync().ConfigureAwait(false);
// process any available project work, preferring the active project.
if (_workItemQueue.TryTakeAnyWork(
this.Processor.GetActiveProject(), this.Processor.DependencyGraph, this.Processor.DiagnosticAnalyzerService,
out var workItem, out var projectCancellation))
{
await ProcessProjectAsync(this.Analyzers, workItem, projectCancellation).ConfigureAwait(false);
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
protected override Task HigherQueueOperationTask
{
get
{
return Task.WhenAll(this.Processor._highPriorityProcessor.Running, this.Processor._normalPriorityProcessor.Running);
}
}
protected override bool HigherQueueHasWorkItem
{
get
{
return this.Processor._highPriorityProcessor.HasAnyWork || this.Processor._normalPriorityProcessor.HasAnyWork;
}
}
protected override void PauseOnGlobalOperation()
{
base.PauseOnGlobalOperation();
_workItemQueue.RequestCancellationOnRunningTasks();
}
public void Enqueue(WorkItem item)
{
this.UpdateLastAccessTime();
// Project work
item = item.With(documentId: null, projectId: item.ProjectId, asyncToken: this.Processor._listener.BeginAsyncOperation("WorkItem"));
var added = _workItemQueue.AddOrReplace(item);
// lower priority queue gets lowest time slot possible. if there is any activity going on in higher queue, it drop whatever it has
// and let higher work item run
CancelRunningTaskIfHigherQueueHasWorkItem();
Logger.Log(FunctionId.WorkCoordinator_Project_Enqueue, s_enqueueLogger, Environment.TickCount, item.ProjectId, !added);
SolutionCrawlerLogger.LogWorkItemEnqueue(this.Processor._logAggregator, item.ProjectId);
}
private void CancelRunningTaskIfHigherQueueHasWorkItem()
{
if (!HigherQueueHasWorkItem)
{
return;
}
_workItemQueue.RequestCancellationOnRunningTasks();
}
private async Task ProcessProjectAsync(ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, CancellationTokenSource source)
{
if (this.CancellationToken.IsCancellationRequested)
{
return;
}
// we do have work item for this project
var projectId = workItem.ProjectId;
var processedEverything = false;
var processingSolution = this.Processor.CurrentSolution;
try
{
using (Logger.LogBlock(FunctionId.WorkCoordinator_ProcessProjectAsync, source.Token))
{
var cancellationToken = source.Token;
var project = processingSolution.GetProject(projectId);
if (project != null)
{
var reasons = workItem.InvocationReasons;
var semanticsChanged = reasons.Contains(PredefinedInvocationReasons.SemanticChanged) ||
reasons.Contains(PredefinedInvocationReasons.SolutionRemoved);
using (Processor.EnableCaching(project.Id))
{
await RunAnalyzersAsync(analyzers, project, (a, p, c) => a.AnalyzeProjectAsync(p, semanticsChanged, reasons, c), cancellationToken).ConfigureAwait(false);
}
}
else
{
SolutionCrawlerLogger.LogProcessProjectNotExist(this.Processor._logAggregator);
RemoveProject(projectId);
}
}
processedEverything = true;
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
finally
{
// we got cancelled in the middle of processing the project.
// let's make sure newly enqueued work item has all the flag needed.
if (!processedEverything)
{
_workItemQueue.AddOrReplace(workItem.Retry(this.Listener.BeginAsyncOperation("ReenqueueWorkItem")));
}
SolutionCrawlerLogger.LogProcessProject(this.Processor._logAggregator, projectId.Id, processedEverything);
// remove one that is finished running
_workItemQueue.RemoveCancellationSource(projectId);
}
}
private void RemoveProject(ProjectId projectId)
{
foreach (var analyzer in this.Analyzers)
{
analyzer.RemoveProject(projectId);
}
}
public override void Shutdown()
{
base.Shutdown();
_workItemQueue.Dispose();
}
internal void WaitUntilCompletion_ForTestingPurposesOnly(ImmutableArray<IIncrementalAnalyzer> analyzers, List<WorkItem> items)
{
CancellationTokenSource source = new CancellationTokenSource();
var uniqueIds = new HashSet<ProjectId>();
foreach (var item in items)
{
if (uniqueIds.Add(item.ProjectId))
{
ProcessProjectAsync(analyzers, item, source).Wait();
}
}
}
internal void WaitUntilCompletion_ForTestingPurposesOnly()
{
// this shouldn't happen. would like to get some diagnostic
while (_workItemQueue.HasAnyWork)
{
Environment.FailFast("How?");
}
}
}
}
}
}
}
| |
#region Apache License
//
// 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.
//
#endregion
using System;
using System.Collections;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.IO;
using System.Threading;
using Ctrip.Layout;
using Ctrip.Core;
using Ctrip.Util;
namespace Ctrip.Appender
{
/// <summary>
/// Appender that allows clients to connect via Telnet to receive log messages
/// </summary>
/// <remarks>
/// <para>
/// The TelnetAppender accepts socket connections and streams logging messages
/// back to the client.
/// The output is provided in a telnet-friendly way so that a log can be monitored
/// over a TCP/IP socket.
/// This allows simple remote monitoring of application logging.
/// </para>
/// <para>
/// The default <see cref="Port"/> is 23 (the telnet port).
/// </para>
/// </remarks>
/// <author>Keith Long</author>
/// <author>Nicko Cadell</author>
public class TelnetAppender : AppenderSkeleton
{
private SocketHandler m_handler;
private int m_listeningPort = 23;
#region Constructor
/// <summary>
/// Default constructor
/// </summary>
/// <remarks>
/// <para>
/// Default constructor
/// </para>
/// </remarks>
public TelnetAppender()
{
}
#endregion
#region Private Static Fields
/// <summary>
/// The fully qualified type of the TelnetAppender class.
/// </summary>
/// <remarks>
/// Used by the internal logger to record the Type of the
/// log message.
/// </remarks>
private readonly static Type declaringType = typeof(TelnetAppender);
#endregion Private Static Fields
/// <summary>
/// Gets or sets the TCP port number on which this <see cref="TelnetAppender"/> will listen for connections.
/// </summary>
/// <value>
/// An integer value in the range <see cref="IPEndPoint.MinPort" /> to <see cref="IPEndPoint.MaxPort" />
/// indicating the TCP port number on which this <see cref="TelnetAppender"/> will listen for connections.
/// </value>
/// <remarks>
/// <para>
/// The default value is 23 (the telnet port).
/// </para>
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException">The value specified is less than <see cref="IPEndPoint.MinPort" />
/// or greater than <see cref="IPEndPoint.MaxPort" />.</exception>
public int Port
{
get
{
return m_listeningPort;
}
set
{
if (value < IPEndPoint.MinPort || value > IPEndPoint.MaxPort)
{
throw Ctrip.Util.SystemInfo.CreateArgumentOutOfRangeException("value", (object)value,
"The value specified for Port is less than " +
IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) +
" or greater than " +
IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + ".");
}
else
{
m_listeningPort = value;
}
}
}
#region Override implementation of AppenderSkeleton
/// <summary>
/// Overrides the parent method to close the socket handler
/// </summary>
/// <remarks>
/// <para>
/// Closes all the outstanding connections.
/// </para>
/// </remarks>
protected override void OnClose()
{
base.OnClose();
if (m_handler != null)
{
m_handler.Dispose();
m_handler = null;
}
}
/// <summary>
/// This appender requires a <see cref="Layout"/> to be set.
/// </summary>
/// <value><c>true</c></value>
/// <remarks>
/// <para>
/// This appender requires a <see cref="Layout"/> to be set.
/// </para>
/// </remarks>
protected override bool RequiresLayout
{
get { return true; }
}
/// <summary>
/// Initialize the appender based on the options set.
/// </summary>
/// <remarks>
/// <para>
/// This is part of the <see cref="IOptionHandler"/> delayed object
/// activation scheme. The <see cref="ActivateOptions"/> method must
/// be called on this object after the configuration properties have
/// been set. Until <see cref="ActivateOptions"/> is called this
/// object is in an undefined state and must not be used.
/// </para>
/// <para>
/// If any of the configuration properties are modified then
/// <see cref="ActivateOptions"/> must be called again.
/// </para>
/// <para>
/// Create the socket handler and wait for connections
/// </para>
/// </remarks>
public override void ActivateOptions()
{
base.ActivateOptions();
try
{
LogLog.Debug(declaringType, "Creating SocketHandler to listen on port ["+m_listeningPort+"]");
m_handler = new SocketHandler(m_listeningPort);
}
catch(Exception ex)
{
LogLog.Error(declaringType, "Failed to create SocketHandler", ex);
throw;
}
}
/// <summary>
/// Writes the logging event to each connected client.
/// </summary>
/// <param name="loggingEvent">The event to log.</param>
/// <remarks>
/// <para>
/// Writes the logging event to each connected client.
/// </para>
/// </remarks>
protected override void Append(LoggingEvent loggingEvent)
{
if (m_handler != null && m_handler.HasConnections)
{
m_handler.Send(RenderLoggingEvent(loggingEvent));
}
}
#endregion
#region SocketHandler helper class
/// <summary>
/// Helper class to manage connected clients
/// </summary>
/// <remarks>
/// <para>
/// The SocketHandler class is used to accept connections from
/// clients. It is threaded so that clients can connect/disconnect
/// asynchronously.
/// </para>
/// </remarks>
protected class SocketHandler : IDisposable
{
private const int MAX_CONNECTIONS = 20;
private Socket m_serverSocket;
private ArrayList m_clients = new ArrayList();
/// <summary>
/// Class that represents a client connected to this handler
/// </summary>
/// <remarks>
/// <para>
/// Class that represents a client connected to this handler
/// </para>
/// </remarks>
protected class SocketClient : IDisposable
{
private Socket m_socket;
private StreamWriter m_writer;
/// <summary>
/// Create this <see cref="SocketClient"/> for the specified <see cref="Socket"/>
/// </summary>
/// <param name="socket">the client's socket</param>
/// <remarks>
/// <para>
/// Opens a stream writer on the socket.
/// </para>
/// </remarks>
public SocketClient(Socket socket)
{
m_socket = socket;
try
{
m_writer = new StreamWriter(new NetworkStream(socket));
}
catch
{
Dispose();
throw;
}
}
/// <summary>
/// Write a string to the client
/// </summary>
/// <param name="message">string to send</param>
/// <remarks>
/// <para>
/// Write a string to the client
/// </para>
/// </remarks>
public void Send(String message)
{
m_writer.Write(message);
m_writer.Flush();
}
#region IDisposable Members
/// <summary>
/// Cleanup the clients connection
/// </summary>
/// <remarks>
/// <para>
/// Close the socket connection.
/// </para>
/// </remarks>
public void Dispose()
{
try
{
if (m_writer != null)
{
m_writer.Close();
m_writer = null;
}
}
catch { }
if (m_socket != null)
{
try
{
m_socket.Shutdown(SocketShutdown.Both);
}
catch { }
try
{
m_socket.Close();
}
catch { }
m_socket = null;
}
}
#endregion
}
/// <summary>
/// Opens a new server port on <paramref ref="port"/>
/// </summary>
/// <param name="port">the local port to listen on for connections</param>
/// <remarks>
/// <para>
/// Creates a socket handler on the specified local server port.
/// </para>
/// </remarks>
public SocketHandler(int port)
{
m_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
m_serverSocket.Bind(new IPEndPoint(IPAddress.Any, port));
m_serverSocket.Listen(5);
m_serverSocket.BeginAccept(new AsyncCallback(OnConnect), null);
}
/// <summary>
/// Sends a string message to each of the connected clients
/// </summary>
/// <param name="message">the text to send</param>
/// <remarks>
/// <para>
/// Sends a string message to each of the connected clients
/// </para>
/// </remarks>
public void Send(String message)
{
ArrayList localClients = m_clients;
foreach (SocketClient client in localClients)
{
try
{
client.Send(message);
}
catch (Exception)
{
// The client has closed the connection, remove it from our list
client.Dispose();
RemoveClient(client);
}
}
}
/// <summary>
/// Add a client to the internal clients list
/// </summary>
/// <param name="client">client to add</param>
private void AddClient(SocketClient client)
{
lock(this)
{
ArrayList clientsCopy = (ArrayList)m_clients.Clone();
clientsCopy.Add(client);
m_clients = clientsCopy;
}
}
/// <summary>
/// Remove a client from the internal clients list
/// </summary>
/// <param name="client">client to remove</param>
private void RemoveClient(SocketClient client)
{
lock(this)
{
ArrayList clientsCopy = (ArrayList)m_clients.Clone();
clientsCopy.Remove(client);
m_clients = clientsCopy;
}
}
/// <summary>
/// Test if this handler has active connections
/// </summary>
/// <value>
/// <c>true</c> if this handler has active connections
/// </value>
/// <remarks>
/// <para>
/// This property will be <c>true</c> while this handler has
/// active connections, that is at least one connection that
/// the handler will attempt to send a message to.
/// </para>
/// </remarks>
public bool HasConnections
{
get
{
ArrayList localClients = m_clients;
return (localClients != null && localClients.Count > 0);
}
}
/// <summary>
/// Callback used to accept a connection on the server socket
/// </summary>
/// <param name="asyncResult">The result of the asynchronous operation</param>
/// <remarks>
/// <para>
/// On connection adds to the list of connections
/// if there are two many open connections you will be disconnected
/// </para>
/// </remarks>
private void OnConnect(IAsyncResult asyncResult)
{
try
{
// Block until a client connects
Socket socket = m_serverSocket.EndAccept(asyncResult);
LogLog.Debug(declaringType, "Accepting connection from ["+socket.RemoteEndPoint.ToString()+"]");
SocketClient client = new SocketClient(socket);
int currentActiveConnectionsCount = m_clients.Count;
if (currentActiveConnectionsCount < MAX_CONNECTIONS)
{
try
{
client.Send("TelnetAppender v1.0 (" + (currentActiveConnectionsCount + 1) + " active connections)\r\n\r\n");
AddClient(client);
}
catch
{
client.Dispose();
}
}
else
{
client.Send("Sorry - Too many connections.\r\n");
client.Dispose();
}
}
catch
{
}
finally
{
if (m_serverSocket != null)
{
m_serverSocket.BeginAccept(new AsyncCallback(OnConnect), null);
}
}
}
#region IDisposable Members
/// <summary>
/// Close all network connections
/// </summary>
/// <remarks>
/// <para>
/// Make sure we close all network connections
/// </para>
/// </remarks>
public void Dispose()
{
ArrayList localClients = m_clients;
foreach (SocketClient client in localClients)
{
client.Dispose();
}
m_clients.Clear();
Socket localSocket = m_serverSocket;
m_serverSocket = null;
try
{
localSocket.Shutdown(SocketShutdown.Both);
}
catch
{
}
try
{
localSocket.Close();
}
catch
{
}
}
#endregion
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
namespace CSR.AST
{
/// <summary>
/// Base Scope class from which all other scopes ineherit
/// </summary>
abstract class Scope
{
// Parent symbol table
public Scope parentScope;
/// <summary>
/// Retrieves the type of a variable
/// </summary>
/// <param name="referenceExpr">Variable name</param>
/// <returns></returns>
public abstract BaseType GetVariable(string referenceExpr);
/// <summary>
/// Retrieves the signature of a function
/// </summary>
/// <param name="callExpr">CallExpression for the function</param>
/// <returns></returns>
public abstract Signature GetFunction(CallExpression callExpr);
/// <summary>
/// Emits a reference to a variable given its name
/// </summary>
/// <param name="referenceExpr">Variable name</param>
/// <param name="ilGen">IL Generator object</param>
public abstract void EmitVariableReference(string referenceExpr, ILGenerator ilGen);
/// <summary>
/// Retrieves metadata information for a function
/// </summary>
/// <param name="callExpr">CallExpression for the function</param>
/// <returns></returns>
public abstract MethodInfo GetMethodInfo(CallExpression callExpr);
/// <summary>
/// Emits a variable assignement given its name
/// </summary>
/// <param name="referenceExpr">Variable name</param>
/// <param name="ilGen">IL Generator object</param>
public abstract void EmitVariableAssignement(string referenceExpr, ILGenerator ilGen);
}
/// <summary>
/// GlobalScope represents the global scope while compiling. The global scope looks up symbols that
/// are not declared in the source code but in referenced assemblies. This is the topmost scope.
/// </summary>
class GlobalScope : Scope
{
// Lookups are used to quickly retrieve MethodInfo and Signature objects for functions
// that were found before
private Dictionary<string, MethodInfo> methodInfoLookup;
private Dictionary<string, Signature> signatureLookup;
// Lookups are used to quickly retrieve FieldInfo and BaseType objects for variables
// that were found before
private Dictionary<string, FieldInfo> fieldInfoLookup;
private Dictionary<string, BaseType> referenceLookup;
// List of referenced assemblies
private List<Assembly> references;
/// <summary>
/// Creates a new instance of GlobalScope
/// </summary>
/// <param name="references">List of assembly references</param>
public GlobalScope(List<string> references)
{
// Initialize private members
this.references = new List<Assembly>();
this.methodInfoLookup = new Dictionary<string, MethodInfo>();
this.signatureLookup = new Dictionary<string, Signature>();
this.fieldInfoLookup = new Dictionary<string, FieldInfo>();
this.referenceLookup = new Dictionary<string, BaseType>();
// Load assemblies
foreach (string file in references)
{
try
{
// Load assembly given its strong name
this.references.Add(Assembly.Load(file));
}
catch
{
// Issue error but continue compiling - assembly might not be needed and if it is, other
// errors will appear when external variables and functions are referenced
Console.WriteLine("Unable to load referenced assembly '{0}'", file);
}
}
}
/// <summary>
/// Retrieves the type of a variable
/// </summary>
/// <param name="referenceExpr">Variable name</param>
/// <returns></returns>
public override BaseType GetVariable(string referenceExpr)
{
// If variable was already found, return it
if (referenceLookup.ContainsKey(referenceExpr))
{
return referenceLookup[referenceExpr];
}
// Split reference FQN into type name and field name
string typeName = referenceExpr.Substring(0, referenceExpr.LastIndexOf("."));
string fieldName = referenceExpr.Substring(referenceExpr.LastIndexOf(".") + 1);
// For each assembly reference
foreach (Assembly asm in references)
{
// Get type (from FQN type)
Type type = Type.GetType(typeName);
// If type is not found step to next assembly
if (type == null)
{
continue;
}
// Set result
FieldInfo result = type.GetField(fieldName);
// Check if field is public and static (cannot reference instance fields)
if (((result.Attributes & FieldAttributes.Static) == FieldAttributes.Static) &&
((result.Attributes & FieldAttributes.Public) == FieldAttributes.Public))
{
// Add to dictionaries
referenceLookup.Add(referenceExpr, BaseType.FromType(result.GetType()));
fieldInfoLookup.Add(referenceExpr, result);
return referenceLookup[referenceExpr];
}
}
return null;
}
/// <summary>
/// Retrieves an external function signature from a given call expression
/// </summary>
/// <param name="callExpr">CallExpression object</param>
/// <returns>Closest matching signature or null if no matching function is found</returns>
public override Signature GetFunction(CallExpression callExpr)
{
// Convert call expression to signature
Signature sig = new Signature(callExpr);
// Candidates to best match
List<Signature> candidates = new List<Signature>();
List<MethodInfo> candidatesMethodInfo = new List<MethodInfo>();
// If signature was already found, return it
if (signatureLookup.ContainsKey(sig.ToString()))
{
return signatureLookup[sig.ToString()];
}
// If we got to global scope and function doesn't have an FQN,
// it means the function doesn't exist
if (!sig.name.Contains("."))
{
return null;
}
// Split function FQN into type name and function name
string typeName = sig.name.Substring(0, sig.name.LastIndexOf("."));
string methodName = sig.name.Substring(sig.name.LastIndexOf(".") + 1);
// For each assembly reference
foreach (Assembly asm in references)
{
Type type = null;
// Get type (from FQN type)
foreach (Type t in asm.GetTypes())
{
if (t.FullName == typeName)
{
type = t;
}
}
// If type is not found step to next assembly
if (type == null)
{
continue;
}
// Retrieve function list of the given type
foreach (MethodInfo mi in type.GetMethods())
{
// If name differs, step to next function
if (mi.Name != methodName)
{
continue;
}
// Create Signature object to test against
Signature testSig = new Signature(mi);
// Check if there is an exact match
if (sig.IsExactMatch(testSig))
{
// Add to dictionary
signatureLookup.Add(testSig.ToString(), testSig);
methodInfoLookup.Add(testSig.ToString(), mi);
return testSig;
}
// If signatures are incompatible, step to next function
if (!sig.IsCompatible(testSig))
{
continue;
}
bool add = false, brk = false;
// Check current signature against each other candidate
foreach (Signature candSig in candidates)
{
// Pick best signature from current signature and candidate
switch (sig.BestSignature(candSig, testSig))
{
// If neither is better, mark add to add this function to the list of candidates
case Match.Ambiguos:
add = true;
break;
// If this is better than the candidate
case Match.SecondBest:
// Remove candidate and mark add to add this function to the list
candidatesMethodInfo.RemoveAt(candidates.IndexOf(candSig));
candidates.Remove(candSig);
add = true;
break;
// If the candidate is better than this function there is no need to evaluate
// against other candidates - there is a better match than this one already found
case Match.FirstBest:
brk = true;
break;
}
// Stop evaluation if brk is true
if (brk)
{
break;
}
}
// Add function to the list of candidates if add is true
if (add)
{
candidates.Add(testSig);
candidatesMethodInfo.Add(mi);
}
}
}
// Check if candidate list is empty
if (candidates.Count == 0)
{
// No match was found
return null;
}
// Check if a single candidate is in the list
else if (candidates.Count == 1)
{
// Add to dictionaries
signatureLookup.Add(candidates[0].ToString(), candidates[0]);
methodInfoLookup.Add(candidates[0].ToString(), candidatesMethodInfo[0]);
return candidates[0];
}
// If more candidates are in the list
else
{
// Ambiguos call - cannot determine which candidate is the best
return null;
}
}
/// <summary>
/// Retrieves metadata information for a function
/// </summary>
/// <param name="callExpr">CallExpression for the function</param>
/// <returns></returns>
public override MethodInfo GetMethodInfo(CallExpression callExpr)
{
// Since signatures are always searched during the evaluation step,
// a MethodInfo must exist in the dictionary
return methodInfoLookup[new Signature(callExpr).ToString()];
}
/// <summary>
/// Emits a reference to a variable given its name
/// </summary>
/// <param name="referenceExpr">Variable name</param>
/// <param name="ilGen">IL Generator object</param>
public override void EmitVariableReference(string referenceExpr, ILGenerator ilGen)
{
// Emit a load static field instruction for the static field
ilGen.Emit(OpCodes.Ldsfld, fieldInfoLookup[referenceExpr]);
}
/// <summary>
/// Emits a variable assignement given its name
/// </summary>
/// <param name="referenceExpr">Variable name</param>
/// <param name="ilGen">IL Generator object</param>
public override void EmitVariableAssignement(string referenceExpr, ILGenerator ilGen)
{
// Get FieldInfo object from dictionary
FieldInfo fi = fieldInfoLookup[referenceExpr];
// Emit a store to static field instruction for the static field
ilGen.Emit(OpCodes.Stsfld, fi);
}
}
/// <summary>
/// ProgramScope represents the scope of the program which stores top level symbols and program name
/// </summary>
class ProgramScope : Scope
{
// The name of the executable
public string name;
// List of variable declarations
public List<VariableDeclaration> variables;
// List of function declarations
public List<FunctionDeclaration> functions;
// Entry point function
public FunctionDeclaration entryPoint;
/// <summary>
/// Creates a new ProgramScope
/// </summary>
/// <param name="parentScope">Parent scope (GlobalScope object should be used)</param>
public ProgramScope(Scope parentScope)
{
// Initialize private members
functions = new List<FunctionDeclaration>();
variables = new List<VariableDeclaration>();
this.parentScope = parentScope;
}
/// <summary>
/// Adds a function declaration
/// </summary>
/// <param name="decl">FunctionDeclaration object</param>
public void AddFunction(FunctionDeclaration decl)
{
// Check if a function with the same exact signature was already declared
foreach (FunctionDeclaration func in functions)
{
// Check if functions have the same name
if (func.name == decl.name)
{
// Check if functions have the same signature
if (func.ToSignature().IsExactMatch(decl.ToSignature()))
{
// Issue error
Compiler.Compiler.errors.SemErr(decl.t.line, decl.t.col, string.Format("Function '{0}' already declared", decl.name));
}
}
}
// Add function to list
functions.Add(decl);
}
/// <summary>
/// Retrieves the type of a variable
/// </summary>
/// <param name="referenceExpr">Variable name</param>
/// <returns></returns>
public override BaseType GetVariable(string referenceExpr)
{
// Search the list of variables
foreach (VariableDeclaration decl in variables)
{
if (decl.name == referenceExpr)
{
return decl.type;
}
}
// If no match is found, delegate request to parent scope
return parentScope.GetVariable(referenceExpr);
}
/// <summary>
/// Retrieves a function signature from a given call expression
/// </summary>
/// <param name="callExpr">CallExpression object</param>
/// <returns></returns>
public override Signature GetFunction(CallExpression callExpr)
{
// Convert call expression to signature
Signature sig = new Signature(callExpr);
// Candidates to best match
List<Signature> candidates = new List<Signature>();
// For each function in function list
foreach (FunctionDeclaration decl in functions)
{
// Create signature
Signature testSig = decl.ToSignature();
// If name is different, continue to next function
if (sig.name != testSig.name)
{
continue;
}
// If an exact match is found, return it
if (sig.IsExactMatch(testSig))
{
return testSig;
}
// If signatures are incompatible, continue to next function
if (!sig.IsCompatible(testSig))
{
continue;
}
bool add = true, brk = false;
// Check current signature against each other candidate
foreach (Signature candSig in candidates)
{
// Pick best signature from current signature and candidate
switch (sig.BestSignature(candSig, testSig))
{
// If neither is better, step to next function
case Match.Ambiguos:
break;
// If current signature is better, remove candidate from list
case Match.SecondBest:
candidates.Remove(candSig);
break;
// If candidate is better, drop this function
case Match.FirstBest:
add = false;
brk = true;
break;
}
// If brk is true, stop evaluating
if (brk)
{
break;
}
}
// If add is true, add this function to the list of candidates
if (add)
{
candidates.Add(testSig);
}
}
// Check if candidate list is empty
if (candidates.Count == 0)
{
// No match was found, delegate request to parent scope
return parentScope.GetFunction(callExpr);
}
// Check if a single match was found
else if (candidates.Count == 1)
{
// Return match
return candidates[0];
}
// More than one match found
else
{
// Ambiguos function call
return null;
}
}
/// <summary>
/// Emits a reference to a variable given its name
/// </summary>
/// <param name="referenceExpr">Variable name</param>
/// <param name="ilGen">IL Generator object</param>
public override void EmitVariableReference(string referenceExpr, ILGenerator ilGen)
{
// Lookup variable in variable list
foreach (VariableDeclaration decl in variables)
{
if (decl.name == referenceExpr)
{
// Emit load static field instruction
ilGen.Emit(OpCodes.Ldsfld, decl.fb);
return;
}
}
// If no variable is found, delegate request to parent scope
parentScope.EmitVariableReference(referenceExpr, ilGen);
}
/// <summary>
/// Retrieves a function MethodInfo from a given call expression
/// </summary>
/// <param name="callExpr">CallExpression object</param>
/// <returns>MethodInfo of closest matching function or null if no matching function
/// is found</returns>
public override MethodInfo GetMethodInfo(CallExpression callExpr)
{
// Convert call expression to signature
Signature sig = new Signature(callExpr);
// Candidates to best match
List<Signature> candidates = new List<Signature>();
List<MethodInfo> candidatesMethodInfo = new List<MethodInfo>();
// For each function in function list
foreach (FunctionDeclaration decl in functions)
{
// Create signature
Signature testSig = decl.ToSignature();
// If name is different, continue to next function
if (sig.name != testSig.name)
{
continue;
}
// If an exact match is found, return it
if (sig.IsExactMatch(testSig))
{
return decl.mb;
}
// If signatures are incompatible, continue to next function
if (!sig.IsCompatible(testSig))
{
continue;
}
bool add = false, brk = false;
// Check current signature against each other candidate
foreach (Signature candSig in candidates)
{
// Pick best signature from current signature and candidate
switch (sig.BestSignature(candSig, testSig))
{
// If neither is better, mark add to add this function to the list of candidates
case Match.Ambiguos:
add = true;
break;
// If this is better, remove the candidate from the list and mark add
case Match.SecondBest:
candidatesMethodInfo.RemoveAt(candidates.IndexOf(candSig));
candidates.Remove(candSig);
add = true;
break;
// If candidate is better, stop evaluating
case Match.FirstBest:
brk = true;
break;
}
// If brk is true, stop evaluating
if (brk)
{
break;
}
}
// If add is true, add this function to the candidate list
if (add)
{
candidates.Add(testSig);
}
}
// Check if candidate list is empty
if (candidates.Count == 0)
{
// If no match was found, delegate request to parent scope
return parentScope.GetMethodInfo(callExpr);
}
// Check if a single match was found
else if (candidates.Count == 1)
{
// Return match
return candidatesMethodInfo[0];
}
// More than one match - ambiguos
else
{
// Cannot determine which function to call
return null;
}
}
/// <summary>
/// Appends a list of variable declarations to the variable list
/// </summary>
/// <param name="decls">Variable declaration list</param>
public void AddVariables(List<VariableDeclaration> decls)
{
variables.AddRange(decls);
// Check if the same identifier appears twice in the variable declarations
for (int i = 0; i < variables.Count - 1; i++)
{
for (int j = i + 1; j < variables.Count; j++)
{
if (variables[i].name == variables[j].name)
{
// Issue error
Compiler.Compiler.errors.SemErr(variables[j].t.line, variables[j].t.col, string.Format("Identifier redeclared '{0}'", variables[j].name));
}
}
}
}
#region Evaluation
/// <summary>
/// Recursively evaluates the AST
/// </summary>
public void Evaluate()
{
// Add the entry point to the function declaration list
functions.Add(entryPoint);
// Evaluate each function declaration
foreach (FunctionDeclaration decl in functions)
{
decl.Evaluate();
}
}
#endregion
#region Reflection
// Reflection.Emit objectss
private AssemblyName an;
private AssemblyBuilder ab;
private ModuleBuilder mb;
private TypeBuilder tb;
/// <summary>
/// Emits all metadata
/// </summary>
public void EmitDeclaration()
{
// Create a new assembly and module
an = new AssemblyName(name);
ab = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.Save);
mb = ab.DefineDynamicModule(name, name + ".exe");
// Emit metadata for each function declaration
foreach (FunctionDeclaration decl in functions)
{
decl.EmitDeclaration(mb);
}
// Type is used to store global variables
tb = mb.DefineType("Data", TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.Sealed);
foreach (VariableDeclaration decl in variables)
{
decl.EmitDeclaration(tb);
}
// Creates a private, static constructor to instantiate any arrays
ConstructorBuilder cb = tb.DefineConstructor(MethodAttributes.Private | MethodAttributes.Static, CallingConventions.Standard, null);
// Creates the IL Generator object for the constructor
ILGenerator ilGen = cb.GetILGenerator();
// Step through the variable list
for (int i = 0; i < variables.Count; i++)
{
ArrayType arrType = variables[i].type as ArrayType;
// If an array is found
if (arrType != null)
{
// Instantiate array
arrType.EmitInstance(ilGen);
ilGen.Emit(OpCodes.Stsfld, variables[i].fb);
}
}
// Return
ilGen.Emit(OpCodes.Ret);
// Create Data class
tb.CreateType();
}
/// <summary>
/// Emits all code
/// </summary>
public void EmitCode()
{
// EmitInstance code for each function declaration
foreach (FunctionDeclaration decl in functions)
{
decl.EmitBody();
}
// Set entry point and finalize
ab.SetEntryPoint(entryPoint.GetMethodInfo());
mb.CreateGlobalFunctions();
// Save assembly
ab.Save(name + ".exe");
}
/// <summary>
/// Emits a variable assignement given its name
/// </summary>
/// <param name="referenceExpr">Variable name</param>
/// <param name="ilGen">IL Generator object</param>
public override void EmitVariableAssignement(string referenceExpr, ILGenerator ilGen)
{
// Step through variable list
for (int i = 0; i < variables.Count; i++)
{
// If variable is found
if (variables[i].name == referenceExpr)
{
// Emit assignement
ilGen.Emit(OpCodes.Stsfld, variables[i].fb);
return;
}
}
// If variable was not found, delegate request to parent scope
parentScope.EmitVariableAssignement(referenceExpr, ilGen);
}
#endregion
}
/// <summary>
/// LocalScope represents the scope of a function which stores its variables and arguments
/// </summary>
class LocalScope : Scope
{
// List of variable declarations and arguments
public List<VariableDeclaration> variables;
public List<VariableDeclaration> arguments;
// Function return type
public BaseType returnType;
/// <summary>
/// Creates a new LocalScope given a parent scope
/// </summary>
/// <param name="parentScope">Parent scope</param>
public LocalScope(Scope parentScope)
{
// Initialize private members
variables = new List<VariableDeclaration>();
arguments = new List<VariableDeclaration>();
this.parentScope = parentScope;
}
/// <summary>
/// Adds a variable to the variable list
/// </summary>
/// <param name="decl"></param>
public void AddVariable(VariableDeclaration decl)
{
// Check if the same identifier was already declared as a variable
foreach (VariableDeclaration var in variables)
{
if (decl.name == var.name)
{
// Issue error
Compiler.Compiler.errors.SemErr(decl.t.line, decl.t.col, string.Format("Identifier redeclared '{0}'", decl.name));
}
}
variables.Add(decl);
}
/// <summary>
/// Adds an argument to the argument list
/// </summary>
/// <param name="decl"></param>
public void AddArgument(VariableDeclaration decl)
{
// Check if the same identifier was already declared as an argument
foreach (VariableDeclaration arg in arguments)
{
if (decl.name == arg.name)
{
// Issue error
Compiler.Compiler.errors.SemErr(decl.t.line, decl.t.col, string.Format("Identifier redeclared '{0}'", decl.name));
}
}
arguments.Add(decl);
}
/// <summary>
/// Appends a list of variables to the variable list
/// </summary>
/// <param name="decls"></param>
public void AddVariables(List<VariableDeclaration> decls)
{
variables.AddRange(decls);
// Check if the same identifier appears twice in the variable declarations
for (int i = 0; i < variables.Count - 1; i++)
{
for (int j = i + 1; j < variables.Count; j++)
{
if (variables[i].name == variables[j].name)
{
// Issue error
Compiler.Compiler.errors.SemErr(variables[j].t.line, variables[j].t.col, string.Format("Identifier redeclared '{0}'", variables[j].name));
}
}
}
}
/// <summary>
/// Retrieves the type of a variable
/// </summary>
/// <param name="referenceExpr">Variable name</param>
/// <returns></returns>
public override BaseType GetVariable(string referenceExpr)
{
// Search for variable in variable list
BaseType result = GetVariable(referenceExpr, variables);
// Check if no variable was found
if (result == null)
{
// Search for variable in argument list
result = GetVariable(referenceExpr, arguments);
// Check if no argument was found
if (result == null)
{
// Delegate request to parent scope
return parentScope.GetVariable(referenceExpr);
}
}
return result;
}
/// <summary>
/// Looks up a variable in a given list of variables
/// </summary>
/// <param name="referenceExpr">Variable name</param>
/// <param name="declList">List of variables</param>
/// <returns></returns>
private BaseType GetVariable(string referenceExpr, List<VariableDeclaration> declList)
{
// Step through variable list
foreach (VariableDeclaration decl in declList)
{
if (decl.name == referenceExpr)
{
// Return match
return decl.type;
}
}
return null;
}
/// <summary>
/// Retrieves a function signature from a given call expression
/// </summary>
/// <param name="callExpr">CallExpression object</param>
/// <returns></returns>
public override Signature GetFunction(CallExpression callExpr)
{
// Delegate request to parent scope since functions cannot be declared inside other functions
return parentScope.GetFunction(callExpr);
}
/// <summary>
/// Emits a reference to a variable given its name
/// </summary>
/// <param name="referenceExpr">Variable name</param>
/// <param name="ilGen">IL Generator object</param>
public override void EmitVariableReference(string referenceExpr, ILGenerator ilGen)
{
// Step through variable list
for (int i = 0; i < variables.Count; i++)
{
if (variables[i].name == referenceExpr)
{
// If variable is found, load local variable and return
ilGen.Emit(OpCodes.Ldloc, (short)i);
return;
}
}
// Step through argument list
for (int i = 0; i < arguments.Count; i++)
{
if (arguments[i].name == referenceExpr)
{
// If argument is found, load argument and return
ilGen.Emit(OpCodes.Ldarg, (short)i);
return;
}
}
// If no match was found, delegate request to parent scope
parentScope.EmitVariableReference(referenceExpr, ilGen);
}
/// <summary>
/// Emits a variable assignement given its name
/// </summary>
/// <param name="referenceExpr">Variable name</param>
/// <param name="ilGen">IL Generator object</param>
public override void EmitVariableAssignement(string referenceExpr, ILGenerator ilGen)
{
// Step through variable list
for (int i = 0; i < variables.Count; i++)
{
if (variables[i].name == referenceExpr)
{
// If variable is found, emit store to locale and return
ilGen.Emit(OpCodes.Stloc, (short)i);
return;
}
}
// If no match was found, delegate request to parent scope
parentScope.EmitVariableAssignement(referenceExpr, ilGen);
}
/// <summary>
/// Retrieves metadata information for a function
/// </summary>
/// <param name="callExpr">CallExpression for the function</param>
/// <returns></returns>
public override MethodInfo GetMethodInfo(CallExpression callExpr)
{
// Delegate request to parent scope since functions cannot be declared inside other functions
return parentScope.GetMethodInfo(callExpr);
}
/// <summary>
/// Emit local variable declaration and array instantiation code
/// </summary>
/// <param name="ilGen">IL Generator object</param>
public void EmitCode(ILGenerator ilGen)
{
// For each variable in variable list
foreach (VariableDeclaration decl in variables)
{
// Declare local variable
ilGen.DeclareLocal(decl.type.ToCLRType());
}
// Step through the variable list
for (int i = 0; i < variables.Count; i++)
{
ArrayType arrType = variables[i].type as ArrayType;
// If an array variable is found
if (arrType != null)
{
// Instantiate array
arrType.EmitInstance(ilGen);
ilGen.Emit(OpCodes.Stloc, (short)i);
}
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V9.Resources
{
/// <summary>Resource name for the <c>KeywordPlanCampaignKeyword</c> resource.</summary>
public sealed partial class KeywordPlanCampaignKeywordName : gax::IResourceName, sys::IEquatable<KeywordPlanCampaignKeywordName>
{
/// <summary>The possible contents of <see cref="KeywordPlanCampaignKeywordName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>customers/{customer_id}/keywordPlanCampaignKeywords/{keyword_plan_campaign_keyword_id}</c>.
/// </summary>
CustomerKeywordPlanCampaignKeyword = 1,
}
private static gax::PathTemplate s_customerKeywordPlanCampaignKeyword = new gax::PathTemplate("customers/{customer_id}/keywordPlanCampaignKeywords/{keyword_plan_campaign_keyword_id}");
/// <summary>
/// Creates a <see cref="KeywordPlanCampaignKeywordName"/> containing an unparsed resource name.
/// </summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="KeywordPlanCampaignKeywordName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static KeywordPlanCampaignKeywordName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new KeywordPlanCampaignKeywordName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="KeywordPlanCampaignKeywordName"/> with the pattern
/// <c>customers/{customer_id}/keywordPlanCampaignKeywords/{keyword_plan_campaign_keyword_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="keywordPlanCampaignKeywordId">
/// The <c>KeywordPlanCampaignKeyword</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// A new instance of <see cref="KeywordPlanCampaignKeywordName"/> constructed from the provided ids.
/// </returns>
public static KeywordPlanCampaignKeywordName FromCustomerKeywordPlanCampaignKeyword(string customerId, string keywordPlanCampaignKeywordId) =>
new KeywordPlanCampaignKeywordName(ResourceNameType.CustomerKeywordPlanCampaignKeyword, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), keywordPlanCampaignKeywordId: gax::GaxPreconditions.CheckNotNullOrEmpty(keywordPlanCampaignKeywordId, nameof(keywordPlanCampaignKeywordId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="KeywordPlanCampaignKeywordName"/> with
/// pattern <c>customers/{customer_id}/keywordPlanCampaignKeywords/{keyword_plan_campaign_keyword_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="keywordPlanCampaignKeywordId">
/// The <c>KeywordPlanCampaignKeyword</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="KeywordPlanCampaignKeywordName"/> with pattern
/// <c>customers/{customer_id}/keywordPlanCampaignKeywords/{keyword_plan_campaign_keyword_id}</c>.
/// </returns>
public static string Format(string customerId, string keywordPlanCampaignKeywordId) =>
FormatCustomerKeywordPlanCampaignKeyword(customerId, keywordPlanCampaignKeywordId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="KeywordPlanCampaignKeywordName"/> with
/// pattern <c>customers/{customer_id}/keywordPlanCampaignKeywords/{keyword_plan_campaign_keyword_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="keywordPlanCampaignKeywordId">
/// The <c>KeywordPlanCampaignKeyword</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="KeywordPlanCampaignKeywordName"/> with pattern
/// <c>customers/{customer_id}/keywordPlanCampaignKeywords/{keyword_plan_campaign_keyword_id}</c>.
/// </returns>
public static string FormatCustomerKeywordPlanCampaignKeyword(string customerId, string keywordPlanCampaignKeywordId) =>
s_customerKeywordPlanCampaignKeyword.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(keywordPlanCampaignKeywordId, nameof(keywordPlanCampaignKeywordId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="KeywordPlanCampaignKeywordName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/keywordPlanCampaignKeywords/{keyword_plan_campaign_keyword_id}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="keywordPlanCampaignKeywordName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <returns>The parsed <see cref="KeywordPlanCampaignKeywordName"/> if successful.</returns>
public static KeywordPlanCampaignKeywordName Parse(string keywordPlanCampaignKeywordName) =>
Parse(keywordPlanCampaignKeywordName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="KeywordPlanCampaignKeywordName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/keywordPlanCampaignKeywords/{keyword_plan_campaign_keyword_id}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="keywordPlanCampaignKeywordName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="KeywordPlanCampaignKeywordName"/> if successful.</returns>
public static KeywordPlanCampaignKeywordName Parse(string keywordPlanCampaignKeywordName, bool allowUnparsed) =>
TryParse(keywordPlanCampaignKeywordName, allowUnparsed, out KeywordPlanCampaignKeywordName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="KeywordPlanCampaignKeywordName"/>
/// instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/keywordPlanCampaignKeywords/{keyword_plan_campaign_keyword_id}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="keywordPlanCampaignKeywordName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="KeywordPlanCampaignKeywordName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string keywordPlanCampaignKeywordName, out KeywordPlanCampaignKeywordName result) =>
TryParse(keywordPlanCampaignKeywordName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="KeywordPlanCampaignKeywordName"/>
/// instance; optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/keywordPlanCampaignKeywords/{keyword_plan_campaign_keyword_id}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="keywordPlanCampaignKeywordName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="KeywordPlanCampaignKeywordName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string keywordPlanCampaignKeywordName, bool allowUnparsed, out KeywordPlanCampaignKeywordName result)
{
gax::GaxPreconditions.CheckNotNull(keywordPlanCampaignKeywordName, nameof(keywordPlanCampaignKeywordName));
gax::TemplatedResourceName resourceName;
if (s_customerKeywordPlanCampaignKeyword.TryParseName(keywordPlanCampaignKeywordName, out resourceName))
{
result = FromCustomerKeywordPlanCampaignKeyword(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(keywordPlanCampaignKeywordName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private KeywordPlanCampaignKeywordName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string keywordPlanCampaignKeywordId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomerId = customerId;
KeywordPlanCampaignKeywordId = keywordPlanCampaignKeywordId;
}
/// <summary>
/// Constructs a new instance of a <see cref="KeywordPlanCampaignKeywordName"/> class from the component parts
/// of pattern <c>customers/{customer_id}/keywordPlanCampaignKeywords/{keyword_plan_campaign_keyword_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="keywordPlanCampaignKeywordId">
/// The <c>KeywordPlanCampaignKeyword</c> ID. Must not be <c>null</c> or empty.
/// </param>
public KeywordPlanCampaignKeywordName(string customerId, string keywordPlanCampaignKeywordId) : this(ResourceNameType.CustomerKeywordPlanCampaignKeyword, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), keywordPlanCampaignKeywordId: gax::GaxPreconditions.CheckNotNullOrEmpty(keywordPlanCampaignKeywordId, nameof(keywordPlanCampaignKeywordId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>KeywordPlanCampaignKeyword</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed
/// resource name.
/// </summary>
public string KeywordPlanCampaignKeywordId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerKeywordPlanCampaignKeyword: return s_customerKeywordPlanCampaignKeyword.Expand(CustomerId, KeywordPlanCampaignKeywordId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as KeywordPlanCampaignKeywordName);
/// <inheritdoc/>
public bool Equals(KeywordPlanCampaignKeywordName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(KeywordPlanCampaignKeywordName a, KeywordPlanCampaignKeywordName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(KeywordPlanCampaignKeywordName a, KeywordPlanCampaignKeywordName b) => !(a == b);
}
public partial class KeywordPlanCampaignKeyword
{
/// <summary>
/// <see cref="KeywordPlanCampaignKeywordName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
internal KeywordPlanCampaignKeywordName ResourceNameAsKeywordPlanCampaignKeywordName
{
get => string.IsNullOrEmpty(ResourceName) ? null : KeywordPlanCampaignKeywordName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="KeywordPlanCampaignName"/>-typed view over the <see cref="KeywordPlanCampaign"/> resource name
/// property.
/// </summary>
internal KeywordPlanCampaignName KeywordPlanCampaignAsKeywordPlanCampaignName
{
get => string.IsNullOrEmpty(KeywordPlanCampaign) ? null : KeywordPlanCampaignName.Parse(KeywordPlanCampaign, allowUnparsed: true);
set => KeywordPlanCampaign = value?.ToString() ?? "";
}
}
}
| |
// 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.Batch.Protocol.Models
{
using System.Linq;
/// <summary>
/// Specifies details of a Job Manager task.
/// </summary>
public partial class JobManagerTask
{
/// <summary>
/// Initializes a new instance of the JobManagerTask class.
/// </summary>
public JobManagerTask() { }
/// <summary>
/// Initializes a new instance of the JobManagerTask class.
/// </summary>
/// <param name="id">A string that uniquely identifies the Job Manager
/// taskwithin the job.</param>
/// <param name="commandLine">The command line of the Job Manager
/// task.</param>
/// <param name="displayName">The display name of the Job Manager
/// task.</param>
/// <param name="resourceFiles">A list of files that the Batch service
/// will download to the compute node before running the command
/// line.</param>
/// <param name="environmentSettings">A list of environment variable
/// settings for the Job Manager task.</param>
/// <param name="constraints">Constraints that apply to the Job Manager
/// task.</param>
/// <param name="killJobOnCompletion">Whether completion of the Job
/// Manager task signifies completion of the entire job.</param>
/// <param name="userIdentity">The user identity under which the Job
/// Manager task runs.</param>
/// <param name="runExclusive">Whether the Job Manager task requires
/// exclusive use of the compute node where it runs.</param>
/// <param name="applicationPackageReferences">A list of application
/// packages that the Batch service will deploy to the compute node
/// before running the command line.</param>
/// <param name="authenticationTokenSettings">The settings for an
/// authentication token that the task can use to perform Batch service
/// operations.</param>
public JobManagerTask(string id, string commandLine, string displayName = default(string), System.Collections.Generic.IList<ResourceFile> resourceFiles = default(System.Collections.Generic.IList<ResourceFile>), System.Collections.Generic.IList<EnvironmentSetting> environmentSettings = default(System.Collections.Generic.IList<EnvironmentSetting>), TaskConstraints constraints = default(TaskConstraints), bool? killJobOnCompletion = default(bool?), UserIdentity userIdentity = default(UserIdentity), bool? runExclusive = default(bool?), System.Collections.Generic.IList<ApplicationPackageReference> applicationPackageReferences = default(System.Collections.Generic.IList<ApplicationPackageReference>), AuthenticationTokenSettings authenticationTokenSettings = default(AuthenticationTokenSettings))
{
Id = id;
DisplayName = displayName;
CommandLine = commandLine;
ResourceFiles = resourceFiles;
EnvironmentSettings = environmentSettings;
Constraints = constraints;
KillJobOnCompletion = killJobOnCompletion;
UserIdentity = userIdentity;
RunExclusive = runExclusive;
ApplicationPackageReferences = applicationPackageReferences;
AuthenticationTokenSettings = authenticationTokenSettings;
}
/// <summary>
/// Gets or sets a string that uniquely identifies the Job Manager
/// taskwithin the job.
/// </summary>
/// <remarks>
/// The id can contain any combination of alphanumeric characters
/// including hyphens and underscores and cannot contain more than 64
/// characters.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "id")]
public string Id { get; set; }
/// <summary>
/// Gets or sets the display name of the Job Manager task.
/// </summary>
/// <remarks>
/// It need not be unique and can contain any Unicode characters up to
/// a maximum length of 1024.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "displayName")]
public string DisplayName { get; set; }
/// <summary>
/// Gets or sets the command line of the Job Manager task.
/// </summary>
/// <remarks>
/// The command line does not run under a shell, and therefore cannot
/// take advantage of shell features such as environment variable
/// expansion. If you want to take advantage of such features, you
/// should invoke the shell in the command line, for example using "cmd
/// /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "commandLine")]
public string CommandLine { get; set; }
/// <summary>
/// Gets or sets a list of files that the Batch service will download
/// to the compute node before running the command line.
/// </summary>
/// <remarks>
/// Files listed under this element are located in the task's working
/// directory.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "resourceFiles")]
public System.Collections.Generic.IList<ResourceFile> ResourceFiles { get; set; }
/// <summary>
/// Gets or sets a list of environment variable settings for the Job
/// Manager task.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "environmentSettings")]
public System.Collections.Generic.IList<EnvironmentSetting> EnvironmentSettings { get; set; }
/// <summary>
/// Gets or sets constraints that apply to the Job Manager task.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "constraints")]
public TaskConstraints Constraints { get; set; }
/// <summary>
/// Gets or sets whether completion of the Job Manager task signifies
/// completion of the entire job.
/// </summary>
/// <remarks>
/// If true, when the Job Manager task completes, the Batch service
/// marks the job as complete. If any tasks are still running at this
/// time (other than Job Release), those tasks are terminated. If
/// false, the completion of the Job Manager task does not affect the
/// job status. In this case, you should either use the
/// onAllTasksComplete attribute to terminate the job, or have a client
/// or user terminate the job explicitly. An example of this is if the
/// Job Manager creates a set of tasks but then takes no further role
/// in their execution. The default value is true. If you are using the
/// onAllTasksComplete and onTaskFailure attributes to control job
/// lifetime, and using the Job Manager task only to create the tasks
/// for the job (not to monitor progress), then it is important to set
/// killJobOnCompletion to false.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "killJobOnCompletion")]
public bool? KillJobOnCompletion { get; set; }
/// <summary>
/// Gets or sets the user identity under which the Job Manager task
/// runs.
/// </summary>
/// <remarks>
/// If omitted, the task runs as a non-administrative user unique to
/// the task.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "userIdentity")]
public UserIdentity UserIdentity { get; set; }
/// <summary>
/// Gets or sets whether the Job Manager task requires exclusive use of
/// the compute node where it runs.
/// </summary>
/// <remarks>
/// If true, no other tasks will run on the same compute node for as
/// long as the Job Manager is running. If false, other tasks can run
/// simultaneously with the Job Manager on a compute node. The Job
/// Manager task counts normally against the node's concurrent task
/// limit, so this is only relevant if the node allows multiple
/// concurrent tasks. The default value is true.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "runExclusive")]
public bool? RunExclusive { get; set; }
/// <summary>
/// Gets or sets a list of application packages that the Batch service
/// will deploy to the compute node before running the command line.
/// </summary>
/// <remarks>
/// Application packages are downloaded and deployed to a shared
/// directory, not the task directory. Therefore, if a referenced
/// package is already on the compute node, and is up to date, then it
/// is not re-downloaded; the existing copy on the compute node is
/// used. If a referenced application package cannot be installed, for
/// example because the package has been deleted or because download
/// failed, the task fails with a scheduling error. This property is
/// currently not supported on jobs running on pools created using the
/// virtualMachineConfiguration (IaaS) property. If a task specifying
/// applicationPackageReferences runs on such a pool, it fails with a
/// scheduling error with code TaskSchedulingConstraintFailed.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "applicationPackageReferences")]
public System.Collections.Generic.IList<ApplicationPackageReference> ApplicationPackageReferences { get; set; }
/// <summary>
/// Gets or sets the settings for an authentication token that the task
/// can use to perform Batch service operations.
/// </summary>
/// <remarks>
/// If this property is set, the Batch service provides the task with
/// an authentication token which can be used to authenticate Batch
/// service operations without requiring an account access key. The
/// token is provided via the AZ_BATCH_AUTHENTICATION_TOKEN environment
/// variable. The operations that the task can carry out using the
/// token depend on the settings. For example, a task can request job
/// permissions in order to add other tasks to the job, or check the
/// status of the job or of other tasks under the job.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "authenticationTokenSettings")]
public AuthenticationTokenSettings AuthenticationTokenSettings { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Id == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "Id");
}
if (CommandLine == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "CommandLine");
}
if (this.ResourceFiles != null)
{
foreach (var element in this.ResourceFiles)
{
if (element != null)
{
element.Validate();
}
}
}
if (this.EnvironmentSettings != null)
{
foreach (var element1 in this.EnvironmentSettings)
{
if (element1 != null)
{
element1.Validate();
}
}
}
if (this.ApplicationPackageReferences != null)
{
foreach (var element2 in this.ApplicationPackageReferences)
{
if (element2 != null)
{
element2.Validate();
}
}
}
}
}
}
| |
// 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.AcceptanceTestsBodyComplex
{
using System.Threading.Tasks;
using Models;
/// <summary>
/// Extension methods for Polymorphism.
/// </summary>
public static partial class PolymorphismExtensions
{
/// <summary>
/// Get complex types that are polymorphic
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Fish GetValid(this IPolymorphism operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPolymorphism)s).GetValidAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types that are polymorphic
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<Fish> GetValidAsync(this IPolymorphism operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetValidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put complex types that are polymorphic
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put a salmon that looks like this:
/// {
/// 'fishtype':'Salmon',
/// 'location':'alaska',
/// 'iswild':true,
/// 'species':'king',
/// 'length':1.0,
/// 'siblings':[
/// {
/// 'fishtype':'Shark',
/// 'age':6,
/// 'birthday': '2012-01-05T01:00:00Z',
/// 'length':20.0,
/// 'species':'predator',
/// },
/// {
/// 'fishtype':'Sawshark',
/// 'age':105,
/// 'birthday': '1900-01-05T01:00:00Z',
/// 'length':10.0,
/// 'picture': new Buffer([255, 255, 255, 255,
/// 254]).toString('base64'),
/// 'species':'dangerous',
/// },
/// {
/// 'fishtype': 'goblin',
/// 'age': 1,
/// 'birthday': '2015-08-08T00:00:00Z',
/// 'length': 30.0,
/// 'species': 'scary',
/// 'jawsize': 5
/// }
/// ]
/// };
/// </param>
public static void PutValid(this IPolymorphism operations, Fish complexBody)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IPolymorphism)s).PutValidAsync(complexBody), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types that are polymorphic
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put a salmon that looks like this:
/// {
/// 'fishtype':'Salmon',
/// 'location':'alaska',
/// 'iswild':true,
/// 'species':'king',
/// 'length':1.0,
/// 'siblings':[
/// {
/// 'fishtype':'Shark',
/// 'age':6,
/// 'birthday': '2012-01-05T01:00:00Z',
/// 'length':20.0,
/// 'species':'predator',
/// },
/// {
/// 'fishtype':'Sawshark',
/// 'age':105,
/// 'birthday': '1900-01-05T01:00:00Z',
/// 'length':10.0,
/// 'picture': new Buffer([255, 255, 255, 255,
/// 254]).toString('base64'),
/// 'species':'dangerous',
/// },
/// {
/// 'fishtype': 'goblin',
/// 'age': 1,
/// 'birthday': '2015-08-08T00:00:00Z',
/// 'length': 30.0,
/// 'species': 'scary',
/// 'jawsize': 5
/// }
/// ]
/// };
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task PutValidAsync(this IPolymorphism operations, Fish complexBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.PutValidWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Put complex types that are polymorphic, attempting to omit required
/// 'birthday' field - the request should not be allowed from the client
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please attempt put a sawshark that looks like this, the client should not
/// allow this data to be sent:
/// {
/// "fishtype": "sawshark",
/// "species": "snaggle toothed",
/// "length": 18.5,
/// "age": 2,
/// "birthday": "2013-06-01T01:00:00Z",
/// "location": "alaska",
/// "picture": base64(FF FF FF FF FE),
/// "siblings": [
/// {
/// "fishtype": "shark",
/// "species": "predator",
/// "birthday": "2012-01-05T01:00:00Z",
/// "length": 20,
/// "age": 6
/// },
/// {
/// "fishtype": "sawshark",
/// "species": "dangerous",
/// "picture": base64(FF FF FF FF FE),
/// "length": 10,
/// "age": 105
/// }
/// ]
/// }
/// </param>
public static void PutValidMissingRequired(this IPolymorphism operations, Fish complexBody)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IPolymorphism)s).PutValidMissingRequiredAsync(complexBody), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types that are polymorphic, attempting to omit required
/// 'birthday' field - the request should not be allowed from the client
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please attempt put a sawshark that looks like this, the client should not
/// allow this data to be sent:
/// {
/// "fishtype": "sawshark",
/// "species": "snaggle toothed",
/// "length": 18.5,
/// "age": 2,
/// "birthday": "2013-06-01T01:00:00Z",
/// "location": "alaska",
/// "picture": base64(FF FF FF FF FE),
/// "siblings": [
/// {
/// "fishtype": "shark",
/// "species": "predator",
/// "birthday": "2012-01-05T01:00:00Z",
/// "length": 20,
/// "age": 6
/// },
/// {
/// "fishtype": "sawshark",
/// "species": "dangerous",
/// "picture": base64(FF FF FF FF FE),
/// "length": 10,
/// "age": 105
/// }
/// ]
/// }
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task PutValidMissingRequiredAsync(this IPolymorphism operations, Fish complexBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.PutValidMissingRequiredWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// ContainsSearchOperator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
namespace System.Linq.Parallel
{
/// <summary>
/// Contains is quite similar to the any/all operator above. Each partition searches a
/// subset of elements for a match, and the first one to find a match signals to the rest
/// of the partitions to stop searching.
/// </summary>
/// <typeparam name="TInput"></typeparam>
internal sealed class ContainsSearchOperator<TInput> : UnaryQueryOperator<TInput, bool>
{
private readonly TInput _searchValue; // The value for which we are searching.
private readonly IEqualityComparer<TInput> _comparer; // The comparer to use for equality tests.
//---------------------------------------------------------------------------------------
// Constructs a new instance of the contains search operator.
//
// Arguments:
// child - the child tree to enumerate.
// searchValue - value we are searching for.
// comparer - a comparison routine used to test equality.
//
internal ContainsSearchOperator(IEnumerable<TInput> child, TInput searchValue, IEqualityComparer<TInput> comparer)
: base(child)
{
Debug.Assert(child != null, "child data source cannot be null");
_searchValue = searchValue;
if (comparer == null)
{
_comparer = EqualityComparer<TInput>.Default;
}
else
{
_comparer = comparer;
}
}
//---------------------------------------------------------------------------------------
// Executes the entire query tree, and aggregates the individual partition results to
// form an overall answer to the search operation.
//
internal bool Aggregate()
{
// Because the final reduction is typically much cheaper than the intermediate
// reductions over the individual partitions, and because each parallel partition
// could do a lot of work to produce a single output element, we prefer to turn off
// pipelining, and process the final reductions serially.
using (IEnumerator<bool> enumerator = GetEnumerator(ParallelMergeOptions.FullyBuffered, true))
{
// Any value of true means the element was found. We needn't consult all partitions
while (enumerator.MoveNext())
{
if (enumerator.Current)
{
return true;
}
}
}
return false;
}
//---------------------------------------------------------------------------------------
// Just opens the current operator, including opening the child and wrapping it with
// partitions as needed.
//
internal override QueryResults<bool> Open(QuerySettings settings, bool preferStriping)
{
QueryResults<TInput> childQueryResults = Child.Open(settings, preferStriping);
return new UnaryQueryOperatorResults(childQueryResults, this, settings, preferStriping);
}
internal override void WrapPartitionedStream<TKey>(
PartitionedStream<TInput, TKey> inputStream, IPartitionedStreamRecipient<bool> recipient, bool preferStriping, QuerySettings settings)
{
int partitionCount = inputStream.PartitionCount;
PartitionedStream<bool, int> outputStream = new PartitionedStream<bool, int>(partitionCount, Util.GetDefaultComparer<int>(), OrdinalIndexState.Correct);
// Create a shared cancellation variable
Shared<bool> resultFoundFlag = new Shared<bool>(false);
for (int i = 0; i < partitionCount; i++)
{
outputStream[i] = new ContainsSearchOperatorEnumerator<TKey>(inputStream[i], _searchValue, _comparer, i, resultFoundFlag,
settings.CancellationState.MergedCancellationToken);
}
recipient.Receive(outputStream);
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
[ExcludeFromCodeCoverage]
internal override IEnumerable<bool> AsSequentialQuery(CancellationToken token)
{
Debug.Fail("This method should never be called as it is an ending operator with LimitsParallelism=false.");
throw new NotSupportedException();
}
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge that would not be performed in
// a similar sequential operation (i.e., in LINQ to Objects).
//
internal override bool LimitsParallelism
{
get { return false; }
}
//---------------------------------------------------------------------------------------
// This enumerator performs the search over its input data source. It also cancels peer
// enumerators when an answer was found, and polls this cancellation flag to stop when
// requested.
//
private class ContainsSearchOperatorEnumerator<TKey> : QueryOperatorEnumerator<bool, int>
{
private readonly QueryOperatorEnumerator<TInput, TKey> _source; // The source data.
private readonly TInput _searchValue; // The value for which we are searching.
private readonly IEqualityComparer<TInput> _comparer; // The comparer to use for equality tests.
private readonly int _partitionIndex; // This partition's unique index.
private readonly Shared<bool> _resultFoundFlag; // Whether to cancel the operation.
private readonly CancellationToken _cancellationToken;
//---------------------------------------------------------------------------------------
// Instantiates a new any/all search operator.
//
internal ContainsSearchOperatorEnumerator(QueryOperatorEnumerator<TInput, TKey> source, TInput searchValue,
IEqualityComparer<TInput> comparer, int partitionIndex, Shared<bool> resultFoundFlag,
CancellationToken cancellationToken)
{
Debug.Assert(source != null);
Debug.Assert(comparer != null);
Debug.Assert(resultFoundFlag != null);
_source = source;
_searchValue = searchValue;
_comparer = comparer;
_partitionIndex = partitionIndex;
_resultFoundFlag = resultFoundFlag;
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// This enumerates the entire input source to perform the search. If another peer
// partition finds an answer before us, we will voluntarily return (propagating the
// peer's result).
//
internal override bool MoveNext(ref bool currentElement, ref int currentKey)
{
Debug.Assert(_comparer != null);
// Avoid enumerating if we've already found an answer.
if (_resultFoundFlag.Value)
return false;
// We just scroll through the enumerator and accumulate the result.
TInput element = default(TInput);
TKey keyUnused = default(TKey);
if (_source.MoveNext(ref element, ref keyUnused))
{
currentElement = false;
currentKey = _partitionIndex;
// Continue walking the data so long as we haven't found an item that satisfies
// the condition we are searching for.
int i = 0;
do
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
if (_resultFoundFlag.Value)
{
// If cancellation occurred, it's because a successful answer was found.
return false;
}
if (_comparer.Equals(element, _searchValue))
{
// We have found an item that satisfies the search. Cancel other
// workers that are concurrently searching, and return.
_resultFoundFlag.Value = true;
currentElement = true;
break;
}
}
while (_source.MoveNext(ref element, ref keyUnused));
return true;
}
return false;
}
protected override void Dispose(bool disposing)
{
Debug.Assert(_source != null);
_source.Dispose();
}
}
}
}
| |
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Context
{
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Pipeline;
using Pipeline.Filters.Outbox;
using Util;
public class InMemoryOutboxConsumeContext :
ConsumeContextProxy,
OutboxContext
{
readonly TaskCompletionSource<InMemoryOutboxConsumeContext> _clearToSend;
readonly ConcurrentBag<Func<Task>> _pendingActions;
public InMemoryOutboxConsumeContext(ConsumeContext context)
: base(context)
{
_pendingActions = new ConcurrentBag<Func<Task>>();
_clearToSend = new TaskCompletionSource<InMemoryOutboxConsumeContext>();
}
public Task ClearToSend => _clearToSend.Task;
public void Add(Func<Task> method)
{
_pendingActions.Add(method);
}
public override async Task<ISendEndpoint> GetSendEndpoint(Uri address)
{
var endpoint = await base.GetSendEndpoint(address).ConfigureAwait(false);
return new OutboxSendEndpoint(this, endpoint);
}
public override Task Publish<T>(T message, CancellationToken cancellationToken)
{
Add(() => base.Publish(message, cancellationToken));
return TaskUtil.Completed;
}
public override Task Publish<T>(T message, IPipe<PublishContext<T>> publishPipe, CancellationToken cancellationToken)
{
Add(() => base.Publish(message, publishPipe, cancellationToken));
return TaskUtil.Completed;
}
public override Task Publish<T>(T message, IPipe<PublishContext> publishPipe, CancellationToken cancellationToken)
{
Add(() => base.Publish(message, publishPipe, cancellationToken));
return TaskUtil.Completed;
}
public override Task Publish(object message, CancellationToken cancellationToken)
{
Add(() => base.Publish(message, cancellationToken));
return TaskUtil.Completed;
}
public override Task Publish(object message, IPipe<PublishContext> publishPipe, CancellationToken cancellationToken)
{
Add(() => base.Publish(message, publishPipe, cancellationToken));
return TaskUtil.Completed;
}
public override Task Publish(object message, Type messageType, CancellationToken cancellationToken)
{
Add(() => base.Publish(message, messageType, cancellationToken));
return TaskUtil.Completed;
}
public override Task Publish(object message, Type messageType, IPipe<PublishContext> publishPipe, CancellationToken cancellationToken)
{
Add(() => base.Publish(message, messageType, publishPipe, cancellationToken));
return TaskUtil.Completed;
}
public override Task Publish<T>(object values, CancellationToken cancellationToken)
{
Add(() => base.Publish<T>(values, cancellationToken));
return TaskUtil.Completed;
}
public override Task Publish<T>(object values, IPipe<PublishContext<T>> publishPipe, CancellationToken cancellationToken)
{
Add(() => base.Publish(values, publishPipe, cancellationToken));
return TaskUtil.Completed;
}
public override Task Publish<T>(object values, IPipe<PublishContext> publishPipe, CancellationToken cancellationToken)
{
Add(() => base.Publish<T>(values, publishPipe, cancellationToken));
return TaskUtil.Completed;
}
public override Task RespondAsync<T>(T message)
{
Add(() => base.RespondAsync(message));
return TaskUtil.Completed;
}
public override Task RespondAsync(object message, Type messageType, IPipe<SendContext> sendPipe)
{
Add(() => base.RespondAsync(message, messageType, sendPipe));
return TaskUtil.Completed;
}
public override Task RespondAsync<T>(object values)
{
Add(() => base.RespondAsync<T>(values));
return TaskUtil.Completed;
}
public override Task RespondAsync<T>(object values, IPipe<SendContext<T>> sendPipe)
{
Add(() => base.RespondAsync(values, sendPipe));
return TaskUtil.Completed;
}
public override Task RespondAsync<T>(object values, IPipe<SendContext> sendPipe)
{
Add(() => base.RespondAsync<T>(values, sendPipe));
return TaskUtil.Completed;
}
public override Task RespondAsync<T>(T message, IPipe<SendContext<T>> sendPipe)
{
Add(() => base.RespondAsync(message, sendPipe));
return TaskUtil.Completed;
}
public override Task RespondAsync<T>(T message, IPipe<SendContext> sendPipe)
{
Add(() => base.RespondAsync(message, sendPipe));
return TaskUtil.Completed;
}
public override Task RespondAsync(object message)
{
Add(() => base.RespondAsync(message));
return TaskUtil.Completed;
}
public override Task RespondAsync(object message, Type messageType)
{
Add(() => base.RespondAsync(message, messageType));
return TaskUtil.Completed;
}
public override Task RespondAsync(object message, IPipe<SendContext> sendPipe)
{
Add(() => base.RespondAsync(message, sendPipe));
return TaskUtil.Completed;
}
public override void Respond<T>(T message)
{
Add(() =>
{
base.Respond(message);
return TaskUtil.Completed;
});
}
public async Task ExecutePendingActions()
{
_clearToSend.TrySetResult(this);
await Task.WhenAll(_pendingActions.Select(x => x())).ConfigureAwait(false);
}
public Task DiscardPendingActions()
{
return TaskUtil.Completed;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
namespace SIL.Xml
{
/// <summary>
/// Summary description for XmlUtils.
/// </summary>
public static class XmlUtils
{
/// <summary>
/// Returns true if value of attrName is 'true' or 'yes' (case ignored)
/// </summary>
/// <param name="node">The XmlNode to look in.</param>
/// <param name="attrName">The optional attribute to find.</param>
/// <returns></returns>
public static bool GetBooleanAttributeValue(XmlNode node, string attrName)
{
return GetBooleanAttributeValue(GetOptionalAttributeValue(node, attrName));
}
/// <summary>
/// Given bytes that represent an xml element, return the values of requested attributes (if they exist).
/// </summary>
/// <param name="data">Data that is expected to an xml element.</param>
/// <param name="attributes">A set of attributes, the values of which are to be returned.</param>
/// <returns>A dictionary </returns>
public static Dictionary<string, string> GetAttributes(byte[] data, HashSet<string> attributes)
{
var results = new Dictionary<string, string>(attributes.Count);
using (var reader = XmlReader.Create(new MemoryStream(data), CanonicalXmlSettings.CreateXmlReaderSettings(ConformanceLevel.Fragment)))
{
reader.MoveToContent();
foreach (var attr in attributes)
{
results.Add(attr, null);
if (reader.MoveToAttribute(attr))
{
results[attr] = reader.Value;
}
}
}
return results;
}
/// <summary>
/// Given a string that represents an xml element, return the values of requested attributes (if they exist).
/// </summary>
/// <param name="data">Data that is expected to an xml element.</param>
/// <param name="attributes">A set of attributes, the values of which are to be returned.</param>
/// <returns>A dictionary </returns>
public static Dictionary<string, string> GetAttributes(string data, HashSet<string> attributes)
{
var results = new Dictionary<string, string>(attributes.Count);
using (var reader = XmlReader.Create(new StringReader(data), CanonicalXmlSettings.CreateXmlReaderSettings(ConformanceLevel.Fragment)))
{
reader.MoveToContent();
foreach (var attr in attributes)
{
results.Add(attr, null);
if (reader.MoveToAttribute(attr))
{
results[attr] = reader.Value;
}
}
}
return results;
}
/// <summary>
/// Returns true if value of attrName is 'true' or 'yes' (case ignored)
/// </summary>
/// <param name="node">The XmlNode to look in.</param>
/// <param name="attrName">The optional attribute to find.</param>
/// <returns></returns>
public static bool GetBooleanAttributeValue(XPathNavigator node, string attrName)
{
return GetBooleanAttributeValue(GetOptionalAttributeValue(node, attrName));
}
/// <summary>
/// Returns true if sValue is 'true' or 'yes' (case ignored)
/// </summary>
public static bool GetBooleanAttributeValue(string sValue)
{
return (sValue != null &&
(sValue.ToLower().Equals("true") || sValue.ToLower().Equals("yes")));
}
/// <summary>
/// Returns a integer obtained from the (mandatory) attribute named.
/// </summary>
/// <param name="node">The XmlNode to look in.</param>
/// <param name="attrName">The mandatory attribute to find.</param>
/// <returns>The value, or 0 if attr is missing.</returns>
public static int GetMandatoryIntegerAttributeValue(XmlNode node, string attrName)
{
return Int32.Parse(GetManditoryAttributeValue(node, attrName));
}
/// <summary>
/// Return an optional integer attribute value, or if not found, the default value.
/// </summary>
/// <param name="node"></param>
/// <param name="attrName"></param>
/// <param name="defaultVal"></param>
/// <returns></returns>
public static int GetOptionalIntegerValue(XmlNode node, string attrName, int defaultVal)
{
string val = GetOptionalAttributeValue(node, attrName);
if (val == null)
{
return defaultVal;
}
return Int32.Parse(val);
}
/// <summary>
/// Retrieve an array, given an attribute consisting of a comma-separated list of integers
/// </summary>
/// <param name="node"></param>
/// <param name="attrName"></param>
/// <returns></returns>
public static int[] GetMandatoryIntegerListAttributeValue(XmlNode node, string attrName)
{
string input = GetManditoryAttributeValue(node, attrName);
string[] vals = input.Split(',');
int[] result = new int[vals.Length];
for (int i = 0;i < vals.Length;i++)
{
result[i] = Int32.Parse(vals[i]);
}
return result;
}
/// <summary>
/// Make a value suitable for GetMandatoryIntegerListAttributeValue to parse.
/// </summary>
/// <param name="vals"></param>
/// <returns></returns>
public static string MakeIntegerListValue(int[] vals)
{
StringBuilder builder = new StringBuilder(vals.Length * 7);
// enough unless VERY big numbers
for (int i = 0;i < vals.Length;i++)
{
if (i != 0)
{
builder.Append(",");
}
builder.Append(vals[i].ToString());
}
return builder.ToString();
}
/// <summary>
/// Make a comma-separated list of the ToStrings of the values in the list.
/// </summary>
/// <param name="vals"></param>
/// <returns></returns>
public static string MakeListValue(List<int> vals)
{
StringBuilder builder = new StringBuilder(vals.Count * 7);
// enough unless VERY big numbers
for (int i = 0;i < vals.Count;i++)
{
if (i != 0)
{
builder.Append(",");
}
builder.Append(vals[i].ToString());
}
return builder.ToString();
}
/// <summary>
/// Get an optional attribute value from an XmlNode.
/// </summary>
/// <param name="node">The XmlNode to look in.</param>
/// <param name="attrName">The attribute to find.</param>
/// <param name="defaultValue"></param>
/// <returns>The value of the attribute, or the default value, if the attribute dismissing</returns>
public static bool GetOptionalBooleanAttributeValue(XmlNode node,
string attrName,
bool defaultValue)
{
return
GetBooleanAttributeValue(GetOptionalAttributeValue(node,
attrName,
defaultValue
? "true"
: "false"));
}
/// <summary>
/// Deprecated: use GetOptionalAttributeValue instead.
/// </summary>
/// <param name="node"></param>
/// <param name="attrName"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static string GetAttributeValue(XmlNode node, string attrName, string defaultValue)
{
return GetOptionalAttributeValue(node, attrName, defaultValue);
}
/// <summary>
/// Get an optional attribute value from an XmlNode.
/// </summary>
/// <param name="node">The XmlNode to look in.</param>
/// <param name="attrName">The attribute to find.</param>
/// <returns>The value of the attribute, or null, if not found.</returns>
public static string GetAttributeValue(XmlNode node, string attrName)
{
return GetOptionalAttributeValue(node, attrName);
}
/// <summary>
/// Get an optional attribute value from an XmlNode.
/// </summary>
/// <param name="node">The XmlNode to look in.</param>
/// <param name="attrName">The attribute to find.</param>
/// <returns>The value of the attribute, or null, if not found.</returns>
public static string GetOptionalAttributeValue(XmlNode node, string attrName)
{
return GetOptionalAttributeValue(node, attrName, null);
}
/// <summary>
/// Get an optional attribute value from an XmlNode.
/// </summary>
/// <param name="node">The XmlNode to look in.</param>
/// <param name="attrName">The attribute to find.</param>
/// <returns>The value of the attribute, or null, if not found.</returns>
public static string GetOptionalAttributeValue(XPathNavigator node, string attrName)
{
return GetOptionalAttributeValue(node, attrName, null);
}
/// <summary>
/// Get an optional attribute value from an XmlNode.
/// </summary>
/// <param name="node">The XmlNode to look in.</param>
/// <param name="attrName">The attribute to find.</param>
/// <returns>The value of the attribute, or null, if not found.</returns>
/// <param name="defaultString"></param>
public static string GetOptionalAttributeValue(XmlNode node,
string attrName,
string defaultString)
{
if (node != null && node.Attributes != null)
{
XmlAttribute xa = node.Attributes[attrName];
if (xa != null)
{
return xa.Value;
}
}
return defaultString;
}
/// <summary>
/// Get an optional attribute value from an XmlNode.
/// </summary>
/// <param name="node">The XmlNode to look in.</param>
/// <param name="attrName">The attribute to find.</param>
/// <returns>The value of the attribute, or null, if not found.</returns>
/// <param name="defaultString"></param>
public static string GetOptionalAttributeValue(XPathNavigator node,
string attrName,
string defaultString)
{
if (node != null && node.HasAttributes)
{
string s = node.GetAttribute(attrName, string.Empty);
if (!string.IsNullOrEmpty(s))
{
return s;
}
}
return defaultString;
}
/// <summary>
/// Return the node that has the desired 'name', either the input node or a decendent.
/// </summary>
/// <param name="node">The XmlNode to look in.</param>
/// <param name="name">The XmlNode name to find.</param>
/// <returns></returns>
public static XmlNode FindNode(XmlNode node, string name)
{
if (node.Name == name)
{
return node;
}
foreach (XmlNode childNode in node.ChildNodes)
{
if (childNode.Name == name)
{
return childNode;
}
XmlNode n = FindNode(childNode, name);
if (n != null)
{
return n;
}
}
return null;
}
/// <summary>
/// Get an obligatory attribute value.
/// </summary>
/// <param name="node">The XmlNode to look in.</param>
/// <param name="attrName">The required attribute to find.</param>
/// <returns>The value of the attribute.</returns>
/// <exception cref="ApplicationException">
/// Thrown when the value is not found in the node.
/// </exception>
public static string GetManditoryAttributeValue(XmlNode node, string attrName)
{
string retval = GetOptionalAttributeValue(node, attrName, null);
if (retval == null)
{
throw new ApplicationException("The attribute'" + attrName +
"' is mandatory, but was missing. " + node.OuterXml);
}
return retval;
}
public static string GetManditoryAttributeValue(XPathNavigator node, string attrName)
{
string retval = GetOptionalAttributeValue(node, attrName, null);
if (retval == null)
{
throw new ApplicationException("The attribute'" + attrName +
"' is mandatory, but was missing. " + node.OuterXml);
}
return retval;
}
/// <summary>
/// Append an attribute with the specified name and value to parent.
/// </summary>
/// <param name="parent"></param>
/// <param name="attrName"></param>
/// <param name="attrVal"></param>
public static void AppendAttribute(XmlNode parent, string attrName, string attrVal)
{
XmlAttribute xa = parent.OwnerDocument.CreateAttribute(attrName);
xa.Value = attrVal;
parent.Attributes.Append(xa);
}
/// <summary>
/// Return true if the two nodes match. Corresponding children should match, and
/// corresponding attributes (though not necessarily in the same order).
/// The nodes are expected to be actually XmlElements; not tested for other cases.
/// Comments do not affect equality.
/// </summary>
/// <param name="node1"></param>
/// <param name="node2"></param>
/// <returns></returns>
public static bool NodesMatch(XmlNode node1, XmlNode node2)
{
if (node1 == null && node2 == null)
{
return true;
}
if (node1 == null || node2 == null)
{
return false;
}
if (node1.Name != node2.Name)
{
return false;
}
if (node1.InnerText != node2.InnerText)
{
return false;
}
if (node1.Attributes == null && node2.Attributes != null)
{
return false;
}
if (node1.Attributes != null && node2.Attributes == null)
{
return false;
}
if (node1.Attributes != null)
{
if (node1.Attributes.Count != node2.Attributes.Count)
{
return false;
}
for (int i = 0;i < node1.Attributes.Count;i++)
{
XmlAttribute xa1 = node1.Attributes[i];
XmlAttribute xa2 = node2.Attributes[xa1.Name];
if (xa2 == null || xa1.Value != xa2.Value)
{
return false;
}
}
}
if (node1.ChildNodes == null && node2.ChildNodes != null)
{
return false;
}
if (node1.ChildNodes != null && node2.ChildNodes == null)
{
return false;
}
if (node1.ChildNodes != null)
{
int ichild1 = 0; // index node1.ChildNodes
int ichild2 = 0; // index node2.ChildNodes
while (ichild1 < node1.ChildNodes.Count && ichild2 < node1.ChildNodes.Count)
{
XmlNode child1 = node1.ChildNodes[ichild1];
// Note that we must defer doing the 'continue' until after we have checked to see if both children are comments
// If we continue immediately and the last node of both elements is a comment, the second node will not have
// ichild2 incremented and the final test will fail.
bool foundComment = false;
if (child1 is XmlComment)
{
ichild1++;
foundComment = true;
}
XmlNode child2 = node2.ChildNodes[ichild2];
if (child2 is XmlComment)
{
ichild2++;
foundComment = true;
}
if (foundComment)
{
continue;
}
if (!NodesMatch(child1, child2))
{
return false;
}
ichild1++;
ichild2++;
}
// If we finished both lists we got a match.
return ichild1 == node1.ChildNodes.Count && ichild2 == node2.ChildNodes.Count;
}
else
{
// both lists are null
return true;
}
}
/// <summary>
/// Return the first child of the node that is not a comment (or null).
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
public static XmlNode GetFirstNonCommentChild(XmlNode node)
{
if (node == null)
{
return null;
}
foreach (XmlNode child in node.ChildNodes)
{
if (!(child is XmlComment))
{
return child;
}
}
return null;
}
/// <summary>
/// Fix the string to be safe in a text region of XML.
/// </summary>
/// <param name="sInput"></param>
/// <returns></returns>
public static string MakeSafeXml(string sInput)
{
string sOutput = sInput;
if (!string.IsNullOrEmpty(sOutput))
{
sOutput = sOutput.Replace("&", "&");
sOutput = sOutput.Replace("<", "<");
sOutput = sOutput.Replace(">", ">");
}
return sOutput;
}
/// <summary>
/// Fix the string to be safe in an attribute value of XML.
/// </summary>
/// <param name="sInput"></param>
/// <returns></returns>
public static string MakeSafeXmlAttribute(string sInput)
{
string sOutput = sInput;
if (sOutput != null && sOutput.Length != 0)
{
sOutput = sOutput.Replace("&", "&");
sOutput = sOutput.Replace("\"", """);
sOutput = sOutput.Replace("'", "'");
sOutput = sOutput.Replace("<", "<");
sOutput = sOutput.Replace(">", ">");
}
return sOutput;
}
/// <summary>
/// lifted from http://www.knowdotnet.com/articles/indentxml.html
/// </summary>
/// <param name="xml"></param>
/// <returns></returns>
public static string GetIndendentedXml(string xml)
{
string outXml = string.Empty;
using(MemoryStream ms = new MemoryStream())
// Create a XMLTextWriter that will send its output to a memory stream (file)
using (XmlTextWriter xtw = new XmlTextWriter(ms, Encoding.Unicode))
{
XmlDocument doc = new XmlDocument();
// try
// {
// Load the unformatted XML text string into an instance
// of the XML Document Object Model (DOM)
doc.LoadXml(xml);
// Set the formatting property of the XML Text Writer to indented
// the text writer is where the indenting will be performed
xtw.Formatting = Formatting.Indented;
// write dom xml to the xmltextwriter
doc.WriteContentTo(xtw);
// Flush the contents of the text writer
// to the memory stream, which is simply a memory file
xtw.Flush();
// set to start of the memory stream (file)
ms.Seek(0, SeekOrigin.Begin);
// create a reader to read the contents of
// the memory stream (file)
StreamReader sr = new StreamReader(ms);
// return the formatted string to caller
return sr.ReadToEnd();
// }
// catch (Exception ex)
// {
// return ex.Message;
// }
}
}
//todo: what's the diff between this one and the next?
static public XmlElement GetOrCreateElementPredicate(XmlDocument dom, XmlElement parent, string predicate, string name)
{
XmlElement element = (XmlElement)parent.SelectSingleNodeHonoringDefaultNS("/" + predicate);
if (element == null)
{
element = parent.OwnerDocument.CreateElement(name, parent.NamespaceURI);
parent.AppendChild(element);
}
return element;
}
static public XmlElement GetOrCreateElement(XmlDocument dom, string parentPath, string name)
{
XmlElement element = (XmlElement)dom.SelectSingleNodeHonoringDefaultNS(parentPath + "/" + name);
if (element == null)
{
XmlElement parent = (XmlElement)dom.SelectSingleNodeHonoringDefaultNS(parentPath);
if (parent == null)
return null;
element = parent.OwnerDocument.CreateElement(name, parent.NamespaceURI);
parent.AppendChild(element);
}
return element;
}
public static string GetStringAttribute(XmlNode form, string attr)
{
try
{
return form.Attributes[attr].Value;
}
catch (NullReferenceException)
{
throw new XmlFormatException(string.Format("Expected a {0} attribute on {1}.", attr, form.OuterXml));
}
}
public static string GetOptionalAttributeString(XmlNode xmlNode, string attributeName)
{
XmlAttribute attr = xmlNode.Attributes[attributeName];
if (attr == null)
return null;
return attr.Value;
}
public static XmlNode GetDocumentNodeFromRawXml(string outerXml, XmlNode nodeMaker)
{
if (string.IsNullOrEmpty(outerXml))
{
throw new ArgumentException();
}
XmlDocument doc = nodeMaker as XmlDocument;
if (doc == null)
{
doc = nodeMaker.OwnerDocument;
}
using (StringReader sr = new StringReader(outerXml))
{
using (XmlReader r = XmlReader.Create(sr))
{
r.Read();
return doc.ReadNode(r);
}
}
}
public static string GetXmlForShowingInHtml(string xml)
{
var s = XmlUtils.GetIndendentedXml(xml).Replace("<", "<");
s = s.Replace("\r\n", "<br/>");
s = s.Replace(" ", " ");
return s;
}
public static string GetTitleOfHtml(XmlDocument dom, string defaultIfMissing)
{
var title = dom.SelectSingleNode("//head/title");
if (title != null && !string.IsNullOrEmpty(title.InnerText) && !string.IsNullOrEmpty(title.InnerText.Trim()))
{
return title.InnerText.Trim();
}
return defaultIfMissing;
}
/// <summary>
/// Write a node out containing the XML in dataToWrite, pretty-printed according to the rules of writer, except
/// that we suppress indentation for children of nodes whose names are listed in suppressIndentingChildren,
/// and also for "mixed" nodes (where some children are text).
/// </summary>
/// <param name="writer"></param>
/// <param name="dataToWrite"></param>
/// <param name="suppressIndentingChildren"></param>
public static void WriteNode(XmlWriter writer, string dataToWrite, HashSet<string> suppressIndentingChildren)
{
XElement element = XDocument.Parse(dataToWrite).Root;
WriteNode(writer, element, suppressIndentingChildren);
}
/// <summary>
/// Write a node out containing the XML in dataToWrite, pretty-printed according to the rules of writer, except
/// that we suppress indentation for children of nodes whose names are listed in suppressIndentingChildren,
/// and also for "mixed" nodes (where some children are text).
/// </summary>
/// <param name="writer"></param>
/// <param name="dataToWrite"></param>
/// <param name="suppressIndentingChildren"></param>
public static void WriteNode(XmlWriter writer, XElement dataToWrite, HashSet<string> suppressIndentingChildren)
{
if (dataToWrite == null)
return;
WriteElementTo(writer, dataToWrite, suppressIndentingChildren);
}
/// <summary>
/// Recursively write an element to the writer, suppressing indentation of children when required.
/// </summary>
/// <param name="writer"></param>
/// <param name="element"></param>
/// <param name="suppressIndentingChildren"></param>
private static void WriteElementTo(XmlWriter writer, XElement element, HashSet<string> suppressIndentingChildren)
{
writer.WriteStartElement(element.Name.LocalName);
foreach (var attr in element.Attributes())
writer.WriteAttributeString(attr.Name.LocalName, attr.Value);
// The writer automatically suppresses indenting children for any element that it detects has text children.
// However, it won't do this for the first child if that is an element, even if it later encounters text children.
// Also, there may be a parent where text including white space is significant, yet it is possible for the
// WHOLE content to be an element. For example, a <text> or <AStr> element may consist entirely of a <span>.
// In such cases there is NO way to tell from the content that it should not be indented, so all we can do
// is pass a list of such elements.
bool suppressIndenting = suppressIndentingChildren.Contains(element.Name.LocalName) || element.Nodes().Any(x => x is XText);
// In either case, we implement the suppression by making the first child a fake text element.
// Calling this method, even with an empty string, has proved to be enough to make the writer treat the parent
// as "mixed" which prevents indenting its children.
if (suppressIndenting)
writer.WriteString("");
foreach (var child in element.Nodes())
{
var xElement = child as XElement;
if (xElement != null)
WriteElementTo(writer, xElement, suppressIndentingChildren);
else
child.WriteTo(writer); // defaults are fine for everything else.
}
writer.WriteEndElement();
}
/// <summary>
/// Remove illegal XML characters from a string.
/// </summary>
public static string SanitizeString(string s)
{
if (string.IsNullOrEmpty(s))
{
return s;
}
StringBuilder buffer = new StringBuilder(s.Length);
for (int i = 0; i < s.Length; i++)
{
int code;
try
{
code = Char.ConvertToUtf32(s, i);
}
catch (ArgumentException)
{
continue;
}
if (IsLegalXmlChar(code))
buffer.Append(Char.ConvertFromUtf32(code));
if (Char.IsSurrogatePair(s, i))
i++;
}
return buffer.ToString();
}
/// <summary>
/// Whether a given character is allowed by XML 1.0.
/// </summary>
private static bool IsLegalXmlChar(int codePoint)
{
return (codePoint == 0x9 ||
codePoint == 0xA ||
codePoint == 0xD ||
(codePoint >= 0x20 && codePoint <= 0xD7FF) ||
(codePoint >= 0xE000 && codePoint <= 0xFFFD) ||
(codePoint >= 0x10000/* && character <= 0x10FFFF*/) //it's impossible to get a code point bigger than 0x10FFFF because Char.ConvertToUtf32 would have thrown an exception
);
}
}
}
| |
using System;
using System.IO;
using ChainUtils.BouncyCastle.Utilities;
namespace ChainUtils.BouncyCastle.Asn1
{
/**
* Class representing the DER-type External
*/
public class DerExternal
: Asn1Object
{
private DerObjectIdentifier directReference;
private DerInteger indirectReference;
private Asn1Object dataValueDescriptor;
private int encoding;
private Asn1Object externalContent;
public DerExternal(
Asn1EncodableVector vector)
{
var offset = 0;
var enc = GetObjFromVector(vector, offset);
if (enc is DerObjectIdentifier)
{
directReference = (DerObjectIdentifier)enc;
offset++;
enc = GetObjFromVector(vector, offset);
}
if (enc is DerInteger)
{
indirectReference = (DerInteger) enc;
offset++;
enc = GetObjFromVector(vector, offset);
}
if (!(enc is DerTaggedObject))
{
dataValueDescriptor = (Asn1Object) enc;
offset++;
enc = GetObjFromVector(vector, offset);
}
if (!(enc is DerTaggedObject))
{
throw new InvalidOperationException(
"No tagged object found in vector. Structure doesn't seem to be of type External");
}
if (vector.Count != offset + 1)
throw new ArgumentException("input vector too large", "vector");
if (!(enc is DerTaggedObject))
throw new ArgumentException("No tagged object found in vector. Structure doesn't seem to be of type External", "vector");
var obj = (DerTaggedObject)enc;
// Use property accessor to include check on value
Encoding = obj.TagNo;
if (encoding < 0 || encoding > 2)
throw new InvalidOperationException("invalid encoding value");
externalContent = obj.GetObject();
}
/**
* Creates a new instance of DerExternal
* See X.690 for more informations about the meaning of these parameters
* @param directReference The direct reference or <code>null</code> if not set.
* @param indirectReference The indirect reference or <code>null</code> if not set.
* @param dataValueDescriptor The data value descriptor or <code>null</code> if not set.
* @param externalData The external data in its encoded form.
*/
public DerExternal(DerObjectIdentifier directReference, DerInteger indirectReference, Asn1Object dataValueDescriptor, DerTaggedObject externalData)
: this(directReference, indirectReference, dataValueDescriptor, externalData.TagNo, externalData.ToAsn1Object())
{
}
/**
* Creates a new instance of DerExternal.
* See X.690 for more informations about the meaning of these parameters
* @param directReference The direct reference or <code>null</code> if not set.
* @param indirectReference The indirect reference or <code>null</code> if not set.
* @param dataValueDescriptor The data value descriptor or <code>null</code> if not set.
* @param encoding The encoding to be used for the external data
* @param externalData The external data
*/
public DerExternal(DerObjectIdentifier directReference, DerInteger indirectReference, Asn1Object dataValueDescriptor, int encoding, Asn1Object externalData)
{
DirectReference = directReference;
IndirectReference = indirectReference;
DataValueDescriptor = dataValueDescriptor;
Encoding = encoding;
ExternalContent = externalData.ToAsn1Object();
}
internal override void Encode(DerOutputStream derOut)
{
var ms = new MemoryStream();
WriteEncodable(ms, directReference);
WriteEncodable(ms, indirectReference);
WriteEncodable(ms, dataValueDescriptor);
WriteEncodable(ms, new DerTaggedObject(Asn1Tags.External, externalContent));
derOut.WriteEncoded(Asn1Tags.Constructed, Asn1Tags.External, ms.ToArray());
}
protected override int Asn1GetHashCode()
{
var ret = externalContent.GetHashCode();
if (directReference != null)
{
ret ^= directReference.GetHashCode();
}
if (indirectReference != null)
{
ret ^= indirectReference.GetHashCode();
}
if (dataValueDescriptor != null)
{
ret ^= dataValueDescriptor.GetHashCode();
}
return ret;
}
protected override bool Asn1Equals(
Asn1Object asn1Object)
{
if (this == asn1Object)
return true;
var other = asn1Object as DerExternal;
if (other == null)
return false;
return Equals(directReference, other.directReference)
&& Equals(indirectReference, other.indirectReference)
&& Equals(dataValueDescriptor, other.dataValueDescriptor)
&& externalContent.Equals(other.externalContent);
}
public Asn1Object DataValueDescriptor
{
get { return dataValueDescriptor; }
set { dataValueDescriptor = value; }
}
public DerObjectIdentifier DirectReference
{
get { return directReference; }
set { directReference = value; }
}
/**
* The encoding of the content. Valid values are
* <ul>
* <li><code>0</code> single-ASN1-type</li>
* <li><code>1</code> OCTET STRING</li>
* <li><code>2</code> BIT STRING</li>
* </ul>
*/
public int Encoding
{
get
{
return encoding;
}
set
{
if (encoding < 0 || encoding > 2)
throw new InvalidOperationException("invalid encoding value: " + encoding);
encoding = value;
}
}
public Asn1Object ExternalContent
{
get { return externalContent; }
set { externalContent = value; }
}
public DerInteger IndirectReference
{
get { return indirectReference; }
set { indirectReference = value; }
}
private static Asn1Object GetObjFromVector(Asn1EncodableVector v, int index)
{
if (v.Count <= index)
throw new ArgumentException("too few objects in input vector", "v");
return v[index].ToAsn1Object();
}
private static void WriteEncodable(MemoryStream ms, Asn1Encodable e)
{
if (e != null)
{
var bs = e.GetDerEncoded();
ms.Write(bs, 0, bs.Length);
}
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gagr = Google.Api.Gax.ResourceNames;
using gcov = Google.Cloud.OsConfig.V1Alpha;
using sys = System;
namespace Google.Cloud.OsConfig.V1Alpha
{
/// <summary>Resource name for the <c>InstanceOSPoliciesCompliance</c> resource.</summary>
public sealed partial class InstanceOSPoliciesComplianceName : gax::IResourceName, sys::IEquatable<InstanceOSPoliciesComplianceName>
{
/// <summary>The possible contents of <see cref="InstanceOSPoliciesComplianceName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/instanceOSPoliciesCompliances/{instance}</c>.
/// </summary>
ProjectLocationInstance = 1,
}
private static gax::PathTemplate s_projectLocationInstance = new gax::PathTemplate("projects/{project}/locations/{location}/instanceOSPoliciesCompliances/{instance}");
/// <summary>
/// Creates a <see cref="InstanceOSPoliciesComplianceName"/> containing an unparsed resource name.
/// </summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="InstanceOSPoliciesComplianceName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static InstanceOSPoliciesComplianceName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new InstanceOSPoliciesComplianceName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="InstanceOSPoliciesComplianceName"/> with the pattern
/// <c>projects/{project}/locations/{location}/instanceOSPoliciesCompliances/{instance}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// A new instance of <see cref="InstanceOSPoliciesComplianceName"/> constructed from the provided ids.
/// </returns>
public static InstanceOSPoliciesComplianceName FromProjectLocationInstance(string projectId, string locationId, string instanceId) =>
new InstanceOSPoliciesComplianceName(ResourceNameType.ProjectLocationInstance, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), instanceId: gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="InstanceOSPoliciesComplianceName"/> with
/// pattern <c>projects/{project}/locations/{location}/instanceOSPoliciesCompliances/{instance}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="InstanceOSPoliciesComplianceName"/> with pattern
/// <c>projects/{project}/locations/{location}/instanceOSPoliciesCompliances/{instance}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string instanceId) =>
FormatProjectLocationInstance(projectId, locationId, instanceId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="InstanceOSPoliciesComplianceName"/> with
/// pattern <c>projects/{project}/locations/{location}/instanceOSPoliciesCompliances/{instance}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="InstanceOSPoliciesComplianceName"/> with pattern
/// <c>projects/{project}/locations/{location}/instanceOSPoliciesCompliances/{instance}</c>.
/// </returns>
public static string FormatProjectLocationInstance(string projectId, string locationId, string instanceId) =>
s_projectLocationInstance.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="InstanceOSPoliciesComplianceName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/instanceOSPoliciesCompliances/{instance}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="instanceOSPoliciesComplianceName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <returns>The parsed <see cref="InstanceOSPoliciesComplianceName"/> if successful.</returns>
public static InstanceOSPoliciesComplianceName Parse(string instanceOSPoliciesComplianceName) =>
Parse(instanceOSPoliciesComplianceName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="InstanceOSPoliciesComplianceName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/instanceOSPoliciesCompliances/{instance}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="instanceOSPoliciesComplianceName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="InstanceOSPoliciesComplianceName"/> if successful.</returns>
public static InstanceOSPoliciesComplianceName Parse(string instanceOSPoliciesComplianceName, bool allowUnparsed) =>
TryParse(instanceOSPoliciesComplianceName, allowUnparsed, out InstanceOSPoliciesComplianceName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="InstanceOSPoliciesComplianceName"/>
/// instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/instanceOSPoliciesCompliances/{instance}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="instanceOSPoliciesComplianceName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="InstanceOSPoliciesComplianceName"/>, or <c>null</c> if
/// parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string instanceOSPoliciesComplianceName, out InstanceOSPoliciesComplianceName result) =>
TryParse(instanceOSPoliciesComplianceName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="InstanceOSPoliciesComplianceName"/>
/// instance; optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/instanceOSPoliciesCompliances/{instance}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="instanceOSPoliciesComplianceName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="InstanceOSPoliciesComplianceName"/>, or <c>null</c> if
/// parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string instanceOSPoliciesComplianceName, bool allowUnparsed, out InstanceOSPoliciesComplianceName result)
{
gax::GaxPreconditions.CheckNotNull(instanceOSPoliciesComplianceName, nameof(instanceOSPoliciesComplianceName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationInstance.TryParseName(instanceOSPoliciesComplianceName, out resourceName))
{
result = FromProjectLocationInstance(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(instanceOSPoliciesComplianceName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private InstanceOSPoliciesComplianceName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string instanceId = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
InstanceId = instanceId;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="InstanceOSPoliciesComplianceName"/> class from the component parts
/// of pattern <c>projects/{project}/locations/{location}/instanceOSPoliciesCompliances/{instance}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param>
public InstanceOSPoliciesComplianceName(string projectId, string locationId, string instanceId) : this(ResourceNameType.ProjectLocationInstance, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), instanceId: gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Instance</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string InstanceId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationInstance: return s_projectLocationInstance.Expand(ProjectId, LocationId, InstanceId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as InstanceOSPoliciesComplianceName);
/// <inheritdoc/>
public bool Equals(InstanceOSPoliciesComplianceName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(InstanceOSPoliciesComplianceName a, InstanceOSPoliciesComplianceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(InstanceOSPoliciesComplianceName a, InstanceOSPoliciesComplianceName b) => !(a == b);
}
public partial class InstanceOSPoliciesCompliance
{
/// <summary>
/// <see cref="gcov::InstanceOSPoliciesComplianceName"/>-typed view over the <see cref="Name"/> resource name
/// property.
/// </summary>
[sys::ObsoleteAttribute]
public gcov::InstanceOSPoliciesComplianceName InstanceOSPoliciesComplianceName
{
get => string.IsNullOrEmpty(Name) ? null : gcov::InstanceOSPoliciesComplianceName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GetInstanceOSPoliciesComplianceRequest
{
/// <summary>
/// <see cref="gcov::InstanceOSPoliciesComplianceName"/>-typed view over the <see cref="Name"/> resource name
/// property.
/// </summary>
[sys::ObsoleteAttribute]
public gcov::InstanceOSPoliciesComplianceName InstanceOSPoliciesComplianceName
{
get => string.IsNullOrEmpty(Name) ? null : gcov::InstanceOSPoliciesComplianceName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListInstanceOSPoliciesCompliancesRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
[sys::ObsoleteAttribute]
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
namespace System.Reflection
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
#if FEATURE_REMOTING
using System.Runtime.Remoting.Metadata;
#endif //FEATURE_REMOTING
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using MemberListType = System.RuntimeType.MemberListType;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
using System.Runtime.CompilerServices;
[Serializable]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_ConstructorInfo))]
#pragma warning disable 618
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
#pragma warning restore 618
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class ConstructorInfo : MethodBase, _ConstructorInfo
{
#region Static Members
[System.Runtime.InteropServices.ComVisible(true)]
public readonly static String ConstructorName = ".ctor";
[System.Runtime.InteropServices.ComVisible(true)]
public readonly static String TypeConstructorName = ".cctor";
#endregion
#region Constructor
protected ConstructorInfo() { }
#endregion
public static bool operator ==(ConstructorInfo left, ConstructorInfo right)
{
if (ReferenceEquals(left, right))
return true;
if ((object)left == null || (object)right == null ||
left is RuntimeConstructorInfo || right is RuntimeConstructorInfo)
{
return false;
}
return left.Equals(right);
}
public static bool operator !=(ConstructorInfo left, ConstructorInfo right)
{
return !(left == right);
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#region Internal Members
internal virtual Type GetReturnType() { throw new NotImplementedException(); }
#endregion
#region MemberInfo Overrides
[System.Runtime.InteropServices.ComVisible(true)]
public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Constructor; } }
#endregion
#region Public Abstract\Virtual Members
public abstract Object Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture);
#endregion
#region Public Members
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public Object Invoke(Object[] parameters)
{
// Theoretically we should set up a LookForMyCaller stack mark here and pass that along.
// But to maintain backward compatibility we can't switch to calling an
// internal overload that takes a stack mark.
// Fortunately the stack walker skips all the reflection invocation frames including this one.
// So this method will never be returned by the stack walker as the caller.
// See SystemDomain::CallersMethodCallbackWithStackMark in AppDomain.cpp.
return Invoke(BindingFlags.Default, null, parameters, null);
}
#endregion
#if !FEATURE_CORECLR
#region COM Interop Support
Type _ConstructorInfo.GetType()
{
return base.GetType();
}
Object _ConstructorInfo.Invoke_2(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
return Invoke(obj, invokeAttr, binder, parameters, culture);
}
Object _ConstructorInfo.Invoke_3(Object obj, Object[] parameters)
{
return Invoke(obj, parameters);
}
Object _ConstructorInfo.Invoke_4(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
return Invoke(invokeAttr, binder, parameters, culture);
}
Object _ConstructorInfo.Invoke_5(Object[] parameters)
{
return Invoke(parameters);
}
void _ConstructorInfo.GetTypeInfoCount(out uint pcTInfo)
{
throw new NotImplementedException();
}
void _ConstructorInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
{
throw new NotImplementedException();
}
void _ConstructorInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
{
throw new NotImplementedException();
}
// If you implement this method, make sure to include _ConstructorInfo.Invoke in VM\DangerousAPIs.h and
// include _ConstructorInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
void _ConstructorInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
{
throw new NotImplementedException();
}
#endregion
#endif
}
[Serializable]
internal sealed class RuntimeConstructorInfo : ConstructorInfo, ISerializable, IRuntimeMethodInfo
{
#region Private Data Members
private volatile RuntimeType m_declaringType;
private RuntimeTypeCache m_reflectedTypeCache;
private string m_toString;
private ParameterInfo[] m_parameters = null; // Created lazily when GetParameters() is called.
#pragma warning disable 169
private object _empty1; // These empties are used to ensure that RuntimeConstructorInfo and RuntimeMethodInfo are have a layout which is sufficiently similar
private object _empty2;
private object _empty3;
#pragma warning restore 169
private IntPtr m_handle;
private MethodAttributes m_methodAttributes;
private BindingFlags m_bindingFlags;
private volatile Signature m_signature;
private INVOCATION_FLAGS m_invocationFlags;
#if FEATURE_APPX
private bool IsNonW8PFrameworkAPI()
{
if (DeclaringType.IsArray && IsPublic && !IsStatic)
return false;
RuntimeAssembly rtAssembly = GetRuntimeAssembly();
if (rtAssembly.IsFrameworkAssembly())
{
int ctorToken = rtAssembly.InvocableAttributeCtorToken;
if (System.Reflection.MetadataToken.IsNullToken(ctorToken) ||
!CustomAttribute.IsAttributeDefined(GetRuntimeModule(), MetadataToken, ctorToken))
return true;
}
if (GetRuntimeType().IsNonW8PFrameworkAPI())
return true;
return false;
}
internal override bool IsDynamicallyInvokable
{
get
{
return !AppDomain.ProfileAPICheck || !IsNonW8PFrameworkAPI();
}
}
#endif // FEATURE_APPX
internal INVOCATION_FLAGS InvocationFlags
{
[System.Security.SecuritySafeCritical]
get
{
if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0)
{
INVOCATION_FLAGS invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_IS_CTOR; // this is a given
Type declaringType = DeclaringType;
//
// first take care of all the NO_INVOKE cases.
if ( declaringType == typeof(void) ||
(declaringType != null && declaringType.ContainsGenericParameters) ||
((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) ||
((Attributes & MethodAttributes.RequireSecObject) == MethodAttributes.RequireSecObject))
{
// We don't need other flags if this method cannot be invoked
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE;
}
else if (IsStatic || declaringType != null && declaringType.IsAbstract)
{
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_CTOR_INVOKE;
}
else
{
// this should be an invocable method, determine the other flags that participate in invocation
invocationFlags |= RuntimeMethodHandle.GetSecurityFlags(this);
if ( (invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) == 0 &&
((Attributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public ||
(declaringType != null && declaringType.NeedsReflectionSecurityCheck)) )
{
// If method is non-public, or declaring type is not visible
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY;
}
// Check for attempt to create a delegate class, we demand unmanaged
// code permission for this since it's hard to validate the target address.
if (typeof(Delegate).IsAssignableFrom(DeclaringType))
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_IS_DELEGATE_CTOR;
}
#if FEATURE_APPX
if (AppDomain.ProfileAPICheck && IsNonW8PFrameworkAPI())
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API;
#endif // FEATURE_APPX
m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED;
}
return m_invocationFlags;
}
}
#endregion
#region Constructor
[System.Security.SecurityCritical] // auto-generated
internal RuntimeConstructorInfo(
RuntimeMethodHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache,
MethodAttributes methodAttributes, BindingFlags bindingFlags)
{
Contract.Ensures(methodAttributes == RuntimeMethodHandle.GetAttributes(handle));
m_bindingFlags = bindingFlags;
m_reflectedTypeCache = reflectedTypeCache;
m_declaringType = declaringType;
m_handle = handle.Value;
m_methodAttributes = methodAttributes;
}
#endregion
#if FEATURE_REMOTING
#region Legacy Remoting Cache
// The size of CachedData is accounted for by BaseObjectWithCachedData in object.h.
// This member is currently being used by Remoting for caching remoting data. If you
// need to cache data here, talk to the Remoting team to work out a mechanism, so that
// both caching systems can happily work together.
private RemotingMethodCachedData m_cachedData;
internal RemotingMethodCachedData RemotingCache
{
get
{
// This grabs an internal copy of m_cachedData and uses
// that instead of looking at m_cachedData directly because
// the cache may get cleared asynchronously. This prevents
// us from having to take a lock.
RemotingMethodCachedData cache = m_cachedData;
if (cache == null)
{
cache = new RemotingMethodCachedData(this);
RemotingMethodCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null);
if (ret != null)
cache = ret;
}
return cache;
}
}
#endregion
#endif //FEATURE_REMOTING
#region NonPublic Methods
RuntimeMethodHandleInternal IRuntimeMethodInfo.Value
{
[System.Security.SecuritySafeCritical]
get
{
return new RuntimeMethodHandleInternal(m_handle);
}
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal override bool CacheEquals(object o)
{
RuntimeConstructorInfo m = o as RuntimeConstructorInfo;
if ((object)m == null)
return false;
return m.m_handle == m_handle;
}
private Signature Signature
{
get
{
if (m_signature == null)
m_signature = new Signature(this, m_declaringType);
return m_signature;
}
}
private RuntimeType ReflectedTypeInternal
{
get
{
return m_reflectedTypeCache.GetRuntimeType();
}
}
private void CheckConsistency(Object target)
{
if (target == null && IsStatic)
return;
if (!m_declaringType.IsInstanceOfType(target))
{
if (target == null)
throw new TargetException(Environment.GetResourceString("RFLCT.Targ_StatMethReqTarg"));
throw new TargetException(Environment.GetResourceString("RFLCT.Targ_ITargMismatch"));
}
}
internal BindingFlags BindingFlags { get { return m_bindingFlags; } }
// Differs from MethodHandle in that it will return a valid handle even for reflection only loaded types
internal RuntimeMethodHandle GetMethodHandle()
{
return new RuntimeMethodHandle(this);
}
internal bool IsOverloaded
{
get
{
return m_reflectedTypeCache.GetConstructorList(MemberListType.CaseSensitive, Name).Length > 1;
}
}
#endregion
#region Object Overrides
public override String ToString()
{
// "Void" really doesn't make sense here. But we'll keep it for compat reasons.
if (m_toString == null)
m_toString = "Void " + FormatNameAndSig();
return m_toString;
}
#endregion
#region ICustomAttributeProvider
public override Object[] GetCustomAttributes(bool inherit)
{
return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return CustomAttributeData.GetCustomAttributesInternal(this);
}
#endregion
#region MemberInfo Overrides
public override String Name
{
[System.Security.SecuritySafeCritical] // auto-generated
get { return RuntimeMethodHandle.GetName(this); }
}
[System.Runtime.InteropServices.ComVisible(true)]
public override MemberTypes MemberType { get { return MemberTypes.Constructor; } }
public override Type DeclaringType
{
get
{
return m_reflectedTypeCache.IsGlobal ? null : m_declaringType;
}
}
public override Type ReflectedType
{
get
{
return m_reflectedTypeCache.IsGlobal ? null : ReflectedTypeInternal;
}
}
public override int MetadataToken
{
[System.Security.SecuritySafeCritical] // auto-generated
get { return RuntimeMethodHandle.GetMethodDef(this); }
}
public override Module Module
{
get { return GetRuntimeModule(); }
}
internal RuntimeType GetRuntimeType() { return m_declaringType; }
internal RuntimeModule GetRuntimeModule() { return RuntimeTypeHandle.GetModule(m_declaringType); }
internal RuntimeAssembly GetRuntimeAssembly() { return GetRuntimeModule().GetRuntimeAssembly(); }
#endregion
#region MethodBase Overrides
// This seems to always returns System.Void.
internal override Type GetReturnType() { return Signature.ReturnType; }
[System.Security.SecuritySafeCritical] // auto-generated
internal override ParameterInfo[] GetParametersNoCopy()
{
if (m_parameters == null)
m_parameters = RuntimeParameterInfo.GetParameters(this, this, Signature);
return m_parameters;
}
[Pure]
public override ParameterInfo[] GetParameters()
{
ParameterInfo[] parameters = GetParametersNoCopy();
if (parameters.Length == 0)
return parameters;
ParameterInfo[] ret = new ParameterInfo[parameters.Length];
Array.Copy(parameters, ret, parameters.Length);
return ret;
}
public override MethodImplAttributes GetMethodImplementationFlags()
{
return RuntimeMethodHandle.GetImplAttributes(this);
}
public override RuntimeMethodHandle MethodHandle
{
get
{
Type declaringType = DeclaringType;
if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly"));
return new RuntimeMethodHandle(this);
}
}
public override MethodAttributes Attributes
{
get
{
return m_methodAttributes;
}
}
public override CallingConventions CallingConvention
{
get
{
return Signature.CallingConvention;
}
}
internal static void CheckCanCreateInstance(Type declaringType, bool isVarArg)
{
if (declaringType == null)
throw new ArgumentNullException(nameof(declaringType));
Contract.EndContractBlock();
// ctor is ReflectOnly
if (declaringType is ReflectionOnlyType)
throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyInvoke"));
// ctor is declared on interface class
else if (declaringType.IsInterface)
throw new MemberAccessException(
String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Acc_CreateInterfaceEx"), declaringType));
// ctor is on an abstract class
else if (declaringType.IsAbstract)
throw new MemberAccessException(
String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Acc_CreateAbstEx"), declaringType));
// ctor is on a class that contains stack pointers
else if (declaringType.GetRootElementType() == typeof(ArgIterator))
throw new NotSupportedException();
// ctor is vararg
else if (isVarArg)
throw new NotSupportedException();
// ctor is generic or on a generic class
else if (declaringType.ContainsGenericParameters)
{
throw new MemberAccessException(
String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Acc_CreateGenericEx"), declaringType));
}
// ctor is declared on System.Void
else if (declaringType == typeof(void))
throw new MemberAccessException(Environment.GetResourceString("Access_Void"));
}
internal void ThrowNoInvokeException()
{
CheckCanCreateInstance(DeclaringType, (CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs);
// ctor is .cctor
if ((Attributes & MethodAttributes.Static) == MethodAttributes.Static)
throw new MemberAccessException(Environment.GetResourceString("Acc_NotClassInit"));
throw new TargetException();
}
[System.Security.SecuritySafeCritical] // auto-generated
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public override Object Invoke(
Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
INVOCATION_FLAGS invocationFlags = InvocationFlags;
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0)
ThrowNoInvokeException();
// check basic method consistency. This call will throw if there are problems in the target/method relationship
CheckConsistency(obj);
#if FEATURE_APPX
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
if (caller != null && !caller.IsSafeForReflection())
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName));
}
#endif
if (obj != null)
{
#if FEATURE_CORECLR
// For unverifiable code, we require the caller to be critical.
// Adding the INVOCATION_FLAGS_NEED_SECURITY flag makes that check happen
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY;
#else // FEATURE_CORECLR
new SecurityPermission(SecurityPermissionFlag.SkipVerification).Demand();
#endif // FEATURE_CORECLR
}
#if !FEATURE_CORECLR
if ((invocationFlags &(INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY)) != 0)
{
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD) != 0)
CodeAccessPermission.Demand(PermissionType.ReflectionMemberAccess);
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0)
RuntimeMethodHandle.PerformSecurityCheck(obj, this, m_declaringType, (uint)m_invocationFlags);
}
#endif // !FEATURE_CORECLR
Signature sig = Signature;
// get the signature
int formalCount = sig.Arguments.Length;
int actualCount =(parameters != null) ? parameters.Length : 0;
if (formalCount != actualCount)
throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt"));
// if we are here we passed all the previous checks. Time to look at the arguments
if (actualCount > 0)
{
Object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig);
Object retValue = RuntimeMethodHandle.InvokeMethod(obj, arguments, sig, false);
// copy out. This should be made only if ByRef are present.
for (int index = 0; index < arguments.Length; index++)
parameters[index] = arguments[index];
return retValue;
}
return RuntimeMethodHandle.InvokeMethod(obj, null, sig, false);
}
[System.Security.SecuritySafeCritical] // overrides SC member
#pragma warning disable 618
[ReflectionPermissionAttribute(SecurityAction.Demand, Flags = ReflectionPermissionFlag.MemberAccess)]
#pragma warning restore 618
public override MethodBody GetMethodBody()
{
MethodBody mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal);
if (mb != null)
mb.m_methodBase = this;
return mb;
}
public override bool IsSecurityCritical
{
#if FEATURE_CORECLR
get { return true; }
#else
get { return RuntimeMethodHandle.IsSecurityCritical(this); }
#endif
}
public override bool IsSecuritySafeCritical
{
#if FEATURE_CORECLR
get { return false; }
#else
get { return RuntimeMethodHandle.IsSecuritySafeCritical(this); }
#endif
}
public override bool IsSecurityTransparent
{
#if FEATURE_CORECLR
get { return false; }
#else
get { return RuntimeMethodHandle.IsSecurityTransparent(this); }
#endif
}
public override bool ContainsGenericParameters
{
get
{
return (DeclaringType != null && DeclaringType.ContainsGenericParameters);
}
}
#endregion
#region ConstructorInfo Overrides
[System.Security.SecuritySafeCritical] // auto-generated
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public override Object Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
INVOCATION_FLAGS invocationFlags = InvocationFlags;
// get the declaring TypeHandle early for consistent exceptions in IntrospectionOnly context
RuntimeTypeHandle declaringTypeHandle = m_declaringType.TypeHandle;
if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE | INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS | INVOCATION_FLAGS.INVOCATION_FLAGS_NO_CTOR_INVOKE)) != 0)
ThrowNoInvokeException();
#if FEATURE_APPX
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
if (caller != null && !caller.IsSafeForReflection())
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName));
}
#endif
#if !FEATURE_CORECLR
if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY | INVOCATION_FLAGS.INVOCATION_FLAGS_IS_DELEGATE_CTOR)) != 0)
{
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD) != 0)
CodeAccessPermission.Demand(PermissionType.ReflectionMemberAccess);
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0)
RuntimeMethodHandle.PerformSecurityCheck(null, this, m_declaringType, (uint)(m_invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_CONSTRUCTOR_INVOKE));
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_IS_DELEGATE_CTOR) != 0)
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
}
#endif // !FEATURE_CORECLR
// get the signature
Signature sig = Signature;
int formalCount = sig.Arguments.Length;
int actualCount =(parameters != null) ? parameters.Length : 0;
if (formalCount != actualCount)
throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt"));
// We don't need to explicitly invoke the class constructor here,
// JIT/NGen will insert the call to .cctor in the instance ctor.
// if we are here we passed all the previous checks. Time to look at the arguments
if (actualCount > 0)
{
Object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig);
Object retValue = RuntimeMethodHandle.InvokeMethod(null, arguments, sig, true);
// copy out. This should be made only if ByRef are present.
for (int index = 0; index < arguments.Length; index++)
parameters[index] = arguments[index];
return retValue;
}
return RuntimeMethodHandle.InvokeMethod(null, null, sig, true);
}
#endregion
#region ISerializable Implementation
[System.Security.SecurityCritical] // auto-generated
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
MemberInfoSerializationHolder.GetSerializationInfo(
info,
Name,
ReflectedTypeInternal,
ToString(),
SerializationToString(),
MemberTypes.Constructor,
null);
}
internal string SerializationToString()
{
// We don't need the return type for constructors.
return FormatNameAndSig(true);
}
internal void SerializationInvoke(Object target, SerializationInfo info, StreamingContext context)
{
RuntimeMethodHandle.SerializationInvoke(this, target, info, ref context);
}
#endregion
}
}
| |
//---------------------------------------------------------------------
// <copyright file="ColumnMapVisitorWithResults.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
namespace System.Data.Query.InternalTrees
{
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Data.Common.CommandTrees;
using System.Data.Metadata.Edm;
using System.Data.Query.PlanCompiler;
using System.Diagnostics;
using System.IO;
using System.Threading;
/// <summary>
/// Basic Visitor Design Pattern support for ColumnMap hierarchy;
///
/// This visitor class will walk the entire hierarchy, but does not
/// return results; it's useful for operations such as printing and
/// searching.
/// </summary>
/// <typeparam name="TArgType"></typeparam>
internal abstract class ColumnMapVisitor<TArgType>
{
#region visitor helpers
/// <summary>
/// Common List(ColumnMap) code
/// </summary>
/// <param name="columnMaps"></param>
/// <param name="arg"></param>
protected void VisitList<TListType>(TListType[] columnMaps, TArgType arg)
where TListType : ColumnMap
{
foreach (TListType columnMap in columnMaps)
{
columnMap.Accept(this, arg);
}
}
#endregion
#region EntityIdentity handling
protected void VisitEntityIdentity(EntityIdentity entityIdentity, TArgType arg)
{
DiscriminatedEntityIdentity dei = entityIdentity as DiscriminatedEntityIdentity;
if (null != dei)
{
VisitEntityIdentity(dei, arg);
}
else
{
VisitEntityIdentity((SimpleEntityIdentity)entityIdentity, arg);
}
}
protected virtual void VisitEntityIdentity(DiscriminatedEntityIdentity entityIdentity, TArgType arg)
{
entityIdentity.EntitySetColumnMap.Accept(this, arg);
foreach (SimpleColumnMap columnMap in entityIdentity.Keys)
{
columnMap.Accept(this, arg);
}
}
protected virtual void VisitEntityIdentity(SimpleEntityIdentity entityIdentity, TArgType arg)
{
foreach (SimpleColumnMap columnMap in entityIdentity.Keys)
{
columnMap.Accept(this, arg);
}
}
#endregion
#region Visitor methods
internal virtual void Visit(ComplexTypeColumnMap columnMap, TArgType arg)
{
ColumnMap nullSentinel = columnMap.NullSentinel;
if (null != nullSentinel)
{
nullSentinel.Accept(this, arg);
}
foreach (ColumnMap p in columnMap.Properties)
{
p.Accept(this, arg);
}
}
internal virtual void Visit(DiscriminatedCollectionColumnMap columnMap, TArgType arg)
{
columnMap.Discriminator.Accept(this, arg);
foreach (SimpleColumnMap fk in columnMap.ForeignKeys)
{
fk.Accept(this, arg);
}
foreach (SimpleColumnMap k in columnMap.Keys)
{
k.Accept(this, arg);
}
columnMap.Element.Accept(this, arg);
}
internal virtual void Visit(EntityColumnMap columnMap, TArgType arg)
{
VisitEntityIdentity(columnMap.EntityIdentity, arg);
foreach (ColumnMap p in columnMap.Properties)
{
p.Accept(this, arg);
}
}
internal virtual void Visit(SimplePolymorphicColumnMap columnMap, TArgType arg)
{
columnMap.TypeDiscriminator.Accept(this, arg);
foreach (ColumnMap cm in columnMap.TypeChoices.Values)
{
cm.Accept(this, arg);
}
foreach (ColumnMap p in columnMap.Properties)
{
p.Accept(this, arg);
}
}
internal virtual void Visit(MultipleDiscriminatorPolymorphicColumnMap columnMap, TArgType arg)
{
foreach (var typeDiscriminator in columnMap.TypeDiscriminators)
{
typeDiscriminator.Accept(this, arg);
}
foreach (var typeColumnMap in columnMap.TypeChoices.Values)
{
typeColumnMap.Accept(this, arg);
}
foreach (var property in columnMap.Properties)
{
property.Accept(this, arg);
}
}
internal virtual void Visit(RecordColumnMap columnMap, TArgType arg)
{
ColumnMap nullSentinel = columnMap.NullSentinel;
if (null != nullSentinel)
{
nullSentinel.Accept(this, arg);
}
foreach (ColumnMap p in columnMap.Properties)
{
p.Accept(this, arg);
}
}
internal virtual void Visit(RefColumnMap columnMap, TArgType arg)
{
VisitEntityIdentity(columnMap.EntityIdentity, arg);
}
internal virtual void Visit(ScalarColumnMap columnMap, TArgType arg)
{
}
internal virtual void Visit(SimpleCollectionColumnMap columnMap, TArgType arg)
{
foreach (SimpleColumnMap fk in columnMap.ForeignKeys)
{
fk.Accept(this, arg);
}
foreach (SimpleColumnMap k in columnMap.Keys)
{
k.Accept(this, arg);
}
columnMap.Element.Accept(this, arg);
}
internal virtual void Visit(VarRefColumnMap columnMap, TArgType arg)
{
}
#endregion
}
/// <summary>
/// Basic Visitor Design Pattern support for ColumnMap hierarchy;
///
/// This visitor class allows you to return results; it's useful for operations
/// that copy or manipulate the hierarchy.
/// </summary>
/// <typeparam name="TArgType"></typeparam>
/// <typeparam name="TResultType"></typeparam>
internal abstract class ColumnMapVisitorWithResults<TResultType, TArgType>
{
#region EntityIdentity handling
protected EntityIdentity VisitEntityIdentity(EntityIdentity entityIdentity, TArgType arg)
{
DiscriminatedEntityIdentity dei = entityIdentity as DiscriminatedEntityIdentity;
if (null != dei)
{
return VisitEntityIdentity(dei, arg);
}
else
{
return VisitEntityIdentity((SimpleEntityIdentity)entityIdentity, arg);
}
}
protected virtual EntityIdentity VisitEntityIdentity(DiscriminatedEntityIdentity entityIdentity, TArgType arg)
{
return entityIdentity;
}
protected virtual EntityIdentity VisitEntityIdentity(SimpleEntityIdentity entityIdentity, TArgType arg)
{
return entityIdentity;
}
#endregion
#region Visitor methods
internal abstract TResultType Visit(ComplexTypeColumnMap columnMap, TArgType arg);
internal abstract TResultType Visit(DiscriminatedCollectionColumnMap columnMap, TArgType arg);
internal abstract TResultType Visit(EntityColumnMap columnMap, TArgType arg);
internal abstract TResultType Visit(SimplePolymorphicColumnMap columnMap, TArgType arg);
internal abstract TResultType Visit(RecordColumnMap columnMap, TArgType arg);
internal abstract TResultType Visit(RefColumnMap columnMap, TArgType arg);
internal abstract TResultType Visit(ScalarColumnMap columnMap, TArgType arg);
internal abstract TResultType Visit(SimpleCollectionColumnMap columnMap, TArgType arg);
internal abstract TResultType Visit(VarRefColumnMap columnMap, TArgType arg);
internal abstract TResultType Visit(MultipleDiscriminatorPolymorphicColumnMap columnMap, TArgType arg);
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Moq;
using NuGet.Test.Mocks;
using Xunit;
namespace NuGet.Test
{
public class PackageWalkerTest
{
[Fact]
public void ReverseDependencyWalkerUsersVersionAndIdToDetermineVisited()
{
// Arrange
// A 1.0 -> B 1.0
IPackage packageA1 = PackageUtility.CreatePackage("A",
"1.0",
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "[1.0]")
});
// A 2.0 -> B 2.0
IPackage packageA2 = PackageUtility.CreatePackage("A",
"2.0",
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "[2.0]")
});
IPackage packageB1 = PackageUtility.CreatePackage("B", "1.0");
IPackage packageB2 = PackageUtility.CreatePackage("B", "2.0");
var mockRepository = new MockPackageRepository();
mockRepository.AddPackage(packageA1);
mockRepository.AddPackage(packageA2);
mockRepository.AddPackage(packageB1);
mockRepository.AddPackage(packageB2);
// Act
IDependentsResolver lookup = new DependentsWalker(mockRepository);
// Assert
Assert.Equal(0, lookup.GetDependents(packageA1).Count());
Assert.Equal(0, lookup.GetDependents(packageA2).Count());
Assert.Equal(1, lookup.GetDependents(packageB1).Count());
Assert.Equal(1, lookup.GetDependents(packageB2).Count());
}
[Fact]
public void ResolveDependenciesForInstallPackageWithUnknownDependencyThrows()
{
// Arrange
IPackage package = PackageUtility.CreatePackage("A",
"1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B")
});
IPackageOperationResolver resolver = new InstallWalker(new MockPackageRepository(),
new MockPackageRepository(),
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false);
// Act & Assert
ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(package), "Unable to resolve dependency 'B'.");
}
[Fact]
public void ResolveDependenciesForInstallPackageResolvesDependencyUsingDependencyProvider()
{
// Arrange
IPackage packageA = PackageUtility.CreatePackage("A",
"1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B")
});
IPackage packageB = PackageUtility.CreatePackage("B");
var repository = new Mock<PackageRepositoryBase>();
repository.Setup(c => c.GetPackages()).Returns(new[] { packageA }.AsQueryable());
var dependencyProvider = repository.As<IDependencyResolver>();
dependencyProvider.Setup(c => c.ResolveDependency(It.Is<PackageDependency>(p => p.Id == "B"), It.IsAny<IPackageConstraintProvider>(), false, true))
.Returns(packageB).Verifiable();
var localRepository = new MockPackageRepository();
IPackageOperationResolver resolver = new InstallWalker(localRepository,
repository.Object,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false);
// Act
var operations = resolver.ResolveOperations(packageA).ToList();
// Assert
Assert.Equal(2, operations.Count);
Assert.Equal(PackageAction.Install, operations.First().Action);
Assert.Equal(packageB, operations.First().Package);
Assert.Equal(PackageAction.Install, operations.Last().Action);
Assert.Equal(packageA, operations.Last().Package);
dependencyProvider.Verify();
}
[Fact]
public void ResolveDependenciesForInstallPackageResolvesDependencyWithConstraintsUsingDependencyResolver()
{
// Arrange
var packageDependency = new PackageDependency("B", new VersionSpec { MinVersion = new SemanticVersion("1.1") });
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> { packageDependency });
IPackage packageB12 = PackageUtility.CreatePackage("B", "1.2");
var repository = new Mock<PackageRepositoryBase>(MockBehavior.Strict);
repository.Setup(c => c.GetPackages()).Returns(new[] { packageA }.AsQueryable());
var dependencyProvider = repository.As<IDependencyResolver>();
dependencyProvider.Setup(c => c.ResolveDependency(packageDependency, It.IsAny<IPackageConstraintProvider>(), false, true))
.Returns(packageB12).Verifiable();
var localRepository = new MockPackageRepository();
IPackageOperationResolver resolver = new InstallWalker(localRepository,
repository.Object,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false);
// Act
var operations = resolver.ResolveOperations(packageA).ToList();
// Assert
Assert.Equal(2, operations.Count);
Assert.Equal(PackageAction.Install, operations.First().Action);
Assert.Equal(packageB12, operations.First().Package);
Assert.Equal(PackageAction.Install, operations.Last().Action);
Assert.Equal(packageA, operations.Last().Package);
dependencyProvider.Verify();
}
[Fact]
public void ResolveDependenciesForInstallCircularReferenceThrows()
{
// Arrange
var localRepository = new MockPackageRepository();
var sourceRepository = new MockPackageRepository();
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B")
});
IPackage packageB = PackageUtility.CreatePackage("B", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("A")
});
sourceRepository.AddPackage(packageA);
sourceRepository.AddPackage(packageB);
IPackageOperationResolver resolver = new InstallWalker(localRepository,
sourceRepository,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false);
// Act & Assert
ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageA), "Circular dependency detected 'A 1.0 => B 1.0 => A 1.0'.");
}
[Fact]
public void ResolveDependenciesForInstallDiamondDependencyGraph()
{
// Arrange
var localRepository = new MockPackageRepository();
var sourceRepository = new MockPackageRepository();
// A -> [B, C]
// B -> [D]
// C -> [D]
// A
// / \
// B C
// \ /
// D
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B"),
new PackageDependency("C")
});
IPackage packageB = PackageUtility.CreatePackage("B", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("D")
});
IPackage packageC = PackageUtility.CreatePackage("C", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("D")
});
IPackage packageD = PackageUtility.CreatePackage("D", "1.0");
sourceRepository.AddPackage(packageA);
sourceRepository.AddPackage(packageB);
sourceRepository.AddPackage(packageC);
sourceRepository.AddPackage(packageD);
IPackageOperationResolver resolver = new InstallWalker(localRepository,
sourceRepository,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false);
// Act
var packages = resolver.ResolveOperations(packageA).ToList();
// Assert
var dict = packages.ToDictionary(p => p.Package.Id);
Assert.Equal(4, packages.Count);
Assert.NotNull(dict["A"]);
Assert.NotNull(dict["B"]);
Assert.NotNull(dict["C"]);
Assert.NotNull(dict["D"]);
}
[Fact]
public void ResolveDependenciesForInstallDiamondDependencyGraphWithDifferntVersionOfSamePackage()
{
// Arrange
var localRepository = new MockPackageRepository();
var sourceRepository = new MockPackageRepository();
// A -> [B, C]
// B -> [D >= 1, E >= 2]
// C -> [D >= 2, E >= 1]
// A
// / \
// B C
// | \ | \
// D1 E2 D2 E1
IPackage packageA = PackageUtility.CreateProjectLevelPackage("A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B"),
new PackageDependency("C")
});
IPackage packageB = PackageUtility.CreateProjectLevelPackage("B", "1.0",
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("D", "1.0"),
PackageDependency.CreateDependency("E", "2.0")
});
IPackage packageC = PackageUtility.CreateProjectLevelPackage("C", "1.0",
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("D", "2.0"),
PackageDependency.CreateDependency("E", "1.0")
});
IPackage packageD10 = PackageUtility.CreateProjectLevelPackage("D", "1.0");
IPackage packageD20 = PackageUtility.CreateProjectLevelPackage("D", "2.0");
IPackage packageE10 = PackageUtility.CreateProjectLevelPackage("E", "1.0");
IPackage packageE20 = PackageUtility.CreateProjectLevelPackage("E", "2.0");
sourceRepository.AddPackage(packageA);
sourceRepository.AddPackage(packageB);
sourceRepository.AddPackage(packageC);
sourceRepository.AddPackage(packageD20);
sourceRepository.AddPackage(packageD10);
sourceRepository.AddPackage(packageE20);
sourceRepository.AddPackage(packageE10);
IPackageOperationResolver resolver = new InstallWalker(localRepository,
sourceRepository,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false);
// Act
var operations = resolver.ResolveOperations(packageA).ToList();
var projectOperations = resolver.ResolveOperations(packageA).ToList();
// Assert
Assert.Equal(5, operations.Count);
Assert.Equal("E", operations[0].Package.Id);
Assert.Equal(new SemanticVersion("2.0"), operations[0].Package.Version);
Assert.Equal("B", operations[1].Package.Id);
Assert.Equal("D", operations[2].Package.Id);
Assert.Equal(new SemanticVersion("2.0"), operations[2].Package.Version);
Assert.Equal("C", operations[3].Package.Id);
Assert.Equal("A", operations[4].Package.Id);
Assert.Equal(5, projectOperations.Count);
Assert.Equal("E", projectOperations[0].Package.Id);
Assert.Equal(new SemanticVersion("2.0"), projectOperations[0].Package.Version);
Assert.Equal("B", projectOperations[1].Package.Id);
Assert.Equal("D", projectOperations[2].Package.Id);
Assert.Equal(new SemanticVersion("2.0"), projectOperations[2].Package.Version);
Assert.Equal("C", projectOperations[3].Package.Id);
Assert.Equal("A", projectOperations[4].Package.Id);
}
[Fact]
public void UninstallWalkerIgnoresMissingDependencies()
{
// Arrange
var localRepository = new MockPackageRepository();
// A -> [B, C]
// B -> [D]
// C -> [D]
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B"),
new PackageDependency("C")
});
IPackage packageC = PackageUtility.CreatePackage("C", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("D")
});
IPackage packageD = PackageUtility.CreatePackage("D", "1.0");
localRepository.AddPackage(packageA);
localRepository.AddPackage(packageC);
localRepository.AddPackage(packageD);
IPackageOperationResolver resolver = new UninstallWalker(localRepository,
new DependentsWalker(localRepository),
NullLogger.Instance,
removeDependencies: true,
forceRemove: false);
// Act
var packages = resolver.ResolveOperations(packageA)
.ToDictionary(p => p.Package.Id);
// Assert
Assert.Equal(3, packages.Count);
Assert.NotNull(packages["A"]);
Assert.NotNull(packages["C"]);
Assert.NotNull(packages["D"]);
}
[Fact]
public void ResolveDependenciesForUninstallDiamondDependencyGraph()
{
// Arrange
var localRepository = new MockPackageRepository();
// A -> [B, C]
// B -> [D]
// C -> [D]
// A
// / \
// B C
// \ /
// D
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B"),
new PackageDependency("C")
});
IPackage packageB = PackageUtility.CreatePackage("B", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("D")
});
IPackage packageC = PackageUtility.CreatePackage("C", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("D")
});
IPackage packageD = PackageUtility.CreatePackage("D", "1.0");
localRepository.AddPackage(packageA);
localRepository.AddPackage(packageB);
localRepository.AddPackage(packageC);
localRepository.AddPackage(packageD);
IPackageOperationResolver resolver = new UninstallWalker(localRepository,
new DependentsWalker(localRepository),
NullLogger.Instance,
removeDependencies: true,
forceRemove: false);
// Act
var packages = resolver.ResolveOperations(packageA)
.ToDictionary(p => p.Package.Id);
// Assert
Assert.Equal(4, packages.Count);
Assert.NotNull(packages["A"]);
Assert.NotNull(packages["B"]);
Assert.NotNull(packages["C"]);
Assert.NotNull(packages["D"]);
}
[Fact]
public void ResolveDependencyForInstallCircularReferenceWithDifferentVersionOfPackageReferenceThrows()
{
// Arrange
var localRepository = new MockPackageRepository();
var sourceRepository = new MockPackageRepository();
IPackage packageA10 = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B")
});
IPackage packageA15 = PackageUtility.CreatePackage("A", "1.5",
dependencies: new List<PackageDependency> {
new PackageDependency("B")
});
IPackage packageB10 = PackageUtility.CreatePackage("B", "1.0",
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("A", "[1.5]")
});
sourceRepository.AddPackage(packageA10);
sourceRepository.AddPackage(packageA15);
sourceRepository.AddPackage(packageB10);
IPackageOperationResolver resolver = new InstallWalker(localRepository,
sourceRepository,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false);
// Act & Assert
ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageA10), "Circular dependency detected 'A 1.0 => B 1.0 => A 1.5'.");
}
[Fact]
public void ResolvingDependencyForUpdateWithConflictingDependents()
{
// Arrange
var localRepository = new MockPackageRepository();
var sourceRepository = new MockPackageRepository();
// A 1.0 -> B [1.0]
IPackage A10 = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "[1.0]")
}, content: new[] { "a1" });
// A 2.0 -> B (any version)
IPackage A20 = PackageUtility.CreatePackage("A", "2.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B")
}, content: new[] { "a2" });
IPackage B10 = PackageUtility.CreatePackage("B", "1.0", content: new[] { "b1" });
IPackage B101 = PackageUtility.CreatePackage("B", "1.0.1", content: new[] { "b101" });
IPackage B20 = PackageUtility.CreatePackage("B", "2.0", content: new[] { "a2" });
localRepository.Add(A10);
localRepository.Add(B10);
sourceRepository.AddPackage(A10);
sourceRepository.AddPackage(A20);
sourceRepository.AddPackage(B10);
sourceRepository.AddPackage(B101);
sourceRepository.AddPackage(B20);
IPackageOperationResolver resolver = new UpdateWalker(localRepository,
sourceRepository,
new DependentsWalker(localRepository),
NullConstraintProvider.Instance,
NullLogger.Instance,
updateDependencies: true,
allowPrereleaseVersions: false) { AcceptedTargets = PackageTargets.Project };
// Act
var packages = resolver.ResolveOperations(B101).ToList();
// Assert
Assert.Equal(4, packages.Count);
AssertOperation("A", "1.0", PackageAction.Uninstall, packages[0]);
AssertOperation("B", "1.0", PackageAction.Uninstall, packages[1]);
AssertOperation("A", "2.0", PackageAction.Install, packages[2]);
AssertOperation("B", "1.0.1", PackageAction.Install, packages[3]);
}
[Fact]
public void ResolvingDependencyForUpdateThatHasAnUnsatisfiedConstraint()
{
// Arrange
var localRepository = new MockPackageRepository();
var sourceRepository = new MockPackageRepository();
var constraintProvider = new Mock<IPackageConstraintProvider>();
constraintProvider.Setup(m => m.GetConstraint("B")).Returns(VersionUtility.ParseVersionSpec("[1.4]"));
constraintProvider.Setup(m => m.Source).Returns("foo");
IPackage A10 = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "1.5")
});
IPackage A20 = PackageUtility.CreatePackage("A", "2.0",
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "2.0")
});
IPackage B15 = PackageUtility.CreatePackage("B", "1.5");
IPackage B20 = PackageUtility.CreatePackage("B", "2.0");
localRepository.Add(A10);
localRepository.Add(B15);
sourceRepository.AddPackage(A10);
sourceRepository.AddPackage(A20);
sourceRepository.AddPackage(B15);
sourceRepository.AddPackage(B20);
IPackageOperationResolver resolver = new InstallWalker(localRepository,
sourceRepository,
constraintProvider.Object,
null,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false);
// Act & Assert
ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(A20), "Unable to resolve dependency 'B (\u2265 2.0)'.'B' has an additional constraint (= 1.4) defined in foo.");
}
[Fact]
public void ResolveDependencyForInstallPackageWithDependencyThatDoesntMeetMinimumVersionThrows()
{
// Arrange
var localRepository = new MockPackageRepository();
var sourceRepository = new MockPackageRepository();
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "1.5")
});
IPackage packageB = PackageUtility.CreatePackage("B", "1.4");
sourceRepository.AddPackage(packageA);
sourceRepository.AddPackage(packageB);
IPackageOperationResolver resolver = new InstallWalker(localRepository,
sourceRepository,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false);
// Act & Assert
ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageA), "Unable to resolve dependency 'B (\u2265 1.5)'.");
}
[Fact]
public void ResolveDependencyForInstallPackageWithDependencyThatDoesntMeetExactVersionThrows()
{
// Arrange
var localRepository = new MockPackageRepository();
var sourceRepository = new MockPackageRepository();
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "[1.5]")
});
sourceRepository.AddPackage(packageA);
IPackage packageB = PackageUtility.CreatePackage("B", "1.4");
sourceRepository.AddPackage(packageB);
IPackageOperationResolver resolver = new InstallWalker(localRepository,
sourceRepository,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false);
// Act & Assert
ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageA), "Unable to resolve dependency 'B (= 1.5)'.");
}
[Fact]
public void ResolveOperationsForInstallSameDependencyAtDifferentLevelsInGraph()
{
// Arrange
var localRepository = new MockPackageRepository();
var sourceRepository = new MockPackageRepository();
// A1 -> B1, C1
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "1.0"),
PackageDependency.CreateDependency("C", "1.0")
});
// B1
IPackage packageB = PackageUtility.CreatePackage("B", "1.0");
// C1 -> B1, D1
IPackage packageC = PackageUtility.CreatePackage("C", "1.0",
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "1.0"),
PackageDependency.CreateDependency("D", "1.0")
});
// D1 -> B1
IPackage packageD = PackageUtility.CreatePackage("D", "1.0",
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "1.0")
});
sourceRepository.AddPackage(packageA);
sourceRepository.AddPackage(packageB);
sourceRepository.AddPackage(packageC);
sourceRepository.AddPackage(packageD);
IPackageOperationResolver resolver = new InstallWalker(localRepository,
sourceRepository,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false);
// Act & Assert
var packages = resolver.ResolveOperations(packageA).ToList();
Assert.Equal(4, packages.Count);
Assert.Equal("B", packages[0].Package.Id);
Assert.Equal("D", packages[1].Package.Id);
Assert.Equal("C", packages[2].Package.Id);
Assert.Equal("A", packages[3].Package.Id);
}
[Fact]
public void ResolveDependenciesForInstallSameDependencyAtDifferentLevelsInGraphDuringUpdate()
{
// Arrange
var localRepository = new MockPackageRepository();
var sourceRepository = new MockPackageRepository();
// A1 -> B1, C1
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
content: new[] { "A1" },
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "1.0"),
PackageDependency.CreateDependency("C", "1.0")
});
// B1
IPackage packageB = PackageUtility.CreatePackage("B", "1.0", new[] { "B1" });
// C1 -> B1, D1
IPackage packageC = PackageUtility.CreatePackage("C", "1.0",
content: new[] { "C1" },
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "1.0"),
PackageDependency.CreateDependency("D", "1.0")
});
// D1 -> B1
IPackage packageD = PackageUtility.CreatePackage("D", "1.0",
content: new[] { "A1" },
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "1.0")
});
// A2 -> B2, C2
IPackage packageA2 = PackageUtility.CreatePackage("A", "2.0",
content: new[] { "A2" },
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "2.0"),
PackageDependency.CreateDependency("C", "2.0")
});
// B2
IPackage packageB2 = PackageUtility.CreatePackage("B", "2.0", new[] { "B2" });
// C2 -> B2, D2
IPackage packageC2 = PackageUtility.CreatePackage("C", "2.0",
content: new[] { "C2" },
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "2.0"),
PackageDependency.CreateDependency("D", "2.0")
});
// D2 -> B2
IPackage packageD2 = PackageUtility.CreatePackage("D", "2.0",
content: new[] { "D2" },
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "2.0")
});
sourceRepository.AddPackage(packageA);
sourceRepository.AddPackage(packageB);
sourceRepository.AddPackage(packageC);
sourceRepository.AddPackage(packageD);
sourceRepository.AddPackage(packageA2);
sourceRepository.AddPackage(packageB2);
sourceRepository.AddPackage(packageC2);
sourceRepository.AddPackage(packageD2);
localRepository.AddPackage(packageA);
localRepository.AddPackage(packageB);
localRepository.AddPackage(packageC);
localRepository.AddPackage(packageD);
IPackageOperationResolver resolver = new UpdateWalker(localRepository,
sourceRepository,
new DependentsWalker(localRepository),
NullConstraintProvider.Instance,
NullLogger.Instance,
updateDependencies: true,
allowPrereleaseVersions: false);
var operations = resolver.ResolveOperations(packageA2).ToList();
Assert.Equal(8, operations.Count);
AssertOperation("A", "1.0", PackageAction.Uninstall, operations[0]);
AssertOperation("C", "1.0", PackageAction.Uninstall, operations[1]);
AssertOperation("D", "1.0", PackageAction.Uninstall, operations[2]);
AssertOperation("B", "1.0", PackageAction.Uninstall, operations[3]);
AssertOperation("B", "2.0", PackageAction.Install, operations[4]);
AssertOperation("D", "2.0", PackageAction.Install, operations[5]);
AssertOperation("C", "2.0", PackageAction.Install, operations[6]);
AssertOperation("A", "2.0", PackageAction.Install, operations[7]);
}
[Fact]
public void ResolveDependenciesForInstallPackageWithDependencyReturnsPackageAndDependency()
{
// Arrange
var localRepository = new MockPackageRepository();
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B")
});
IPackage packageB = PackageUtility.CreatePackage("B", "1.0");
localRepository.AddPackage(packageA);
localRepository.AddPackage(packageB);
IPackageOperationResolver resolver = new UninstallWalker(localRepository,
new DependentsWalker(localRepository),
NullLogger.Instance,
removeDependencies: true,
forceRemove: false);
// Act
var packages = resolver.ResolveOperations(packageA)
.ToDictionary(p => p.Package.Id);
// Assert
Assert.Equal(2, packages.Count);
Assert.NotNull(packages["A"]);
Assert.NotNull(packages["B"]);
}
[Fact]
public void ResolveDependenciesForUninstallPackageWithDependentThrows()
{
// Arrange
var localRepository = new MockPackageRepository();
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B")
});
IPackage packageB = PackageUtility.CreatePackage("B", "1.0");
localRepository.AddPackage(packageA);
localRepository.AddPackage(packageB);
IPackageOperationResolver resolver = new UninstallWalker(localRepository,
new DependentsWalker(localRepository),
NullLogger.Instance,
removeDependencies: false,
forceRemove: false);
// Act & Assert
ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageB), "Unable to uninstall 'B 1.0' because 'A 1.0' depends on it.");
}
[Fact]
public void ResolveDependenciesForUninstallPackageWithDependentAndRemoveDependenciesThrows()
{
// Arrange
var localRepository = new MockPackageRepository();
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B")
});
IPackage packageB = PackageUtility.CreatePackage("B", "1.0");
localRepository.AddPackage(packageA);
localRepository.AddPackage(packageB);
IPackageOperationResolver resolver = new UninstallWalker(localRepository,
new DependentsWalker(localRepository),
NullLogger.Instance,
removeDependencies: true,
forceRemove: false);
// Act & Assert
ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageB), "Unable to uninstall 'B 1.0' because 'A 1.0' depends on it.");
}
[Fact]
public void ResolveDependenciesForUninstallPackageWithDependentAndForceReturnsPackage()
{
// Arrange
var localRepository = new MockPackageRepository();
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B")
});
IPackage packageB = PackageUtility.CreatePackage("B", "1.0");
localRepository.AddPackage(packageA);
localRepository.AddPackage(packageB);
IPackageOperationResolver resolver = new UninstallWalker(localRepository,
new DependentsWalker(localRepository),
NullLogger.Instance,
removeDependencies: false,
forceRemove: true);
// Act
var packages = resolver.ResolveOperations(packageB)
.ToDictionary(p => p.Package.Id);
// Assert
Assert.Equal(1, packages.Count);
Assert.NotNull(packages["B"]);
}
[Fact]
public void ResolveDependenciesForUninstallPackageWithRemoveDependenciesExcludesDependencyIfDependencyInUse()
{
// Arrange
var localRepository = new MockPackageRepository();
// A 1.0 -> [B, C]
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B"),
new PackageDependency("C")
});
IPackage packageB = PackageUtility.CreatePackage("B", "1.0");
IPackage packageC = PackageUtility.CreatePackage("C", "1.0");
// D -> [C]
IPackage packageD = PackageUtility.CreatePackage("D", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("C"),
});
localRepository.AddPackage(packageD);
localRepository.AddPackage(packageA);
localRepository.AddPackage(packageB);
localRepository.AddPackage(packageC);
IPackageOperationResolver resolver = new UninstallWalker(localRepository,
new DependentsWalker(localRepository),
NullLogger.Instance,
removeDependencies: true,
forceRemove: false);
// Act
var packages = resolver.ResolveOperations(packageA)
.ToDictionary(p => p.Package.Id);
// Assert
Assert.Equal(2, packages.Count);
Assert.NotNull(packages["A"]);
Assert.NotNull(packages["B"]);
}
[Fact]
public void ResolveDependenciesForUninstallPackageWithRemoveDependenciesSetAndForceReturnsAllDependencies()
{
// Arrange
var localRepository = new MockPackageRepository();
// A 1.0 -> [B, C]
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B"),
new PackageDependency("C")
});
IPackage packageB = PackageUtility.CreatePackage("B", "1.0");
IPackage packageC = PackageUtility.CreatePackage("C", "1.0");
// D -> [C]
IPackage packageD = PackageUtility.CreatePackage("D", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("C"),
});
localRepository.AddPackage(packageA);
localRepository.AddPackage(packageB);
localRepository.AddPackage(packageC);
localRepository.AddPackage(packageD);
IPackageOperationResolver resolver = new UninstallWalker(localRepository,
new DependentsWalker(localRepository),
NullLogger.Instance,
removeDependencies: true,
forceRemove: true);
// Act
var packages = resolver.ResolveOperations(packageA)
.ToDictionary(p => p.Package.Id);
// Assert
Assert.NotNull(packages["A"]);
Assert.NotNull(packages["B"]);
Assert.NotNull(packages["C"]);
}
[Fact]
public void ProjectInstallWalkerIgnoresSolutionLevelPackages()
{
// Arrange
var localRepository = new MockPackageRepository();
var sourceRepository = new MockPackageRepository();
IPackage projectPackage = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "[1.5]")
}, content: new[] { "content" });
sourceRepository.AddPackage(projectPackage);
IPackage toolsPackage = PackageUtility.CreatePackage("B", "1.5", tools: new[] { "init.ps1" });
sourceRepository.AddPackage(toolsPackage);
IPackageOperationResolver resolver = new UpdateWalker(localRepository,
sourceRepository,
new DependentsWalker(localRepository),
NullConstraintProvider.Instance,
NullLogger.Instance,
updateDependencies: true,
allowPrereleaseVersions: false) { AcceptedTargets = PackageTargets.Project };
// Act
var packages = resolver.ResolveOperations(projectPackage)
.ToDictionary(p => p.Package.Id);
// Assert
Assert.Equal(1, packages.Count);
Assert.NotNull(packages["A"]);
}
[Fact]
public void AfterPackageWalkMetaPackageIsClassifiedTheSameAsDependencies()
{
// Arrange
var mockRepository = new MockPackageRepository();
var walker = new TestWalker(mockRepository);
IPackage metaPackage = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B"),
new PackageDependency("C")
});
IPackage projectPackageA = PackageUtility.CreatePackage("B", "1.0", content: new[] { "contentB" });
IPackage projectPackageB = PackageUtility.CreatePackage("C", "1.0", content: new[] { "contentC" });
mockRepository.AddPackage(projectPackageA);
mockRepository.AddPackage(projectPackageB);
Assert.Equal(PackageTargets.None, walker.GetPackageInfo(metaPackage).Target);
// Act
walker.Walk(metaPackage);
// Assert
Assert.Equal(PackageTargets.Project, walker.GetPackageInfo(metaPackage).Target);
}
[Fact]
public void LocalizedIntelliSenseFileCountsAsProjectTarget()
{
// Arrange
var mockRepository = new MockPackageRepository();
var walker = new TestWalker(mockRepository);
IPackage runtimePackage = PackageUtility.CreatePackage("A", "1.0",
assemblyReferences: new[] { @"lib\A.dll", @"lib\A.xml" });
IPackage satellitePackage = PackageUtility.CreatePackage("A.fr-fr", "1.0",
dependencies: new[] { new PackageDependency("A") },
satelliteAssemblies: new[] { @"lib\fr-fr\A.xml" },
language: "fr-fr");
mockRepository.AddPackage(runtimePackage);
mockRepository.AddPackage(satellitePackage);
// Act
walker.Walk(satellitePackage);
// Assert
Assert.Equal(PackageTargets.Project, walker.GetPackageInfo(satellitePackage).Target);
}
[Fact]
public void AfterPackageWalkSatellitePackageIsClassifiedTheSameAsDependencies()
{
// Arrange
var mockRepository = new MockPackageRepository();
var walker = new TestWalker(mockRepository);
IPackage runtimePackage = PackageUtility.CreatePackage("A", "1.0",
assemblyReferences: new[] { @"lib\A.dll" });
IPackage satellitePackage = PackageUtility.CreatePackage("A.fr-fr", "1.0",
dependencies: new[] { new PackageDependency("A") },
satelliteAssemblies: new[] { @"lib\fr-fr\A.resources.dll" },
language: "fr-fr");
mockRepository.AddPackage(runtimePackage);
mockRepository.AddPackage(satellitePackage);
// Act
walker.Walk(satellitePackage);
// Assert
Assert.Equal(PackageTargets.Project, walker.GetPackageInfo(satellitePackage).Target);
}
[Fact]
public void MetaPackageWithMixedTargetsThrows()
{
// Arrange
var mockRepository = new MockPackageRepository();
var walker = new TestWalker(mockRepository);
IPackage metaPackage = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B"),
new PackageDependency("C")
});
IPackage projectPackageA = PackageUtility.CreatePackage("B", "1.0", content: new[] { "contentB" });
IPackage solutionPackage = PackageUtility.CreatePackage("C", "1.0", tools: new[] { "tools" });
mockRepository.AddPackage(projectPackageA);
mockRepository.AddPackage(solutionPackage);
// Act && Assert
ExceptionAssert.Throws<InvalidOperationException>(() => walker.Walk(metaPackage), "Child dependencies of dependency only packages cannot mix external and project packages.");
}
[Fact]
public void ExternalPackagesThatDepdendOnProjectLevelPackagesThrows()
{
// Arrange
var mockRepository = new MockPackageRepository();
var walker = new TestWalker(mockRepository);
IPackage solutionPackage = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B")
}, tools: new[] { "install.ps1" });
IPackage projectPackageA = PackageUtility.CreatePackage("B", "1.0", content: new[] { "contentB" });
mockRepository.AddPackage(projectPackageA);
mockRepository.AddPackage(solutionPackage);
// Act && Assert
ExceptionAssert.Throws<InvalidOperationException>(() => walker.Walk(solutionPackage), "External packages cannot depend on packages that target projects.");
}
[Fact]
public void InstallWalkerResolvesLowestMajorAndMinorVersionForDependencies()
{
// Arrange
// A 1.0 -> B 1.0
// B 1.0 -> C 1.1
// C 1.1 -> D 1.0
var A10 = PackageUtility.CreatePackage("A", "1.0", dependencies: new[] { PackageDependency.CreateDependency("B", "1.0") });
var repository = new MockPackageRepository() {
PackageUtility.CreatePackage("B", "2.0", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }),
PackageUtility.CreatePackage("B", "1.0", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }),
PackageUtility.CreatePackage("B", "1.0.1"),
A10,
PackageUtility.CreatePackage("D", "2.0"),
PackageUtility.CreatePackage("C", "1.1.3", dependencies: new[] { PackageDependency.CreateDependency("D", "1.0") }),
PackageUtility.CreatePackage("C", "1.1.1", dependencies: new[] { PackageDependency.CreateDependency("D", "1.0") }),
PackageUtility.CreatePackage("C", "1.5.1", dependencies: new[] { PackageDependency.CreateDependency("D", "1.0") }),
PackageUtility.CreatePackage("B", "1.0.9", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }),
PackageUtility.CreatePackage("B", "1.1", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") })
};
IPackageOperationResolver resolver = new InstallWalker(new MockPackageRepository(),
repository,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false);
// Act
var packages = resolver.ResolveOperations(A10).ToList();
// Assert
Assert.Equal(4, packages.Count);
Assert.Equal("D", packages[0].Package.Id);
Assert.Equal(new SemanticVersion("2.0"), packages[0].Package.Version);
Assert.Equal("C", packages[1].Package.Id);
Assert.Equal(new SemanticVersion("1.1.1"), packages[1].Package.Version);
Assert.Equal("B", packages[2].Package.Id);
Assert.Equal(new SemanticVersion("1.0"), packages[2].Package.Version);
Assert.Equal("A", packages[3].Package.Id);
Assert.Equal(new SemanticVersion("1.0"), packages[3].Package.Version);
}
[Fact]
public void InstallWalkerResolvesLowestMajorAndMinorVersionOfListedPackagesForDependencies()
{
// Arrange
// A 1.0 -> B 1.0
// B 1.0 -> C 1.1
// C 1.1 -> D 1.0
var A10 = PackageUtility.CreatePackage("A", "1.0", dependencies: new[] { PackageDependency.CreateDependency("B", "1.0") });
var repository = new MockPackageRepository() {
PackageUtility.CreatePackage("B", "2.0", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }),
PackageUtility.CreatePackage("B", "1.0", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }, listed: false),
PackageUtility.CreatePackage("B", "1.0.1"),
A10,
PackageUtility.CreatePackage("D", "2.0"),
PackageUtility.CreatePackage("C", "1.1.3", dependencies: new[] { PackageDependency.CreateDependency("D", "1.0") }),
PackageUtility.CreatePackage("C", "1.1.1", dependencies: new[] { PackageDependency.CreateDependency("D", "1.0") }, listed: false),
PackageUtility.CreatePackage("C", "1.5.1", dependencies: new[] { PackageDependency.CreateDependency("D", "1.0") }),
PackageUtility.CreatePackage("B", "1.0.9", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }),
PackageUtility.CreatePackage("B", "1.1", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") })
};
IPackageOperationResolver resolver = new InstallWalker(new MockPackageRepository(),
repository,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false);
// Act
var packages = resolver.ResolveOperations(A10).ToList();
// Assert
Assert.Equal(2, packages.Count);
Assert.Equal("B", packages[0].Package.Id);
Assert.Equal(new SemanticVersion("1.0.1"), packages[0].Package.Version);
Assert.Equal("A", packages[1].Package.Id);
Assert.Equal(new SemanticVersion("1.0"), packages[1].Package.Version);
}
private void AssertOperation(string expectedId, string expectedVersion, PackageAction expectedAction, PackageOperation operation)
{
Assert.Equal(expectedAction, operation.Action);
Assert.Equal(expectedId, operation.Package.Id);
Assert.Equal(new SemanticVersion(expectedVersion), operation.Package.Version);
}
private class TestWalker : PackageWalker
{
private readonly IPackageRepository _repository;
public TestWalker(IPackageRepository repository)
{
_repository = repository;
}
protected override IPackage ResolveDependency(PackageDependency dependency)
{
return _repository.ResolveDependency(dependency, AllowPrereleaseVersions, false);
}
}
}
}
| |
using System;
using System.Collections.Specialized;
using System.Net;
using System.Web;
using Skybrud.Social.Http;
using Skybrud.Social.Instagram.Endpoints.Raw;
using Skybrud.Social.Instagram.Responses;
using Skybrud.Social.Interfaces;
using Skybrud.Social.Json;
namespace Skybrud.Social.Instagram.OAuth {
/// <summary>
/// Class for handling the raw communication with the Instagram API as well
/// as any OAuth 2.0 communication/authentication.
/// </summary>
public class InstagramOAuthClient {
#region Private fields
private InstagramLocationsRawEndpoint _locations;
private InstagramMediaRawEndpoint _media;
private InstagramRelationshipsRawEndpoint _relationships;
private InstagramTagsRawEndpoint _tags;
private InstagramUsersRawEndpoint _users;
#endregion
#region Properties
/// <summary>
/// The ID of the app/client.
/// </summary>
public string ClientId { get; set; }
/// <summary>
/// The secret of the app/client.
/// </summary>
public string ClientSecret { get; set; }
/// <summary>
/// The redirect URI of your application.
/// </summary>
[Obsolete("Use \"RedirectUri\" instead to follow Instagram lingo.")]
public string ReturnUri {
get { return RedirectUri; }
set { RedirectUri = value; }
}
/// <summary>
/// The redirect URI of your application.
/// </summary>
public string RedirectUri { get; set; }
/// <summary>
/// The access token.
/// </summary>
public string AccessToken { get; set; }
/// <summary>
/// Gets a reference to the locations endpoint.
/// </summary>
public InstagramLocationsRawEndpoint Locations {
get { return _locations ?? (_locations = new InstagramLocationsRawEndpoint(this)); }
}
/// <summary>
/// Gets a reference to the media endpoint.
/// </summary>
public InstagramMediaRawEndpoint Media {
get { return _media ?? (_media = new InstagramMediaRawEndpoint(this)); }
}
/// <summary>
/// Gets a reference to the relationships endpoint.
/// </summary>
public InstagramRelationshipsRawEndpoint Relationships {
get { return _relationships ?? (_relationships = new InstagramRelationshipsRawEndpoint(this)); }
}
/// <summary>
/// Gets a reference to the tags endpoint.
/// </summary>
public InstagramTagsRawEndpoint Tags {
get { return _tags ?? (_tags = new InstagramTagsRawEndpoint(this)); }
}
/// <summary>
/// Gets a reference to the users endpoint.
/// </summary>
public InstagramUsersRawEndpoint Users {
get { return _users ?? (_users = new InstagramUsersRawEndpoint(this)); }
}
#endregion
#region Constructors
/// <summary>
/// Initializes an OAuth client with empty information.
/// </summary>
public InstagramOAuthClient() {
// default constructor
}
/// <summary>
/// Initializes an OAuth client with the specified access token. Using this initializer,
/// the client will have no information about your app.
/// </summary>
/// <param name="accessToken">A valid access token.</param>
public InstagramOAuthClient(string accessToken) {
AccessToken = accessToken;
}
/// <summary>
/// Initializes an OAuth client with the specified app ID and app secret.
/// </summary>
/// <param name="appId">The ID of the app.</param>
/// <param name="appSecret">The secret of the app.</param>
public InstagramOAuthClient(long appId, string appSecret) {
ClientId = appId + "";
ClientSecret = appSecret;
}
/// <summary>
/// Initializes an OAuth client with the specified app ID, app secret and return URI.
/// </summary>
/// <param name="appId">The ID of the app.</param>
/// <param name="appSecret">The secret of the app.</param>
/// <param name="redirectUri">The return URI of the app.</param>
public InstagramOAuthClient(long appId, string appSecret, string redirectUri) {
ClientId = appId + "";
ClientSecret = appSecret;
RedirectUri = redirectUri;
}
/// <summary>
/// Initializes an OAuth client with the specified app ID and app secret.
/// </summary>
/// <param name="appId">The ID of the app.</param>
/// <param name="appSecret">The secret of the app.</param>
public InstagramOAuthClient(string appId, string appSecret) {
ClientId = appId;
ClientSecret = appSecret;
}
/// <summary>
/// Initializes an OAuth client with the specified app ID, app secret and return URI.
/// </summary>
/// <param name="appId">The ID of the app.</param>
/// <param name="appSecret">The secret of the app.</param>
/// <param name="redirectUri">The return URI of the app.</param>
public InstagramOAuthClient(string appId, string appSecret, string redirectUri) {
ClientId = appId;
ClientSecret = appSecret;
RedirectUri = redirectUri;
}
#endregion
#region Methods
/// <summary>
/// Gets an authorization URL using the specified <var>state</var>.
/// This URL will only make your application request a basic scope.
/// </summary>
/// <param name="state">A unique state for the request.</param>
public string GetAuthorizationUrl(string state) {
return GetAuthorizationUrl(state, InstagramScope.Basic);
}
/// <summary>
/// Gets an authorization URL using the specified <var>state</var> and
/// request the specified <var>scope</var>.
/// </summary>
/// <param name="state">A unique state for the request.</param>
/// <param name="scope">The scope of your application.</param>
public string GetAuthorizationUrl(string state, InstagramScope scope) {
return String.Format(
"https://api.instagram.com/oauth/authorize/?client_id={0}&redirect_uri={1}&response_type=code&state={2}&scope={3}",
SocialUtils.UrlEncode(ClientId),
SocialUtils.UrlEncode(RedirectUri),
SocialUtils.UrlEncode(state),
SocialUtils.UrlEncode(scope.ToString().Replace(", ", "+").ToLower())
);
}
public InstagramAccessTokenResponse GetAccessTokenFromAuthCode(string authCode) {
// Initialize collection with POST data
NameValueCollection parameters = new NameValueCollection {
{"client_id", ClientId},
{"client_secret", ClientSecret},
{"grant_type", "authorization_code"},
{"redirect_uri", RedirectUri},
{"code", authCode }
};
// Make the call to the API
HttpWebResponse response = SocialUtils.DoHttpPostRequest("https://api.instagram.com/oauth/access_token", null, parameters);
// Wrap the native response class
SocialHttpResponse social = SocialHttpResponse.GetFromWebResponse(response);
// Parse the response
return InstagramAccessTokenResponse.ParseResponse(social);
}
/// <summary>
/// Makes an authenticated GET request to the specified URL. If an access token has been
/// specified for this client, that access token will be added to the query string.
/// Similar if a client ID has been specified instead of an access token, that client ID
/// will be added to the query string. However some endpoint methods may require an access
/// token, and a client ID will therefore not be sufficient for such methods.
/// </summary>
/// <param name="url">The URL to call.</param>
public SocialHttpResponse DoAuthenticatedGetRequest(string url) {
return DoAuthenticatedGetRequest(url, new NameValueCollection());
}
/// <summary>
/// Makes an authenticated GET request to the specified URL. If an access token has been
/// specified for this client, that access token will be added to the query string.
/// Similar if a client ID has been specified instead of an access token, that client ID
/// will be added to the query string. However some endpoint methods may require an access
/// token, and a client ID will therefore not be sufficient for such methods.
/// </summary>
/// <param name="url">The URL to call.</param>
/// <param name="query">The query string for the call.</param>
public SocialHttpResponse DoAuthenticatedGetRequest(string url, NameValueCollection query) {
return DoAuthenticatedGetRequest(url, new SocialQueryString(query));
}
/// <summary>
/// Makes an authenticated GET request to the specified URL. If an access token has been
/// specified for this client, that access token will be added to the query string.
/// Similar if a client ID has been specified instead of an access token, that client ID
/// will be added to the query string. However some endpoint methods may require an access
/// token, and a client ID will therefore not be sufficient for such methods.
/// </summary>
/// <param name="url">The URL to call.</param>
/// <param name="query">The query string for the call.</param>
public SocialHttpResponse DoAuthenticatedGetRequest(string url, IGetOptions query) {
return DoAuthenticatedGetRequest(url, query == null ? null : query.GetQueryString());
}
/// <summary>
/// Makes an authenticated GET request to the specified URL. If an access token has been
/// specified for this client, that access token will be added to the query string.
/// Similar if a client ID has been specified instead of an access token, that client ID
/// will be added to the query string. However some endpoint methods may require an access
/// token, and a client ID will therefore not be sufficient for such methods.
/// </summary>
/// <param name="url">The URL to call.</param>
/// <param name="query">The query string for the call.</param>
public SocialHttpResponse DoAuthenticatedGetRequest(string url, SocialQueryString query) {
// Throw an exception if the URL is empty
if (String.IsNullOrWhiteSpace(url)) throw new ArgumentNullException("url");
// Initialize a new instance of SocialQueryString if the one specified is NULL
if (query == null) query = new SocialQueryString();
// Append either the access token or the client ID to the query string
if (!String.IsNullOrWhiteSpace(AccessToken)) {
query.Add("access_token", AccessToken);
} else if (!String.IsNullOrWhiteSpace(ClientId)) {
query.Add("client_id", ClientId);
}
// Append the query string to the URL
if (!query.IsEmpty) url += (url.Contains("?") ? "&" : "?") + query;
// Initialize a new HTTP request
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
// Get the HTTP response
try {
return SocialHttpResponse.GetFromWebResponse(request.GetResponse() as HttpWebResponse);
} catch (WebException ex) {
if (ex.Status != WebExceptionStatus.ProtocolError) throw;
return SocialHttpResponse.GetFromWebResponse(ex.Response as HttpWebResponse);
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.UseThrowExpression;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.UseThrowExpression;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseThrowExpression
{
public partial class UseThrowExpressionTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpUseThrowExpressionDiagnosticAnalyzer(), new UseThrowExpressionCodeFixProvider());
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task WithoutBraces()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M(string s)
{
if (s == null)
[|throw|] new ArgumentNullException(nameof(s));
_s = s;
}
}",
@"using System;
class C
{
void M(string s)
{
_s = s ?? throw new ArgumentNullException(nameof(s));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task TestOnIf()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M(string s)
{
[|if|] (s == null)
throw new ArgumentNullException(nameof(s));
_s = s;
}
}",
@"using System;
class C
{
void M(string s)
{
_s = s ?? throw new ArgumentNullException(nameof(s));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task WithBraces()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M(string s)
{
if (s == null)
{
[|throw|] new ArgumentNullException(nameof(s));
}
_s = s;
}
}",
@"using System;
class C
{
void M(string s)
{
_s = s ?? throw new ArgumentNullException(nameof(s));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task TestNotOnAssign()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class C
{
void M(string s)
{
if (s == null)
throw new ArgumentNullException(nameof(s));
_s = [|s|];
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task OnlyInCSharp7AndHigher()
{
await TestMissingAsync(
@"using System;
class C
{
void M(string s)
{
if (s == null)
{
[|throw|] new ArgumentNullException(nameof(s)) };
_s = s;
}
}", new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task WithIntermediaryStatements()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M(string s, string t)
{
if (s == null)
{
[|throw|] new ArgumentNullException(nameof(s));
}
if (t == null)
{
throw new ArgumentNullException(nameof(t));
}
_s = s;
}
}",
@"using System;
class C
{
void M(string s, string t)
{
if (t == null)
{
throw new ArgumentNullException(nameof(t));
}
_s = s ?? throw new ArgumentNullException(nameof(s));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task NotWithIntermediaryWrite()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class C
{
void M(string s, string t)
{
if (s == null)
{
[|throw|] new ArgumentNullException(nameof(s));
};
s = ""something"";
_s = s;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task NotWithIntermediaryMemberAccess()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class C
{
void M(string s, string t)
{
if (s == null)
{
[|throw|] new ArgumentNullException(nameof(s));
};
s.ToString();
_s = s;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task TestNullCheckOnLeft()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M(string s)
{
if (null == s)
[|throw|] new ArgumentNullException(nameof(s));
_s = s;
}
}",
@"using System;
class C
{
void M(string s)
{
_s = s ?? throw new ArgumentNullException(nameof(s));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task TestWithLocal()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M()
{
string s = null;
if (null == s)
[|throw|] new ArgumentNullException(nameof(s));
_s = s;
}
}",
@"using System;
class C
{
void M()
{
string s = null;
_s = s ?? throw new ArgumentNullException(nameof(s));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task TestNotOnField()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class C
{
string s;
void M()
{
if (null == s)
[|throw|] new ArgumentNullException(nameof(s));
_s = s;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task TestAssignBeforeCheck()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class C
{
void M(string s)
{
_s = s;
if (s == null)
[|throw|] new ArgumentNullException(nameof(s));
}
}");
}
[WorkItem(16234, "https://github.com/dotnet/roslyn/issues/16234")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task TestNotInExpressionTree()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Linq.Expressions;
class C
{
private string _s;
void Foo()
{
Expression<Action<string>> e = s =>
{
if (s == null)
[|throw|] new ArgumentNullException(nameof(s));
_s = s;
};
}
}");
}
}
}
| |
/*
* REST API Documentation for Schoolbus
*
* API Sample
*
* OpenAPI spec version: v1
*
*
*/
using Newtonsoft.Json;
using SchoolBusAPI.Models;
using SchoolBusAPI.ViewModels;
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using Xunit;
namespace SchoolBusAPI.Test
{
public class UserApiIntegrationTest : ApiIntegrationTestBase
{
[Fact]
/// <summary>
/// Integration test for Users Bulk
/// </summary>
public async void TestUsersBulk()
{
var request = new HttpRequestMessage(HttpMethod.Post, "/api/users/bulk");
request.Content = new StringContent("[]", Encoding.UTF8, "application/json");
var response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
}
[Fact]
/// <summary>
/// Basic Integration test for Users
/// </summary>
public async void TestUsersBasic()
{
string initialName = "InitialName";
string changedName = "ChangedName";
// first test the POST.
var request = new HttpRequestMessage(HttpMethod.Post, "/api/users");
// create a new object.
UserViewModel user = new UserViewModel();
user.GivenName = initialName;
string jsonString = user.ToJson();
request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
var response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
user = JsonConvert.DeserializeObject<UserViewModel>(jsonString);
// get the id
var id = user.Id;
// change the name
user.GivenName = changedName;
// now do an update.
request = new HttpRequestMessage(HttpMethod.Put, "/api/users/" + id);
request.Content = new StringContent(user.ToJson(), Encoding.UTF8, "application/json");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// do a get.
request = new HttpRequestMessage(HttpMethod.Get, "/api/users/" + id);
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
user = JsonConvert.DeserializeObject<UserViewModel>(jsonString);
// verify the change went through.
Assert.Equal(user.GivenName, changedName);
// do a delete.
request = new HttpRequestMessage(HttpMethod.Post, "/api/users/" + id + "/delete");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// should get a 404 if we try a get now.
request = new HttpRequestMessage(HttpMethod.Get, "/api/users/" + id);
response = await _client.SendAsync(request);
Assert.Equal(response.StatusCode, HttpStatusCode.NotFound);
}
[Fact]
/// <summary>
/// Integration test for User Favourites.
/// </summary>
public async void TestUserFavorites()
{
string initialName = "InitialName";
// create a user.
var request = new HttpRequestMessage(HttpMethod.Post, "/api/users");
User user = new User();
user.GivenName = initialName;
string jsonString = user.ToJson();
request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
var response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
user = JsonConvert.DeserializeObject<User>(jsonString);
// get the id
var id = user.Id;
// add and associate the favourite
request = new HttpRequestMessage(HttpMethod.Post, "/api/users/" + id + "/favourites");
UserFavourite userFavourite = new UserFavourite();
userFavourite.User = user;
UserFavourite[] items = new UserFavourite[1];
items[0] = userFavourite;
jsonString = JsonConvert.SerializeObject(items, Formatting.Indented);
request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// verify the user has a favourite.
request = new HttpRequestMessage(HttpMethod.Get, "/api/users/" + id + "/favourites");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
items = JsonConvert.DeserializeObject<UserFavourite[]>(jsonString);
bool found = false;
foreach (UserFavourite item in items)
{
if (item != null)
{
found = true;
}
}
Assert.Equal(found, true);
// remove the favourites from the user
items = new UserFavourite[0];
request = new HttpRequestMessage(HttpMethod.Put, "/api/users/" + id + "/favourites");
jsonString = JsonConvert.SerializeObject(items, Formatting.Indented);
request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// verify the group membership - should be false now.
request = new HttpRequestMessage(HttpMethod.Get, "/api/users/" + id + "/favourites");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
jsonString = await response.Content.ReadAsStringAsync();
items = JsonConvert.DeserializeObject<UserFavourite[]>(jsonString);
found = false;
foreach (UserFavourite item in items)
{
if (item != null)
{
found = true;
}
}
Assert.Equal(found, false);
// delete the user
request = new HttpRequestMessage(HttpMethod.Post, "/api/users/" + id + "/delete");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// should get a 404 if we try a get now.
request = new HttpRequestMessage(HttpMethod.Get, "/api/users/" + id);
response = await _client.SendAsync(request);
Assert.Equal(response.StatusCode, HttpStatusCode.NotFound);
}
[Fact]
/// <summary>
/// Integration test for Users
/// </summary>
public async void TestUsers()
{
string initialName = "InitialName";
string changedName = "ChangedName";
// first test the POST.
var request = new HttpRequestMessage(HttpMethod.Post, "/api/users");
// create a new object.
UserViewModel user = new UserViewModel();
user.GivenName = initialName;
string jsonString = user.ToJson();
request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
var response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
user = JsonConvert.DeserializeObject<UserViewModel>(jsonString);
// get the id
var id = user.Id;
// change the name
user.GivenName = changedName;
// now do an update.
request = new HttpRequestMessage(HttpMethod.Put, "/api/users/" + id);
request.Content = new StringContent(user.ToJson(), Encoding.UTF8, "application/json");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// do a get.
request = new HttpRequestMessage(HttpMethod.Get, "/api/users/" + id);
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
user = JsonConvert.DeserializeObject<UserViewModel>(jsonString);
// verify the change went through.
Assert.Equal(user.GivenName, changedName);
// do a delete.
request = new HttpRequestMessage(HttpMethod.Post, "/api/users/" + id + "/delete");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// should get a 404 if we try a get now.
request = new HttpRequestMessage(HttpMethod.Get, "/api/users/" + id);
response = await _client.SendAsync(request);
Assert.Equal(response.StatusCode, HttpStatusCode.NotFound);
}
[Fact]
/// <summary>
/// Integration test for User Delete
/// </summary>
public async void TestUserDelete()
{
// first create a role.
string initialName = "InitialName";
var request = new HttpRequestMessage(HttpMethod.Post, "/api/roles");
RoleViewModel role = new RoleViewModel();
role.Name = initialName;
role.Description = "test";
string jsonString = role.ToJson();
request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
var response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
role = JsonConvert.DeserializeObject<RoleViewModel>(jsonString);
// get the role id
var role_id = role.Id;
// now create a user.
request = new HttpRequestMessage(HttpMethod.Post, "/api/users");
UserViewModel user = new UserViewModel();
user.GivenName = initialName;
jsonString = user.ToJson();
request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
user = JsonConvert.DeserializeObject<UserViewModel>(jsonString);
// get the user id
var user_id = user.Id;
// now add the user to the role.
UserRoleViewModel userRole = new UserRoleViewModel();
userRole.RoleId = role_id;
userRole.UserId = user_id;
userRole.EffectiveDate = DateTime.UtcNow;
UserRoleViewModel[] items = new UserRoleViewModel[1];
items[0] = userRole;
// send the request.
request = new HttpRequestMessage(HttpMethod.Put, "/api/roles/" + role_id + "/users");
jsonString = JsonConvert.SerializeObject(items, Formatting.Indented);
request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// if we do a get we should get the same items.
request = new HttpRequestMessage(HttpMethod.Get, "/api/roles/" + role_id + "/users");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
User[] userRolesResponse = JsonConvert.DeserializeObject<User[]>(jsonString);
Assert.Equal(items[0].UserId, userRolesResponse[0].Id);
// now add a group to the user
SchoolBusAPI.Models.User newUser = new SchoolBusAPI.Models.User();
newUser.Id = user.Id;
// now create a Group
request = new HttpRequestMessage(HttpMethod.Post, "/api/groups");
Group group = new Group();
group.Name = "initialName";
jsonString = user.ToJson();
request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
group = JsonConvert.DeserializeObject<Group>(jsonString);
// get the id
int group_id = user.Id;
// assign user to group
GroupMembershipViewModel groupMembership = new GroupMembershipViewModel();
groupMembership.UserId = newUser.Id;
groupMembership.GroupId = group.Id;
GroupMembershipViewModel[] groupmembershipItems = new GroupMembershipViewModel[1];
groupmembershipItems[0] = groupMembership;
// send the request.
request = new HttpRequestMessage(HttpMethod.Put, "/api/users/" + user_id + "/groups");
jsonString = JsonConvert.SerializeObject(groupmembershipItems, Formatting.Indented);
request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// verify the group membership
request = new HttpRequestMessage(HttpMethod.Get, "/api/groups/" + group_id + "/users");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
jsonString = await response.Content.ReadAsStringAsync();
User[] users = JsonConvert.DeserializeObject<User[]>(jsonString);
bool found = false;
foreach (User item in users)
{
if (item != null && item.Id == user_id)
{
found = true;
}
}
Assert.Equal(found, true);
// cleanup
// Delete user
request = new HttpRequestMessage(HttpMethod.Post, "/api/users/" + user_id + "/delete");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// should get a 404 if we try a get now.
request = new HttpRequestMessage(HttpMethod.Get, "/api/users/" + user_id);
response = await _client.SendAsync(request);
Assert.Equal(response.StatusCode, HttpStatusCode.NotFound);
// Delete role
request = new HttpRequestMessage(HttpMethod.Post, "/api/roles/" + role_id + "/delete");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// should get a 404 if we try a get now.
request = new HttpRequestMessage(HttpMethod.Get, "/api/roles/" + role_id);
response = await _client.SendAsync(request);
Assert.Equal(response.StatusCode, HttpStatusCode.NotFound);
// delete the group
request = new HttpRequestMessage(HttpMethod.Post, "/api/groups/" + group_id + "/delete");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// should get a 404 if we try a get now.
request = new HttpRequestMessage(HttpMethod.Get, "/api/groups/" + group_id);
response = await _client.SendAsync(request);
Assert.Equal(response.StatusCode, HttpStatusCode.NotFound);
}
[Fact]
/// <summary>
/// Integration test for User Favourites.
/// </summary>
public async void TestUserEdit()
{
string initialName = "InitialName";
string changedName = "ChangedName";
var request = new HttpRequestMessage(HttpMethod.Post, "/api/roles");
RoleViewModel role = new RoleViewModel();
role.Name = initialName;
role.Description = "test";
string jsonString = role.ToJson();
request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
var response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
role = JsonConvert.DeserializeObject<RoleViewModel>(jsonString);
// get the role id
var role_id = role.Id;
// now create a Group
request = new HttpRequestMessage(HttpMethod.Post, "/api/groups");
Group group = new Group();
group.Name = "initialName";
jsonString = group.ToJson();
request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
group = JsonConvert.DeserializeObject<Group>(jsonString);
// get the id
int group_id = group.Id;
// create a user.
request = new HttpRequestMessage(HttpMethod.Post, "/api/users");
User user = new User();
user.GivenName = initialName;
jsonString = user.ToJson();
request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
user = JsonConvert.DeserializeObject<User>(jsonString);
// get the id
var id = user.Id;
// add and associate the role
request = new HttpRequestMessage(HttpMethod.Post, "/api/users/" + id + "/roles");
UserRoleViewModel userRoleViewModel = new UserRoleViewModel();
userRoleViewModel.RoleId = role.Id;
userRoleViewModel.EffectiveDate = DateTime.UtcNow;
UserRoleViewModel[] items = new UserRoleViewModel[1];
items[0] = userRoleViewModel;
jsonString = JsonConvert.SerializeObject(userRoleViewModel, Formatting.Indented);
request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// verify the user has a favourite.
request = new HttpRequestMessage(HttpMethod.Get, "/api/users/" + id + "/roles");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
UserRoleViewModel[] returnedItems = JsonConvert.DeserializeObject<UserRoleViewModel[]>(jsonString);
bool found = false;
foreach (UserRoleViewModel item in returnedItems)
{
if (item != null)
{
found = true;
}
}
Assert.Equal(found, true);
// verify that the put works too.
request = new HttpRequestMessage(HttpMethod.Put, "/api/users/" + id + "/roles");
jsonString = JsonConvert.SerializeObject(items, Formatting.Indented);
request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// verify the user has a role.
request = new HttpRequestMessage(HttpMethod.Get, "/api/users/" + id + "/roles");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
returnedItems = JsonConvert.DeserializeObject<UserRoleViewModel[]>(jsonString);
found = false;
foreach (UserRoleViewModel item in returnedItems)
{
if (item != null)
{
found = true;
}
}
Assert.Equal(found, true);
// verify that the user has roles.
request = new HttpRequestMessage(HttpMethod.Get, "/api/users/" + id);
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
UserViewModel userViewModel = JsonConvert.DeserializeObject<UserViewModel>(jsonString);
Assert.NotNull(userViewModel);
Assert.NotNull(userViewModel.UserRoles);
found = false;
foreach (UserRole userRole in userViewModel.UserRoles)
{
if (userRole != null && userRole.Role != null && userRole.Role.Id == role.Id)
{
found = true;
}
}
Assert.Equal(found, true);
// edit the user.
userViewModel.Surname = changedName;
request = new HttpRequestMessage(HttpMethod.Put, "/api/users/" + id);
request.Content = new StringContent(userViewModel.ToJson(), Encoding.UTF8, "application/json");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// verify the user still has roles.
request = new HttpRequestMessage(HttpMethod.Get, "/api/users/" + id);
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
userViewModel = JsonConvert.DeserializeObject<UserViewModel>(jsonString);
Assert.NotNull(userViewModel);
Assert.Equal(userViewModel.Surname, changedName);
Assert.NotNull(userViewModel.UserRoles);
found = false;
foreach (UserRole userRole in userViewModel.UserRoles)
{
if (userRole != null && userRole.Role != null && userRole.Role.Id == role.Id)
{
found = true;
}
}
Assert.Equal(found, true);
// update groups for the user. start by getting existing groups
request = new HttpRequestMessage(HttpMethod.Get, "/api/users/" + id + "/groups");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
returnedItems = JsonConvert.DeserializeObject<UserRoleViewModel[]>(jsonString);
// delete the user
request = new HttpRequestMessage(HttpMethod.Post, "/api/users/" + id + "/delete");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// should get a 404 if we try a get now.
request = new HttpRequestMessage(HttpMethod.Get, "/api/users/" + id);
response = await _client.SendAsync(request);
Assert.Equal(response.StatusCode, HttpStatusCode.NotFound);
// Delete role
request = new HttpRequestMessage(HttpMethod.Post, "/api/roles/" + role_id + "/delete");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// should get a 404 if we try a get now.
request = new HttpRequestMessage(HttpMethod.Get, "/api/roles/" + role_id);
response = await _client.SendAsync(request);
Assert.Equal(response.StatusCode, HttpStatusCode.NotFound);
// Delete group
request = new HttpRequestMessage(HttpMethod.Post, "/api/groups/" + group_id + "/delete");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// should get a 404 if we try a get now.
request = new HttpRequestMessage(HttpMethod.Get, "/api/groups/" + group_id);
response = await _client.SendAsync(request);
Assert.Equal(response.StatusCode, HttpStatusCode.NotFound);
}
}
}
| |
using System;
using ServiceStack.ServiceHost;
using ServiceStack.Text;
namespace ServiceStack.Common.Web
{
public static class ContentType
{
public const string Utf8Suffix = "; charset=utf-8";
public const string HeaderContentType = "Content-Type";
public const string FormUrlEncoded = "application/x-www-form-urlencoded";
public const string MultiPartFormData = "multipart/form-data";
public const string Html = "text/html";
public const string JsonReport = "text/jsonreport";
public const string Xml = "application/xml";
public const string XmlText = "text/xml";
public const string Soap11 = " text/xml; charset=utf-8";
public const string Soap12 = " application/soap+xml";
public const string Json = "application/json";
public const string JsonText = "text/json";
public const string JavaScript = "application/javascript";
public const string Jsv = "application/jsv";
public const string JsvText = "text/jsv";
public const string Csv = "text/csv";
public const string Yaml = "application/yaml";
public const string YamlText = "text/yaml";
public const string PlainText = "text/plain";
public const string MarkdownText = "text/markdown";
public const string ProtoBuf = "application/x-protobuf";
public const string MsgPack = "application/x-msgpack";
public const string Bson = "application/bson";
public const string Binary = "application/octet-stream";
public static EndpointAttributes GetEndpointAttributes(string contentType)
{
if (contentType == null)
return EndpointAttributes.None;
var realContentType = GetRealContentType(contentType);
switch (realContentType)
{
case Json:
case JsonText:
return EndpointAttributes.Json;
case Xml:
case XmlText:
return EndpointAttributes.Xml;
case Html:
return EndpointAttributes.Html;
case Jsv:
case JsvText:
return EndpointAttributes.Jsv;
case Yaml:
case YamlText:
return EndpointAttributes.Yaml;
case Csv:
return EndpointAttributes.Csv;
case Soap11:
return EndpointAttributes.Soap11;
case Soap12:
return EndpointAttributes.Soap12;
case ProtoBuf:
return EndpointAttributes.ProtoBuf;
case MsgPack:
return EndpointAttributes.MsgPack;
}
return EndpointAttributes.FormatOther;
}
public static string GetRealContentType(string contentType)
{
return contentType == null
? null
: contentType.Split(';')[0].Trim();
}
public static bool MatchesContentType(this string contentType, string matchesContentType)
{
return GetRealContentType(contentType) == GetRealContentType(matchesContentType);
}
public static bool IsBinary(this string contentType)
{
var realContentType = GetRealContentType(contentType);
switch (realContentType)
{
case ProtoBuf:
case MsgPack:
case Binary:
case Bson:
return true;
}
var primaryType = realContentType.SplitOnFirst('/')[0];
switch (primaryType)
{
case "image":
case "audio":
case "video":
return true;
}
return false;
}
public static Feature ToFeature(this string contentType)
{
if (contentType == null)
return Feature.None;
var realContentType = GetRealContentType(contentType);
switch (realContentType)
{
case Json:
case JsonText:
return Feature.Json;
case Xml:
case XmlText:
return Feature.Xml;
case Html:
return Feature.Html;
case Jsv:
case JsvText:
return Feature.Jsv;
case Csv:
return Feature.Csv;
case Soap11:
return Feature.Soap11;
case Soap12:
return Feature.Soap12;
case ProtoBuf:
return Feature.ProtoBuf;
case MsgPack:
return Feature.MsgPack;
}
return Feature.CustomFormat;
}
public static string GetContentFormat(Format format)
{
var formatStr = format.ToString().ToLower();
return format == Format.MsgPack || format == Format.ProtoBuf
? "x-" + formatStr
: formatStr;
}
public static string GetContentFormat(string contentType)
{
if (contentType == null)
return null;
var parts = contentType.Split('/');
return parts[parts.Length - 1];
}
public static string ToContentFormat(this string contentType)
{
return GetContentFormat(contentType);
}
public static string ToContentType(this Format formats)
{
switch (formats)
{
case Format.Soap11:
case Format.Soap12:
case Format.Xml:
return Xml;
case Format.Json:
return Json;
case Format.Jsv:
return JsvText;
case Format.Csv:
return Csv;
case Format.ProtoBuf:
return ProtoBuf;
case Format.MsgPack:
return MsgPack;
case Format.Html:
return Html;
case Format.Yaml:
return Yaml;
default:
return null;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.IO;
using System.Net.Test.Common;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
public abstract class HttpClientHandler_Cancellation_Test : HttpClientTestBase
{
[Theory]
[InlineData(false, CancellationMode.Token)]
[InlineData(true, CancellationMode.Token)]
public async Task PostAsync_CancelDuringRequestContentSend_TaskCanceledQuickly(bool chunkedTransfer, CancellationMode mode)
{
if (!UseSocketsHttpHandler)
{
// Issue #27063: hangs / doesn't cancel
return;
}
var serverRelease = new TaskCompletionSource<bool>();
await LoopbackServer.CreateClientAndServerAsync(async uri =>
{
try
{
using (HttpClient client = CreateHttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
var cts = new CancellationTokenSource();
var waitToSend = new TaskCompletionSource<bool>();
var contentSending = new TaskCompletionSource<bool>();
var req = new HttpRequestMessage(HttpMethod.Post, uri) { Content = new ByteAtATimeContent(int.MaxValue, waitToSend.Task, contentSending) };
req.Headers.TransferEncodingChunked = chunkedTransfer;
Task<HttpResponseMessage> resp = client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, cts.Token);
waitToSend.SetResult(true);
await contentSending.Task;
Cancel(mode, client, cts);
await ValidateClientCancellationAsync(() => resp);
}
}
finally
{
serverRelease.SetResult(true);
}
}, server => server.AcceptConnectionAsync(connection => serverRelease.Task));
}
[Theory]
[MemberData(nameof(TwoBoolsAndCancellationMode))]
public async Task GetAsync_CancelDuringResponseHeadersReceived_TaskCanceledQuickly(bool chunkedTransfer, bool connectionClose, CancellationMode mode)
{
using (HttpClient client = CreateHttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
var cts = new CancellationTokenSource();
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
var partialResponseHeadersSent = new TaskCompletionSource<bool>();
var clientFinished = new TaskCompletionSource<bool>();
Task serverTask = server.AcceptConnectionAsync(async connection =>
{
await connection.ReadRequestHeaderAndSendCustomResponseAsync(
$"HTTP/1.1 200 OK\r\nDate: {DateTimeOffset.UtcNow:R}\r\n"); // missing final \r\n so headers don't complete
partialResponseHeadersSent.TrySetResult(true);
await clientFinished.Task;
});
await ValidateClientCancellationAsync(async () =>
{
var req = new HttpRequestMessage(HttpMethod.Get, url);
req.Headers.ConnectionClose = connectionClose;
Task<HttpResponseMessage> getResponse = client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, cts.Token);
await partialResponseHeadersSent.Task;
Cancel(mode, client, cts);
await getResponse;
});
try
{
clientFinished.SetResult(true);
await serverTask;
} catch { }
});
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Test needs to be rewritten to work on UAP due to WinRT differences")]
[Theory]
[MemberData(nameof(TwoBoolsAndCancellationMode))]
public async Task GetAsync_CancelDuringResponseBodyReceived_Buffered_TaskCanceledQuickly(bool chunkedTransfer, bool connectionClose, CancellationMode mode)
{
using (HttpClient client = CreateHttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
var cts = new CancellationTokenSource();
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
var responseHeadersSent = new TaskCompletionSource<bool>();
var clientFinished = new TaskCompletionSource<bool>();
Task serverTask = server.AcceptConnectionAsync(async connection =>
{
await connection.ReadRequestHeaderAndSendCustomResponseAsync(
$"HTTP/1.1 200 OK\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
(!chunkedTransfer ? "Content-Length: 20\r\n" : "") +
(connectionClose ? "Connection: close\r\n" : "") +
$"\r\n123"); // "123" is part of body and could either be chunked size or part of content-length bytes, both incomplete
responseHeadersSent.TrySetResult(true);
await clientFinished.Task;
});
await ValidateClientCancellationAsync(async () =>
{
var req = new HttpRequestMessage(HttpMethod.Get, url);
req.Headers.ConnectionClose = connectionClose;
Task<HttpResponseMessage> getResponse = client.SendAsync(req, HttpCompletionOption.ResponseContentRead, cts.Token);
await responseHeadersSent.Task;
await Task.Delay(1); // make it more likely that client will have started processing response body
Cancel(mode, client, cts);
await getResponse;
});
try
{
clientFinished.SetResult(true);
await serverTask;
} catch { }
});
}
}
[Theory]
[MemberData(nameof(ThreeBools))]
public async Task GetAsync_CancelDuringResponseBodyReceived_Unbuffered_TaskCanceledQuickly(bool chunkedTransfer, bool connectionClose, bool readOrCopyToAsync)
{
if (IsNetfxHandler || IsCurlHandler)
{
// doesn't cancel
return;
}
using (HttpClient client = CreateHttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
var cts = new CancellationTokenSource();
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
var clientFinished = new TaskCompletionSource<bool>();
Task serverTask = server.AcceptConnectionAsync(async connection =>
{
await connection.ReadRequestHeaderAndSendCustomResponseAsync(
$"HTTP/1.1 200 OK\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
(!chunkedTransfer ? "Content-Length: 20\r\n" : "") +
(connectionClose ? "Connection: close\r\n" : "") +
$"\r\n");
await clientFinished.Task;
});
var req = new HttpRequestMessage(HttpMethod.Get, url);
req.Headers.ConnectionClose = connectionClose;
Task<HttpResponseMessage> getResponse = client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, cts.Token);
await ValidateClientCancellationAsync(async () =>
{
HttpResponseMessage resp = await getResponse;
Stream respStream = await resp.Content.ReadAsStreamAsync();
Task readTask = readOrCopyToAsync ?
respStream.ReadAsync(new byte[1], 0, 1, cts.Token) :
respStream.CopyToAsync(Stream.Null, 10, cts.Token);
cts.Cancel();
await readTask;
});
try
{
clientFinished.SetResult(true);
await serverTask;
} catch { }
});
}
}
[Theory]
[InlineData(CancellationMode.CancelPendingRequests, false)]
[InlineData(CancellationMode.DisposeHttpClient, true)]
[InlineData(CancellationMode.CancelPendingRequests, false)]
[InlineData(CancellationMode.DisposeHttpClient, true)]
public async Task GetAsync_CancelPendingRequests_DoesntCancelReadAsyncOnResponseStream(CancellationMode mode, bool copyToAsync)
{
if (IsNetfxHandler)
{
// throws ObjectDisposedException as part of Stream.CopyToAsync/ReadAsync
return;
}
if (IsCurlHandler)
{
// Issue #27065
// throws OperationCanceledException from Stream.CopyToAsync/ReadAsync
return;
}
using (HttpClient client = CreateHttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
var clientReadSomeBody = new TaskCompletionSource<bool>();
var clientFinished = new TaskCompletionSource<bool>();
var responseContentSegment = new string('s', 3000);
int responseSegments = 4;
int contentLength = responseContentSegment.Length * responseSegments;
Task serverTask = server.AcceptConnectionAsync(async connection =>
{
await connection.ReadRequestHeaderAndSendCustomResponseAsync(
$"HTTP/1.1 200 OK\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
$"Content-Length: {contentLength}\r\n" +
$"\r\n");
for (int i = 0; i < responseSegments; i++)
{
await connection.Writer.WriteAsync(responseContentSegment);
if (i == 0)
{
await clientReadSomeBody.Task;
}
}
await clientFinished.Task;
});
using (HttpResponseMessage resp = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
using (Stream respStream = await resp.Content.ReadAsStreamAsync())
{
var result = new MemoryStream();
int b = respStream.ReadByte();
Assert.NotEqual(-1, b);
result.WriteByte((byte)b);
Cancel(mode, client, null); // should not cancel the operation, as using ResponseHeadersRead
clientReadSomeBody.SetResult(true);
if (copyToAsync)
{
await respStream.CopyToAsync(result, 10, new CancellationTokenSource().Token);
}
else
{
byte[] buffer = new byte[10];
int bytesRead;
while ((bytesRead = await respStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
result.Write(buffer, 0, bytesRead);
}
}
Assert.Equal(contentLength, result.Length);
}
clientFinished.SetResult(true);
await serverTask;
});
}
}
[ActiveIssue(32000)]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "WinRT stack can't set MaxConnectionsPerServer < 2")]
[Fact]
public async Task MaxConnectionsPerServer_WaitingConnectionsAreCancelable()
{
if (IsNetfxHandler)
{
// Throws HttpRequestException wrapping a WebException for the canceled request
// instead of throwing an OperationCanceledException or a canceled WebException directly.
return;
}
using (HttpClientHandler handler = CreateHttpClientHandler())
using (HttpClient client = new HttpClient(handler))
{
handler.MaxConnectionsPerServer = 1;
client.Timeout = Timeout.InfiniteTimeSpan;
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
var serverAboutToBlock = new TaskCompletionSource<bool>();
var blockServerResponse = new TaskCompletionSource<bool>();
Task serverTask1 = server.AcceptConnectionAsync(async connection1 =>
{
await connection1.ReadRequestHeaderAsync();
await connection1.Writer.WriteAsync($"HTTP/1.1 200 OK\r\nConnection: close\r\nDate: {DateTimeOffset.UtcNow:R}\r\n");
serverAboutToBlock.SetResult(true);
await blockServerResponse.Task;
await connection1.Writer.WriteAsync("Content-Length: 5\r\n\r\nhello");
});
Task get1 = client.GetAsync(url);
await serverAboutToBlock.Task;
var cts = new CancellationTokenSource();
Task get2 = ValidateClientCancellationAsync(() => client.GetAsync(url, cts.Token));
Task get3 = ValidateClientCancellationAsync(() => client.GetAsync(url, cts.Token));
Task get4 = client.GetAsync(url);
cts.Cancel();
await get2;
await get3;
blockServerResponse.SetResult(true);
await new[] { get1, serverTask1 }.WhenAllOrAnyFailed();
Task serverTask4 = server.AcceptConnectionSendResponseAndCloseAsync();
await new[] { get4, serverTask4 }.WhenAllOrAnyFailed();
});
}
}
private async Task ValidateClientCancellationAsync(Func<Task> clientBodyAsync)
{
var stopwatch = Stopwatch.StartNew();
Exception error = await Record.ExceptionAsync(clientBodyAsync);
stopwatch.Stop();
Assert.NotNull(error);
if (IsNetfxHandler)
{
Assert.True(
error is WebException we && we.Status == WebExceptionStatus.RequestCanceled ||
error is OperationCanceledException,
"Expected cancellation exception, got:" + Environment.NewLine + error);
}
else
{
Assert.True(
error is OperationCanceledException,
"Expected cancellation exception, got:" + Environment.NewLine + error);
}
Assert.True(stopwatch.Elapsed < new TimeSpan(0, 0, 60), $"Elapsed time {stopwatch.Elapsed} should be less than 60 seconds, was {stopwatch.Elapsed.TotalSeconds}");
}
private static void Cancel(CancellationMode mode, HttpClient client, CancellationTokenSource cts)
{
if ((mode & CancellationMode.Token) != 0)
{
cts?.Cancel();
}
if ((mode & CancellationMode.CancelPendingRequests) != 0)
{
client?.CancelPendingRequests();
}
if ((mode & CancellationMode.DisposeHttpClient) != 0)
{
client?.Dispose();
}
}
[Flags]
public enum CancellationMode
{
Token = 0x1,
CancelPendingRequests = 0x2,
DisposeHttpClient = 0x4
}
private static readonly bool[] s_bools = new[] { true, false };
public static IEnumerable<object[]> TwoBoolsAndCancellationMode() =>
from first in s_bools
from second in s_bools
from mode in new[] { CancellationMode.Token, CancellationMode.CancelPendingRequests, CancellationMode.DisposeHttpClient, CancellationMode.Token | CancellationMode.CancelPendingRequests }
select new object[] { first, second, mode };
public static IEnumerable<object[]> ThreeBools() =>
from first in s_bools
from second in s_bools
from third in s_bools
select new object[] { first, second, third };
private sealed class ByteAtATimeContent : HttpContent
{
private readonly Task _waitToSend;
private readonly TaskCompletionSource<bool> _startedSend;
private readonly int _length;
public ByteAtATimeContent(int length, Task waitToSend, TaskCompletionSource<bool> startedSend)
{
_length = length;
_waitToSend = waitToSend;
_startedSend = startedSend;
}
protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
await _waitToSend;
_startedSend.SetResult(true);
var buffer = new byte[1] { 42 };
for (int i = 0; i < _length; i++)
{
await stream.WriteAsync(buffer);
await stream.FlushAsync();
await Task.Delay(1);
}
}
protected override bool TryComputeLength(out long length)
{
length = _length;
return true;
}
}
}
}
| |
namespace FakeItEasy.Configuration
{
using System;
using System.Collections.Generic;
using System.Linq;
using FakeItEasy.Compatibility;
using FakeItEasy.Core;
/// <summary>
/// Provides the base for rules that can be built using the FakeConfiguration.
/// </summary>
internal abstract class BuildableCallRule
: IFakeObjectCallRule
{
public static readonly Func<IFakeObjectCall, ICollection<object?>> DefaultOutAndRefParametersValueProducer = call =>
ArrayHelper.Empty<object>();
private static readonly Action<IInterceptedFakeObjectCall> DefaultApplicator = call =>
call.SetReturnValue(call.GetDefaultReturnValue());
private readonly List<WherePredicate> wherePredicates;
private Action<IInterceptedFakeObjectCall> applicator;
private bool wasApplicatorSet;
private bool canSetOutAndRefParametersValueProducer;
protected BuildableCallRule()
{
this.Actions = new LinkedList<Action<IFakeObjectCall>>();
this.applicator = DefaultApplicator;
this.OutAndRefParametersValueProducer = DefaultOutAndRefParametersValueProducer;
this.canSetOutAndRefParametersValueProducer = true;
this.wherePredicates = new List<WherePredicate>();
}
/// <summary>
/// Gets a collection of actions that should be invoked when the configured
/// call is made.
/// </summary>
public virtual ICollection<Action<IFakeObjectCall>> Actions { get; }
/// <summary>
/// Gets or sets a value indicating whether the base method of the fake object call should be
/// called when the fake object call is made.
/// </summary>
public bool CallBaseMethod { get; set; }
/// <summary>
/// Gets or sets a wrapped object to which the call should be delegated.
/// </summary>
public object? CallWrappedMethodOn { get; set; }
/// <summary>
/// Gets or sets the number of times the configured rule should be used.
/// </summary>
public virtual int? NumberOfTimesToCall { get; set; }
/// <summary>
/// Sets a function that provides values to apply to output and reference variables.
/// </summary>
protected Func<IFakeObjectCall, ICollection<object?>> OutAndRefParametersValueProducer
{
private get; set;
}
/// <summary>
/// Writes a description of calls the rule is applicable to.
/// </summary>
/// <param name="writer">The writer on which to describe the call.</param>
public abstract void DescribeCallOn(IOutputWriter writer);
/// <summary>
/// Sets an action that is called by the <see cref="Apply"/> method to apply this
/// rule to a fake object call.
/// </summary>
/// <param name="newApplicator">The action to use.</param>
public void UseApplicator(Action<IInterceptedFakeObjectCall> newApplicator)
{
if (this.wasApplicatorSet)
{
throw new InvalidOperationException(ExceptionMessages.CallBehaviorAlreadyDefined);
}
this.applicator = newApplicator;
this.wasApplicatorSet = true;
}
/// <summary>
/// Sets (or resets) the applicator (see <see cref="UseApplicator"/>) to the default action:
/// the same as a newly-created rule would have.
/// </summary>
public void UseDefaultApplicator() => this.UseApplicator(DefaultApplicator);
public virtual void Apply(IInterceptedFakeObjectCall fakeObjectCall)
{
Guard.AgainstNull(fakeObjectCall, nameof(fakeObjectCall));
foreach (var action in this.Actions)
{
action.Invoke(fakeObjectCall);
}
this.applicator.Invoke(fakeObjectCall);
this.ApplyOutAndRefParametersValueProducer(fakeObjectCall);
if (this.CallBaseMethod)
{
fakeObjectCall.CallBaseMethod();
}
else if (this.CallWrappedMethodOn is object wrappedObject)
{
fakeObjectCall.CallWrappedMethod(wrappedObject);
}
}
/// <summary>
/// Gets if this rule is applicable to the specified call.
/// </summary>
/// <param name="fakeObjectCall">The call to validate.</param>
/// <returns>True if the rule applies to the call.</returns>
public virtual bool IsApplicableTo(IFakeObjectCall fakeObjectCall)
{
return this.wherePredicates.All(x => x.Matches(fakeObjectCall))
&& this.OnIsApplicableTo(fakeObjectCall);
}
/// <summary>
/// Writes a description of calls the rule is applicable to.
/// </summary>
/// <param name="writer">The writer to write the description to.</param>
public void WriteDescriptionOfValidCall(IOutputWriter writer)
{
Guard.AgainstNull(writer, nameof(writer));
this.DescribeCallOn(writer);
Func<string> wherePrefix = () =>
{
wherePrefix = () => "and";
return "where";
};
using (writer.Indent())
{
foreach (var wherePredicate in this.wherePredicates)
{
writer.WriteLine();
writer.Write(wherePrefix.Invoke());
writer.Write(" ");
wherePredicate.WriteDescription(writer);
}
}
}
public virtual void ApplyWherePredicate(Func<IFakeObjectCall, bool> predicate, Action<IOutputWriter> descriptionWriter)
{
this.wherePredicates.Add(new WherePredicate(predicate, descriptionWriter));
}
public abstract void UsePredicateToValidateArguments(Func<ArgumentCollection, bool> predicate);
/// <summary>
/// Clones the part of the rule that describes which call is being configured.
/// </summary>
/// <returns>The cloned rule.</returns>
public BuildableCallRule CloneCallSpecification()
{
var clone = this.CloneCallSpecificationCore();
clone.wherePredicates.AddRange(this.wherePredicates);
return clone;
}
/// <summary>
/// Sets the delegate that will provide out and ref parameters when an applicable call is made.
/// May only be called once per BuildableCallRule.
/// <seealso cref="OutAndRefParametersValueProducer" />
/// </summary>
/// <param name="producer">The new value producer.</param>
/// <exception cref="System.InvalidOperationException">
/// Thrown when the SetOutAndRefParametersValueProducer method has previously been called.
/// </exception>
public void SetOutAndRefParametersValueProducer(Func<IFakeObjectCall, ICollection<object?>> producer)
{
if (!this.canSetOutAndRefParametersValueProducer)
{
throw new InvalidOperationException(ExceptionMessages.OutAndRefBehaviorAlreadyDefined);
}
this.OutAndRefParametersValueProducer = producer;
this.canSetOutAndRefParametersValueProducer = false;
}
/// <summary>
/// When overridden in a derived class, returns a new instance of the same type and copies the call
/// specification members for that type.
/// </summary>
/// <returns>The cloned rule.</returns>
protected abstract BuildableCallRule CloneCallSpecificationCore();
protected abstract bool OnIsApplicableTo(IFakeObjectCall fakeObjectCall);
private static ICollection<int> GetIndexesOfOutAndRefParameters(IInterceptedFakeObjectCall fakeObjectCall)
{
var indexes = new List<int>();
var arguments = fakeObjectCall.Method.GetParameters();
for (var i = 0; i < arguments.Length; i++)
{
if (arguments[i].IsOutOrRef())
{
indexes.Add(i);
}
}
return indexes;
}
private void ApplyOutAndRefParametersValueProducer(IInterceptedFakeObjectCall fakeObjectCall)
{
if (this.OutAndRefParametersValueProducer == DefaultOutAndRefParametersValueProducer)
{
return;
}
var indexes = GetIndexesOfOutAndRefParameters(fakeObjectCall);
ICollection<object?> values = this.OutAndRefParametersValueProducer(fakeObjectCall);
if (values.Count != indexes.Count)
{
throw new InvalidOperationException(ExceptionMessages.NumberOfOutAndRefParametersDoesNotMatchCall);
}
foreach (var argument in indexes.Zip(values, (index, value) => new { Index = index, Value = value }))
{
fakeObjectCall.SetArgumentValue(argument.Index, argument.Value);
}
}
private class WherePredicate
{
private readonly Func<IFakeObjectCall, bool> predicate;
private readonly Action<IOutputWriter> descriptionWriter;
public WherePredicate(Func<IFakeObjectCall, bool> predicate, Action<IOutputWriter> descriptionWriter)
{
this.predicate = predicate;
this.descriptionWriter = descriptionWriter;
}
public void WriteDescription(IOutputWriter writer)
{
try
{
this.descriptionWriter.Invoke(writer);
}
catch (Exception ex)
{
throw new UserCallbackException(ExceptionMessages.UserCallbackThrewAnException("Call filter description"), ex);
}
}
public bool Matches(IFakeObjectCall call)
{
try
{
return this.predicate.Invoke(call);
}
catch (Exception ex)
{
throw new UserCallbackException(ExceptionMessages.UserCallbackThrewAnException($"Call filter <{this.GetDescription()}>"), ex);
}
}
private string GetDescription()
{
var writer = ServiceLocator.Resolve<StringBuilderOutputWriter.Factory>().Invoke();
this.WriteDescription(writer);
return writer.Builder.ToString();
}
}
}
}
| |
// This is a copy of the 7-zip LZMA
// compression library.
using System;
namespace LZMA
{
using RangeCoder;
internal class LzmaEncoder : ICoder, ISetCoderProperties, IWriteCoderProperties
{
enum EMatchFinderType
{
BT2,
BT4,
};
const UInt32 kIfinityPrice = 0xFFFFFFF;
static Byte[] g_FastPos = new Byte[1 << 11];
static LzmaEncoder()
{
const Byte kFastSlots = 22;
int c = 2;
g_FastPos[0] = 0;
g_FastPos[1] = 1;
for (Byte slotFast = 2; slotFast < kFastSlots; slotFast++)
{
UInt32 k = ((UInt32)1 << ((slotFast >> 1) - 1));
for (UInt32 j = 0; j < k; j++, c++)
g_FastPos[c] = slotFast;
}
}
static UInt32 GetPosSlot(UInt32 pos)
{
if (pos < (1 << 11))
return g_FastPos[pos];
if (pos < (1 << 21))
return (UInt32)(g_FastPos[pos >> 10] + 20);
return (UInt32)(g_FastPos[pos >> 20] + 40);
}
static UInt32 GetPosSlot2(UInt32 pos)
{
if (pos < (1 << 17))
return (UInt32)(g_FastPos[pos >> 6] + 12);
if (pos < (1 << 27))
return (UInt32)(g_FastPos[pos >> 16] + 32);
return (UInt32)(g_FastPos[pos >> 26] + 52);
}
Base.State _state = new Base.State();
Byte _previousByte;
UInt32[] _repDistances = new UInt32[Base.kNumRepDistances];
void BaseInit()
{
_state.Init();
_previousByte = 0;
for (UInt32 i = 0; i < Base.kNumRepDistances; i++)
_repDistances[i] = 0;
}
const int kDefaultDictionaryLogSize = 22;
const UInt32 kNumFastBytesDefault = 0x20;
class LiteralEncoder
{
public struct Encoder2
{
BitEncoder[] m_Encoders;
public void Create() { m_Encoders = new BitEncoder[0x300]; }
public void Init() { for (int i = 0; i < 0x300; i++) m_Encoders[i].Init(); }
public void Encode(RangeCoder.Encoder rangeEncoder, byte symbol)
{
uint context = 1;
for (int i = 7; i >= 0; i--)
{
uint bit = (uint)((symbol >> i) & 1);
m_Encoders[context].Encode(rangeEncoder, bit);
context = (context << 1) | bit;
}
}
public void EncodeMatched(RangeCoder.Encoder rangeEncoder, byte matchByte, byte symbol)
{
uint context = 1;
bool same = true;
for (int i = 7; i >= 0; i--)
{
uint bit = (uint)((symbol >> i) & 1);
uint state = context;
if (same)
{
uint matchBit = (uint)((matchByte >> i) & 1);
state += ((1 + matchBit) << 8);
same = (matchBit == bit);
}
m_Encoders[state].Encode(rangeEncoder, bit);
context = (context << 1) | bit;
}
}
public uint GetPrice(bool matchMode, byte matchByte, byte symbol)
{
uint price = 0;
uint context = 1;
int i = 7;
if (matchMode)
{
for (; i >= 0; i--)
{
uint matchBit = (uint)(matchByte >> i) & 1;
uint bit = (uint)(symbol >> i) & 1;
price += m_Encoders[((1 + matchBit) << 8) + context].GetPrice(bit);
context = (context << 1) | bit;
if (matchBit != bit)
{
i--;
break;
}
}
}
for (; i >= 0; i--)
{
uint bit = (uint)(symbol >> i) & 1;
price += m_Encoders[context].GetPrice(bit);
context = (context << 1) | bit;
}
return price;
}
}
Encoder2[] m_Coders;
int m_NumPrevBits;
int m_NumPosBits;
uint m_PosMask;
public void Create(int numPosBits, int numPrevBits)
{
if (m_Coders != null && m_NumPrevBits == numPrevBits && m_NumPosBits == numPosBits)
return;
m_NumPosBits = numPosBits;
m_PosMask = ((uint)1 << numPosBits) - 1;
m_NumPrevBits = numPrevBits;
uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits);
m_Coders = new Encoder2[numStates];
for (uint i = 0; i < numStates; i++)
m_Coders[i].Create();
}
public void Init()
{
uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits);
for (uint i = 0; i < numStates; i++)
m_Coders[i].Init();
}
public Encoder2 GetSubCoder(UInt32 pos, Byte prevByte)
{ return m_Coders[((pos & m_PosMask) << m_NumPrevBits) + (uint)(prevByte >> (8 - m_NumPrevBits))]; }
}
class LenEncoder
{
RangeCoder.BitEncoder _choice = new RangeCoder.BitEncoder();
RangeCoder.BitEncoder _choice2 = new RangeCoder.BitEncoder();
RangeCoder.BitTreeEncoder[] _lowCoder = new RangeCoder.BitTreeEncoder[Base.kNumPosStatesEncodingMax];
RangeCoder.BitTreeEncoder[] _midCoder = new RangeCoder.BitTreeEncoder[Base.kNumPosStatesEncodingMax];
RangeCoder.BitTreeEncoder _highCoder = new RangeCoder.BitTreeEncoder(Base.kNumHighLenBits);
public LenEncoder()
{
for (UInt32 posState = 0; posState < Base.kNumPosStatesEncodingMax; posState++)
{
_lowCoder[posState] = new RangeCoder.BitTreeEncoder(Base.kNumLowLenBits);
_midCoder[posState] = new RangeCoder.BitTreeEncoder(Base.kNumMidLenBits);
}
}
public void Init(UInt32 numPosStates)
{
_choice.Init();
_choice2.Init();
for (UInt32 posState = 0; posState < numPosStates; posState++)
{
_lowCoder[posState].Init();
_midCoder[posState].Init();
}
_highCoder.Init();
}
public void Encode(RangeCoder.Encoder rangeEncoder, UInt32 symbol, UInt32 posState)
{
if (symbol < Base.kNumLowLenSymbols)
{
_choice.Encode(rangeEncoder, 0);
_lowCoder[posState].Encode(rangeEncoder, symbol);
}
else
{
symbol -= Base.kNumLowLenSymbols;
_choice.Encode(rangeEncoder, 1);
if (symbol < Base.kNumMidLenSymbols)
{
_choice2.Encode(rangeEncoder, 0);
_midCoder[posState].Encode(rangeEncoder, symbol);
}
else
{
_choice2.Encode(rangeEncoder, 1);
_highCoder.Encode(rangeEncoder, symbol - Base.kNumMidLenSymbols);
}
}
}
public void SetPrices(UInt32 posState, UInt32 numSymbols, UInt32[] prices, UInt32 st)
{
UInt32 a0 = _choice.GetPrice0();
UInt32 a1 = _choice.GetPrice1();
UInt32 b0 = a1 + _choice2.GetPrice0();
UInt32 b1 = a1 + _choice2.GetPrice1();
UInt32 i = 0;
for (i = 0; i < Base.kNumLowLenSymbols; i++)
{
if (i >= numSymbols)
return;
prices[st + i] = a0 + _lowCoder[posState].GetPrice(i);
}
for (; i < Base.kNumLowLenSymbols + Base.kNumMidLenSymbols; i++)
{
if (i >= numSymbols)
return;
prices[st + i] = b0 + _midCoder[posState].GetPrice(i - Base.kNumLowLenSymbols);
}
for (; i < numSymbols; i++)
prices[st + i] = b1 + _highCoder.GetPrice(i - Base.kNumLowLenSymbols - Base.kNumMidLenSymbols);
}
};
const UInt32 kNumLenSpecSymbols = Base.kNumLowLenSymbols + Base.kNumMidLenSymbols;
class LenPriceTableEncoder : LenEncoder
{
UInt32[] _prices = new UInt32[Base.kNumLenSymbols << Base.kNumPosStatesBitsEncodingMax];
UInt32 _tableSize;
UInt32[] _counters = new UInt32[Base.kNumPosStatesEncodingMax];
public void SetTableSize(UInt32 tableSize) { _tableSize = tableSize; }
public UInt32 GetPrice(UInt32 symbol, UInt32 posState)
{
return _prices[posState * Base.kNumLenSymbols + symbol];
}
void UpdateTable(UInt32 posState)
{
SetPrices(posState, _tableSize, _prices, posState * Base.kNumLenSymbols);
_counters[posState] = _tableSize;
}
public void UpdateTables(UInt32 numPosStates)
{
for (UInt32 posState = 0; posState < numPosStates; posState++)
UpdateTable(posState);
}
public new void Encode(RangeCoder.Encoder rangeEncoder, UInt32 symbol, UInt32 posState)
{
base.Encode(rangeEncoder, symbol, posState);
if (--_counters[posState] == 0)
UpdateTable(posState);
}
}
const UInt32 kNumOpts = 1 << 12;
class Optimal
{
public Base.State State;
public bool Prev1IsChar;
public bool Prev2;
public UInt32 PosPrev2;
public UInt32 BackPrev2;
public UInt32 Price;
public UInt32 PosPrev;
public UInt32 BackPrev;
public UInt32 Backs0;
public UInt32 Backs1;
public UInt32 Backs2;
public UInt32 Backs3;
public void MakeAsChar() { BackPrev = 0xFFFFFFFF; Prev1IsChar = false; }
public void MakeAsShortRep() { BackPrev = 0; ; Prev1IsChar = false; }
public bool IsShortRep() { return (BackPrev == 0); }
};
Optimal[] _optimum = new Optimal[kNumOpts];
IMatchFinder _matchFinder = null;
RangeCoder.Encoder _rangeEncoder = new RangeCoder.Encoder();
RangeCoder.BitEncoder[] _isMatch = new RangeCoder.BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax];
RangeCoder.BitEncoder[] _isRep = new RangeCoder.BitEncoder[Base.kNumStates];
RangeCoder.BitEncoder[] _isRepG0 = new RangeCoder.BitEncoder[Base.kNumStates];
RangeCoder.BitEncoder[] _isRepG1 = new RangeCoder.BitEncoder[Base.kNumStates];
RangeCoder.BitEncoder[] _isRepG2 = new RangeCoder.BitEncoder[Base.kNumStates];
RangeCoder.BitEncoder[] _isRep0Long = new RangeCoder.BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax];
RangeCoder.BitTreeEncoder[] _posSlotEncoder = new RangeCoder.BitTreeEncoder[Base.kNumLenToPosStates];
RangeCoder.BitEncoder[] _posEncoders = new RangeCoder.BitEncoder[Base.kNumFullDistances - Base.kEndPosModelIndex];
RangeCoder.BitTreeEncoder _posAlignEncoder = new RangeCoder.BitTreeEncoder(Base.kNumAlignBits);
LenPriceTableEncoder _lenEncoder = new LenPriceTableEncoder();
LenPriceTableEncoder _repMatchLenEncoder = new LenPriceTableEncoder();
LiteralEncoder _literalEncoder = new LiteralEncoder();
UInt32[] _matchDistances = new UInt32[Base.kMatchMaxLen * 2 + 2];
UInt32 _numFastBytes = kNumFastBytesDefault;
UInt32 _longestMatchLength;
UInt32 _numDistancePairs;
UInt32 _additionalOffset;
UInt32 _optimumEndIndex;
UInt32 _optimumCurrentIndex;
bool _longestMatchWasFound;
UInt32[] _posSlotPrices = new UInt32[1 << (Base.kNumPosSlotBits + Base.kNumLenToPosStatesBits)];
UInt32[] _distancesPrices = new UInt32[Base.kNumFullDistances << Base.kNumLenToPosStatesBits];
UInt32[] _alignPrices = new UInt32[Base.kAlignTableSize];
UInt32 _alignPriceCount;
UInt32 _distTableSize = (kDefaultDictionaryLogSize * 2);
int _posStateBits = 2;
UInt32 _posStateMask = (4 - 1);
int _numLiteralPosStateBits = 0;
int _numLiteralContextBits = 3;
UInt32 _dictionarySize = (1 << kDefaultDictionaryLogSize);
UInt32 _dictionarySizePrev = 0xFFFFFFFF;
UInt32 _numFastBytesPrev = 0xFFFFFFFF;
Int64 nowPos64;
bool _finished;
System.IO.Stream _inStream;
EMatchFinderType _matchFinderType = EMatchFinderType.BT4;
bool _writeEndMark = false;
bool _needReleaseMFStream;
void Create()
{
if (_matchFinder == null)
{
BinTree bt = new BinTree();
int numHashBytes = 4;
if (_matchFinderType == EMatchFinderType.BT2)
numHashBytes = 2;
bt.SetType(numHashBytes);
_matchFinder = bt;
}
_literalEncoder.Create(_numLiteralPosStateBits, _numLiteralContextBits);
if (_dictionarySize == _dictionarySizePrev && _numFastBytesPrev == _numFastBytes)
return;
_matchFinder.Create(_dictionarySize, kNumOpts, _numFastBytes, Base.kMatchMaxLen + 1);
_dictionarySizePrev = _dictionarySize;
_numFastBytesPrev = _numFastBytes;
}
public LzmaEncoder()
{
for (int i = 0; i < kNumOpts; i++)
_optimum[i] = new Optimal();
for (int i = 0; i < Base.kNumLenToPosStates; i++)
_posSlotEncoder[i] = new RangeCoder.BitTreeEncoder(Base.kNumPosSlotBits);
}
void SetWriteEndMarkerMode(bool writeEndMarker)
{
_writeEndMark = writeEndMarker;
}
void Init()
{
BaseInit();
_rangeEncoder.Init();
uint i;
for (i = 0; i < Base.kNumStates; i++)
{
for (uint j = 0; j <= _posStateMask; j++)
{
uint complexState = (i << Base.kNumPosStatesBitsMax) + j;
_isMatch[complexState].Init();
_isRep0Long[complexState].Init();
}
_isRep[i].Init();
_isRepG0[i].Init();
_isRepG1[i].Init();
_isRepG2[i].Init();
}
_literalEncoder.Init();
for (i = 0; i < Base.kNumLenToPosStates; i++)
_posSlotEncoder[i].Init();
for (i = 0; i < Base.kNumFullDistances - Base.kEndPosModelIndex; i++)
_posEncoders[i].Init();
_lenEncoder.Init((UInt32)1 << _posStateBits);
_repMatchLenEncoder.Init((UInt32)1 << _posStateBits);
_posAlignEncoder.Init();
_longestMatchWasFound = false;
_optimumEndIndex = 0;
_optimumCurrentIndex = 0;
_additionalOffset = 0;
}
void ReadMatchDistances(out UInt32 lenRes, out UInt32 numDistancePairs)
{
lenRes = 0;
numDistancePairs = _matchFinder.GetMatches(_matchDistances);
if (numDistancePairs > 0)
{
lenRes = _matchDistances[numDistancePairs - 2];
if (lenRes == _numFastBytes)
lenRes += _matchFinder.GetMatchLen((int)lenRes - 1, _matchDistances[numDistancePairs - 1],
Base.kMatchMaxLen - lenRes);
}
_additionalOffset++;
}
void MovePos(UInt32 num)
{
if (num > 0)
{
_matchFinder.Skip(num);
_additionalOffset += num;
}
}
UInt32 GetRepLen1Price(Base.State state, UInt32 posState)
{
return _isRepG0[state.Index].GetPrice0() +
_isRep0Long[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0();
}
UInt32 GetPureRepPrice(UInt32 repIndex, Base.State state, UInt32 posState)
{
UInt32 price;
if (repIndex == 0)
{
price = _isRepG0[state.Index].GetPrice0();
price += _isRep0Long[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1();
}
else
{
price = _isRepG0[state.Index].GetPrice1();
if (repIndex == 1)
price += _isRepG1[state.Index].GetPrice0();
else
{
price += _isRepG1[state.Index].GetPrice1();
price += _isRepG2[state.Index].GetPrice(repIndex - 2);
}
}
return price;
}
UInt32 GetRepPrice(UInt32 repIndex, UInt32 len, Base.State state, UInt32 posState)
{
UInt32 price = _repMatchLenEncoder.GetPrice(len - Base.kMatchMinLen, posState);
return price + GetPureRepPrice(repIndex, state, posState);
}
UInt32 GetPosLenPrice(UInt32 pos, UInt32 len, UInt32 posState)
{
UInt32 price;
UInt32 lenToPosState = Base.GetLenToPosState(len);
if (pos < Base.kNumFullDistances)
price = _distancesPrices[(lenToPosState * Base.kNumFullDistances) + pos];
else
price = _posSlotPrices[(lenToPosState << Base.kNumPosSlotBits) + GetPosSlot2(pos)] +
_alignPrices[pos & Base.kAlignMask];
return price + _lenEncoder.GetPrice(len - Base.kMatchMinLen, posState);
}
UInt32 Backward(out UInt32 backRes, UInt32 cur)
{
_optimumEndIndex = cur;
UInt32 posMem = _optimum[cur].PosPrev;
UInt32 backMem = _optimum[cur].BackPrev;
do
{
if (_optimum[cur].Prev1IsChar)
{
_optimum[posMem].MakeAsChar();
_optimum[posMem].PosPrev = posMem - 1;
if (_optimum[cur].Prev2)
{
_optimum[posMem - 1].Prev1IsChar = false;
_optimum[posMem - 1].PosPrev = _optimum[cur].PosPrev2;
_optimum[posMem - 1].BackPrev = _optimum[cur].BackPrev2;
}
}
UInt32 posPrev = posMem;
UInt32 backCur = backMem;
backMem = _optimum[posPrev].BackPrev;
posMem = _optimum[posPrev].PosPrev;
_optimum[posPrev].BackPrev = backCur;
_optimum[posPrev].PosPrev = cur;
cur = posPrev;
}
while (cur > 0);
backRes = _optimum[0].BackPrev;
_optimumCurrentIndex = _optimum[0].PosPrev;
return _optimumCurrentIndex;
}
UInt32[] reps = new UInt32[Base.kNumRepDistances];
UInt32[] repLens = new UInt32[Base.kNumRepDistances];
UInt32 GetOptimum(UInt32 position, out UInt32 backRes)
{
if (_optimumEndIndex != _optimumCurrentIndex)
{
UInt32 lenRes = _optimum[_optimumCurrentIndex].PosPrev - _optimumCurrentIndex;
backRes = _optimum[_optimumCurrentIndex].BackPrev;
_optimumCurrentIndex = _optimum[_optimumCurrentIndex].PosPrev;
return lenRes;
}
_optimumCurrentIndex = _optimumEndIndex = 0;
UInt32 lenMain, numDistancePairs;
if (!_longestMatchWasFound)
{
ReadMatchDistances(out lenMain, out numDistancePairs);
}
else
{
lenMain = _longestMatchLength;
numDistancePairs = _numDistancePairs;
_longestMatchWasFound = false;
}
UInt32 numAvailableBytes = _matchFinder.GetNumAvailableBytes() + 1;
if (numAvailableBytes < 2)
{
backRes = 0xFFFFFFFF;
return 1;
}
if (numAvailableBytes > Base.kMatchMaxLen)
numAvailableBytes = Base.kMatchMaxLen;
UInt32 repMaxIndex = 0;
UInt32 i;
for (i = 0; i < Base.kNumRepDistances; i++)
{
reps[i] = _repDistances[i];
repLens[i] = _matchFinder.GetMatchLen(0 - 1, reps[i], Base.kMatchMaxLen);
if (repLens[i] > repLens[repMaxIndex])
repMaxIndex = i;
}
if (repLens[repMaxIndex] >= _numFastBytes)
{
backRes = repMaxIndex;
UInt32 lenRes = repLens[repMaxIndex];
MovePos(lenRes - 1);
return lenRes;
}
if (lenMain >= _numFastBytes)
{
backRes = _matchDistances[numDistancePairs - 1] + Base.kNumRepDistances;
MovePos(lenMain - 1);
return lenMain;
}
Byte currentByte = _matchFinder.GetIndexByte(0 - 1);
Byte matchByte = _matchFinder.GetIndexByte((Int32)(0 - _repDistances[0] - 1 - 1));
if (lenMain < 2 && currentByte != matchByte && repLens[repMaxIndex] < 2)
{
backRes = (UInt32)0xFFFFFFFF;
return 1;
}
_optimum[0].State = _state;
UInt32 posState = (position & _posStateMask);
_optimum[1].Price = _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0() +
_literalEncoder.GetSubCoder(position, _previousByte).GetPrice(!_state.IsCharState(), matchByte, currentByte);
_optimum[1].MakeAsChar();
UInt32 matchPrice = _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1();
UInt32 repMatchPrice = matchPrice + _isRep[_state.Index].GetPrice1();
if (matchByte == currentByte)
{
UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(_state, posState);
if (shortRepPrice < _optimum[1].Price)
{
_optimum[1].Price = shortRepPrice;
_optimum[1].MakeAsShortRep();
}
}
UInt32 lenEnd = ((lenMain >= repLens[repMaxIndex]) ? lenMain : repLens[repMaxIndex]);
if(lenEnd < 2)
{
backRes = _optimum[1].BackPrev;
return 1;
}
_optimum[1].PosPrev = 0;
_optimum[0].Backs0 = reps[0];
_optimum[0].Backs1 = reps[1];
_optimum[0].Backs2 = reps[2];
_optimum[0].Backs3 = reps[3];
UInt32 len = lenEnd;
do
_optimum[len--].Price = kIfinityPrice;
while (len >= 2);
for (i = 0; i < Base.kNumRepDistances; i++)
{
UInt32 repLen = repLens[i];
if (repLen < 2)
continue;
UInt32 price = repMatchPrice + GetPureRepPrice(i, _state, posState);
do
{
UInt32 curAndLenPrice = price + _repMatchLenEncoder.GetPrice(repLen - 2, posState);
Optimal optimum = _optimum[repLen];
if (curAndLenPrice < optimum.Price)
{
optimum.Price = curAndLenPrice;
optimum.PosPrev = 0;
optimum.BackPrev = i;
optimum.Prev1IsChar = false;
}
}
while (--repLen >= 2);
}
UInt32 normalMatchPrice = matchPrice + _isRep[_state.Index].GetPrice0();
len = ((repLens[0] >= 2) ? repLens[0] + 1 : 2);
if (len <= lenMain)
{
UInt32 offs = 0;
while (len > _matchDistances[offs])
offs += 2;
for (; ; len++)
{
UInt32 distance = _matchDistances[offs + 1];
UInt32 curAndLenPrice = normalMatchPrice + GetPosLenPrice(distance, len, posState);
Optimal optimum = _optimum[len];
if (curAndLenPrice < optimum.Price)
{
optimum.Price = curAndLenPrice;
optimum.PosPrev = 0;
optimum.BackPrev = distance + Base.kNumRepDistances;
optimum.Prev1IsChar = false;
}
if (len == _matchDistances[offs])
{
offs += 2;
if (offs == numDistancePairs)
break;
}
}
}
UInt32 cur = 0;
while (true)
{
cur++;
if (cur == lenEnd)
return Backward(out backRes, cur);
UInt32 newLen;
ReadMatchDistances(out newLen, out numDistancePairs);
if (newLen >= _numFastBytes)
{
_numDistancePairs = numDistancePairs;
_longestMatchLength = newLen;
_longestMatchWasFound = true;
return Backward(out backRes, cur);
}
position++;
UInt32 posPrev = _optimum[cur].PosPrev;
Base.State state;
if (_optimum[cur].Prev1IsChar)
{
posPrev--;
if (_optimum[cur].Prev2)
{
state = _optimum[_optimum[cur].PosPrev2].State;
if (_optimum[cur].BackPrev2 < Base.kNumRepDistances)
state.UpdateRep();
else
state.UpdateMatch();
}
else
state = _optimum[posPrev].State;
state.UpdateChar();
}
else
state = _optimum[posPrev].State;
if (posPrev == cur - 1)
{
if (_optimum[cur].IsShortRep())
state.UpdateShortRep();
else
state.UpdateChar();
}
else
{
UInt32 pos;
if (_optimum[cur].Prev1IsChar && _optimum[cur].Prev2)
{
posPrev = _optimum[cur].PosPrev2;
pos = _optimum[cur].BackPrev2;
state.UpdateRep();
}
else
{
pos = _optimum[cur].BackPrev;
if (pos < Base.kNumRepDistances)
state.UpdateRep();
else
state.UpdateMatch();
}
Optimal opt = _optimum[posPrev];
if (pos < Base.kNumRepDistances)
{
if (pos == 0)
{
reps[0] = opt.Backs0;
reps[1] = opt.Backs1;
reps[2] = opt.Backs2;
reps[3] = opt.Backs3;
}
else if (pos == 1)
{
reps[0] = opt.Backs1;
reps[1] = opt.Backs0;
reps[2] = opt.Backs2;
reps[3] = opt.Backs3;
}
else if (pos == 2)
{
reps[0] = opt.Backs2;
reps[1] = opt.Backs0;
reps[2] = opt.Backs1;
reps[3] = opt.Backs3;
}
else
{
reps[0] = opt.Backs3;
reps[1] = opt.Backs0;
reps[2] = opt.Backs1;
reps[3] = opt.Backs2;
}
}
else
{
reps[0] = (pos - Base.kNumRepDistances);
reps[1] = opt.Backs0;
reps[2] = opt.Backs1;
reps[3] = opt.Backs2;
}
}
_optimum[cur].State = state;
_optimum[cur].Backs0 = reps[0];
_optimum[cur].Backs1 = reps[1];
_optimum[cur].Backs2 = reps[2];
_optimum[cur].Backs3 = reps[3];
UInt32 curPrice = _optimum[cur].Price;
currentByte = _matchFinder.GetIndexByte(0 - 1);
matchByte = _matchFinder.GetIndexByte((Int32)(0 - reps[0] - 1 - 1));
posState = (position & _posStateMask);
UInt32 curAnd1Price = curPrice +
_isMatch[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0() +
_literalEncoder.GetSubCoder(position, _matchFinder.GetIndexByte(0 - 2)).
GetPrice(!state.IsCharState(), matchByte, currentByte);
Optimal nextOptimum = _optimum[cur + 1];
bool nextIsChar = false;
if (curAnd1Price < nextOptimum.Price)
{
nextOptimum.Price = curAnd1Price;
nextOptimum.PosPrev = cur;
nextOptimum.MakeAsChar();
nextIsChar = true;
}
matchPrice = curPrice + _isMatch[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1();
repMatchPrice = matchPrice + _isRep[state.Index].GetPrice1();
if (matchByte == currentByte &&
!(nextOptimum.PosPrev < cur && nextOptimum.BackPrev == 0))
{
UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(state, posState);
if (shortRepPrice <= nextOptimum.Price)
{
nextOptimum.Price = shortRepPrice;
nextOptimum.PosPrev = cur;
nextOptimum.MakeAsShortRep();
nextIsChar = true;
}
}
UInt32 numAvailableBytesFull = _matchFinder.GetNumAvailableBytes() + 1;
numAvailableBytesFull = Math.Min(kNumOpts - 1 - cur, numAvailableBytesFull);
numAvailableBytes = numAvailableBytesFull;
if (numAvailableBytes < 2)
continue;
if (numAvailableBytes > _numFastBytes)
numAvailableBytes = _numFastBytes;
if (!nextIsChar && matchByte != currentByte)
{
// try Literal + rep0
UInt32 t = Math.Min(numAvailableBytesFull - 1, _numFastBytes);
UInt32 lenTest2 = _matchFinder.GetMatchLen(0, reps[0], t);
if (lenTest2 >= 2)
{
Base.State state2 = state;
state2.UpdateChar();
UInt32 posStateNext = (position + 1) & _posStateMask;
UInt32 nextRepMatchPrice = curAnd1Price +
_isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice1() +
_isRep[state2.Index].GetPrice1();
{
UInt32 offset = cur + 1 + lenTest2;
while (lenEnd < offset)
_optimum[++lenEnd].Price = kIfinityPrice;
UInt32 curAndLenPrice = nextRepMatchPrice + GetRepPrice(
0, lenTest2, state2, posStateNext);
Optimal optimum = _optimum[offset];
if (curAndLenPrice < optimum.Price)
{
optimum.Price = curAndLenPrice;
optimum.PosPrev = cur + 1;
optimum.BackPrev = 0;
optimum.Prev1IsChar = true;
optimum.Prev2 = false;
}
}
}
}
UInt32 startLen = 2; // speed optimization
for (UInt32 repIndex = 0; repIndex < Base.kNumRepDistances; repIndex++)
{
UInt32 lenTest = _matchFinder.GetMatchLen(0 - 1, reps[repIndex], numAvailableBytes);
if (lenTest < 2)
continue;
UInt32 lenTestTemp = lenTest;
do
{
while (lenEnd < cur + lenTest)
_optimum[++lenEnd].Price = kIfinityPrice;
UInt32 curAndLenPrice = repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState);
Optimal optimum = _optimum[cur + lenTest];
if (curAndLenPrice < optimum.Price)
{
optimum.Price = curAndLenPrice;
optimum.PosPrev = cur;
optimum.BackPrev = repIndex;
optimum.Prev1IsChar = false;
}
}
while(--lenTest >= 2);
lenTest = lenTestTemp;
if (repIndex == 0)
startLen = lenTest + 1;
// if (_maxMode)
if (lenTest < numAvailableBytesFull)
{
UInt32 t = Math.Min(numAvailableBytesFull - 1 - lenTest, _numFastBytes);
UInt32 lenTest2 = _matchFinder.GetMatchLen((Int32)lenTest, reps[repIndex], t);
if (lenTest2 >= 2)
{
Base.State state2 = state;
state2.UpdateRep();
UInt32 posStateNext = (position + lenTest) & _posStateMask;
UInt32 curAndLenCharPrice =
repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState) +
_isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice0() +
_literalEncoder.GetSubCoder(position + lenTest,
_matchFinder.GetIndexByte((Int32)lenTest - 1 - 1)).GetPrice(true,
_matchFinder.GetIndexByte((Int32)((Int32)lenTest - 1 - (Int32)(reps[repIndex] + 1))),
_matchFinder.GetIndexByte((Int32)lenTest - 1));
state2.UpdateChar();
posStateNext = (position + lenTest + 1) & _posStateMask;
UInt32 nextMatchPrice = curAndLenCharPrice + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice1();
UInt32 nextRepMatchPrice = nextMatchPrice + _isRep[state2.Index].GetPrice1();
// for(; lenTest2 >= 2; lenTest2--)
{
UInt32 offset = lenTest + 1 + lenTest2;
while(lenEnd < cur + offset)
_optimum[++lenEnd].Price = kIfinityPrice;
UInt32 curAndLenPrice = nextRepMatchPrice + GetRepPrice(0, lenTest2, state2, posStateNext);
Optimal optimum = _optimum[cur + offset];
if (curAndLenPrice < optimum.Price)
{
optimum.Price = curAndLenPrice;
optimum.PosPrev = cur + lenTest + 1;
optimum.BackPrev = 0;
optimum.Prev1IsChar = true;
optimum.Prev2 = true;
optimum.PosPrev2 = cur;
optimum.BackPrev2 = repIndex;
}
}
}
}
}
if (newLen > numAvailableBytes)
{
newLen = numAvailableBytes;
for (numDistancePairs = 0; newLen > _matchDistances[numDistancePairs]; numDistancePairs += 2) ;
_matchDistances[numDistancePairs] = newLen;
numDistancePairs += 2;
}
if (newLen >= startLen)
{
normalMatchPrice = matchPrice + _isRep[state.Index].GetPrice0();
while (lenEnd < cur + newLen)
_optimum[++lenEnd].Price = kIfinityPrice;
UInt32 offs = 0;
while (startLen > _matchDistances[offs])
offs += 2;
for (UInt32 lenTest = startLen; ; lenTest++)
{
UInt32 curBack = _matchDistances[offs + 1];
UInt32 curAndLenPrice = normalMatchPrice + GetPosLenPrice(curBack, lenTest, posState);
Optimal optimum = _optimum[cur + lenTest];
if (curAndLenPrice < optimum.Price)
{
optimum.Price = curAndLenPrice;
optimum.PosPrev = cur;
optimum.BackPrev = curBack + Base.kNumRepDistances;
optimum.Prev1IsChar = false;
}
if (lenTest == _matchDistances[offs])
{
if (lenTest < numAvailableBytesFull)
{
UInt32 t = Math.Min(numAvailableBytesFull - 1 - lenTest, _numFastBytes);
UInt32 lenTest2 = _matchFinder.GetMatchLen((Int32)lenTest, curBack, t);
if (lenTest2 >= 2)
{
Base.State state2 = state;
state2.UpdateMatch();
UInt32 posStateNext = (position + lenTest) & _posStateMask;
UInt32 curAndLenCharPrice = curAndLenPrice +
_isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice0() +
_literalEncoder.GetSubCoder(position + lenTest,
_matchFinder.GetIndexByte((Int32)lenTest - 1 - 1)).
GetPrice(true,
_matchFinder.GetIndexByte((Int32)lenTest - (Int32)(curBack + 1) - 1),
_matchFinder.GetIndexByte((Int32)lenTest - 1));
state2.UpdateChar();
posStateNext = (position + lenTest + 1) & _posStateMask;
UInt32 nextMatchPrice = curAndLenCharPrice + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice1();
UInt32 nextRepMatchPrice = nextMatchPrice + _isRep[state2.Index].GetPrice1();
UInt32 offset = lenTest + 1 + lenTest2;
while (lenEnd < cur + offset)
_optimum[++lenEnd].Price = kIfinityPrice;
curAndLenPrice = nextRepMatchPrice + GetRepPrice(0, lenTest2, state2, posStateNext);
optimum = _optimum[cur + offset];
if (curAndLenPrice < optimum.Price)
{
optimum.Price = curAndLenPrice;
optimum.PosPrev = cur + lenTest + 1;
optimum.BackPrev = 0;
optimum.Prev1IsChar = true;
optimum.Prev2 = true;
optimum.PosPrev2 = cur;
optimum.BackPrev2 = curBack + Base.kNumRepDistances;
}
}
}
offs += 2;
if (offs == numDistancePairs)
break;
}
}
}
}
}
bool ChangePair(UInt32 smallDist, UInt32 bigDist)
{
const int kDif = 7;
return (smallDist < ((UInt32)(1) << (32 - kDif)) && bigDist >= (smallDist << kDif));
}
void WriteEndMarker(UInt32 posState)
{
if (!_writeEndMark)
return;
_isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].Encode(_rangeEncoder, 1);
_isRep[_state.Index].Encode(_rangeEncoder, 0);
_state.UpdateMatch();
UInt32 len = Base.kMatchMinLen;
_lenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState);
UInt32 posSlot = (1 << Base.kNumPosSlotBits) - 1;
UInt32 lenToPosState = Base.GetLenToPosState(len);
_posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot);
int footerBits = 30;
UInt32 posReduced = (((UInt32)1) << footerBits) - 1;
_rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, footerBits - Base.kNumAlignBits);
_posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.kAlignMask);
}
void Flush(UInt32 nowPos)
{
ReleaseMFStream();
WriteEndMarker(nowPos & _posStateMask);
_rangeEncoder.FlushData();
_rangeEncoder.FlushStream();
}
public void CodeOneBlock(out Int64 inSize, out Int64 outSize, out bool finished)
{
inSize = 0;
outSize = 0;
finished = true;
if (_inStream != null)
{
_matchFinder.SetStream(_inStream);
_matchFinder.Init();
_needReleaseMFStream = true;
_inStream = null;
if (_trainSize > 0)
_matchFinder.Skip(_trainSize);
}
if (_finished)
return;
_finished = true;
Int64 progressPosValuePrev = nowPos64;
if (nowPos64 == 0)
{
if (_matchFinder.GetNumAvailableBytes() == 0)
{
Flush((UInt32)nowPos64);
return;
}
UInt32 len, numDistancePairs; // it's not used
ReadMatchDistances(out len, out numDistancePairs);
UInt32 posState = (UInt32)(nowPos64) & _posStateMask;
_isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].Encode(_rangeEncoder, 0);
_state.UpdateChar();
Byte curByte = _matchFinder.GetIndexByte((Int32)(0 - _additionalOffset));
_literalEncoder.GetSubCoder((UInt32)(nowPos64), _previousByte).Encode(_rangeEncoder, curByte);
_previousByte = curByte;
_additionalOffset--;
nowPos64++;
}
if (_matchFinder.GetNumAvailableBytes() == 0)
{
Flush((UInt32)nowPos64);
return;
}
while (true)
{
UInt32 pos;
UInt32 len = GetOptimum((UInt32)nowPos64, out pos);
UInt32 posState = ((UInt32)nowPos64) & _posStateMask;
UInt32 complexState = (_state.Index << Base.kNumPosStatesBitsMax) + posState;
if (len == 1 && pos == 0xFFFFFFFF)
{
_isMatch[complexState].Encode(_rangeEncoder, 0);
Byte curByte = _matchFinder.GetIndexByte((Int32)(0 - _additionalOffset));
LiteralEncoder.Encoder2 subCoder = _literalEncoder.GetSubCoder((UInt32)nowPos64, _previousByte);
if (!_state.IsCharState())
{
Byte matchByte = _matchFinder.GetIndexByte((Int32)(0 - _repDistances[0] - 1 - _additionalOffset));
subCoder.EncodeMatched(_rangeEncoder, matchByte, curByte);
}
else
subCoder.Encode(_rangeEncoder, curByte);
_previousByte = curByte;
_state.UpdateChar();
}
else
{
_isMatch[complexState].Encode(_rangeEncoder, 1);
if (pos < Base.kNumRepDistances)
{
_isRep[_state.Index].Encode(_rangeEncoder, 1);
if (pos == 0)
{
_isRepG0[_state.Index].Encode(_rangeEncoder, 0);
if (len == 1)
_isRep0Long[complexState].Encode(_rangeEncoder, 0);
else
_isRep0Long[complexState].Encode(_rangeEncoder, 1);
}
else
{
_isRepG0[_state.Index].Encode(_rangeEncoder, 1);
if (pos == 1)
_isRepG1[_state.Index].Encode(_rangeEncoder, 0);
else
{
_isRepG1[_state.Index].Encode(_rangeEncoder, 1);
_isRepG2[_state.Index].Encode(_rangeEncoder, pos - 2);
}
}
if (len == 1)
_state.UpdateShortRep();
else
{
_repMatchLenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState);
_state.UpdateRep();
}
UInt32 distance = _repDistances[pos];
if (pos != 0)
{
for (UInt32 i = pos; i >= 1; i--)
_repDistances[i] = _repDistances[i - 1];
_repDistances[0] = distance;
}
}
else
{
_isRep[_state.Index].Encode(_rangeEncoder, 0);
_state.UpdateMatch();
_lenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState);
pos -= Base.kNumRepDistances;
UInt32 posSlot = GetPosSlot(pos);
UInt32 lenToPosState = Base.GetLenToPosState(len);
_posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot);
if (posSlot >= Base.kStartPosModelIndex)
{
int footerBits = (int)((posSlot >> 1) - 1);
UInt32 baseVal = ((2 | (posSlot & 1)) << footerBits);
UInt32 posReduced = pos - baseVal;
if (posSlot < Base.kEndPosModelIndex)
RangeCoder.BitTreeEncoder.ReverseEncode(_posEncoders,
baseVal - posSlot - 1, _rangeEncoder, footerBits, posReduced);
else
{
_rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, footerBits - Base.kNumAlignBits);
_posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.kAlignMask);
_alignPriceCount++;
}
}
UInt32 distance = pos;
for (UInt32 i = Base.kNumRepDistances - 1; i >= 1; i--)
_repDistances[i] = _repDistances[i - 1];
_repDistances[0] = distance;
_matchPriceCount++;
}
_previousByte = _matchFinder.GetIndexByte((Int32)(len - 1 - _additionalOffset));
}
_additionalOffset -= len;
nowPos64 += len;
if (_additionalOffset == 0)
{
// if (!_fastMode)
if (_matchPriceCount >= (1 << 7))
FillDistancesPrices();
if (_alignPriceCount >= Base.kAlignTableSize)
FillAlignPrices();
inSize = nowPos64;
outSize = _rangeEncoder.GetProcessedSizeAdd();
if (_matchFinder.GetNumAvailableBytes() == 0)
{
Flush((UInt32)nowPos64);
return;
}
if (nowPos64 - progressPosValuePrev >= (1 << 12))
{
_finished = false;
finished = false;
return;
}
}
}
}
void ReleaseMFStream()
{
if (_matchFinder != null && _needReleaseMFStream)
{
_matchFinder.ReleaseStream();
_needReleaseMFStream = false;
}
}
void SetOutStream(System.IO.Stream outStream) { _rangeEncoder.SetStream(outStream); }
void ReleaseOutStream() { _rangeEncoder.ReleaseStream(); }
void ReleaseStreams()
{
ReleaseMFStream();
ReleaseOutStream();
}
void SetStreams(System.IO.Stream inStream, System.IO.Stream outStream,
Int64 inSize, Int64 outSize)
{
_inStream = inStream;
_finished = false;
Create();
SetOutStream(outStream);
Init();
// if (!_fastMode)
{
FillDistancesPrices();
FillAlignPrices();
}
_lenEncoder.SetTableSize(_numFastBytes + 1 - Base.kMatchMinLen);
_lenEncoder.UpdateTables((UInt32)1 << _posStateBits);
_repMatchLenEncoder.SetTableSize(_numFastBytes + 1 - Base.kMatchMinLen);
_repMatchLenEncoder.UpdateTables((UInt32)1 << _posStateBits);
nowPos64 = 0;
}
public void Code(System.IO.Stream inStream, System.IO.Stream outStream,
Int64 inSize, Int64 outSize, ICodeProgress progress)
{
_needReleaseMFStream = false;
try
{
SetStreams(inStream, outStream, inSize, outSize);
while (true)
{
Int64 processedInSize;
Int64 processedOutSize;
bool finished;
CodeOneBlock(out processedInSize, out processedOutSize, out finished);
if (finished)
return;
if (progress != null)
{
progress.SetProgress(processedInSize, processedOutSize);
}
}
}
finally
{
ReleaseStreams();
}
}
const int kPropSize = 5;
Byte[] properties = new Byte[kPropSize];
public void WriteCoderProperties(System.IO.Stream outStream)
{
properties[0] = (Byte)((_posStateBits * 5 + _numLiteralPosStateBits) * 9 + _numLiteralContextBits);
for (int i = 0; i < 4; i++)
properties[1 + i] = (Byte)((_dictionarySize >> (8 * i)) & 0xFF);
outStream.Write(properties, 0, kPropSize);
}
UInt32[] tempPrices = new UInt32[Base.kNumFullDistances];
UInt32 _matchPriceCount;
void FillDistancesPrices()
{
for (UInt32 i = Base.kStartPosModelIndex; i < Base.kNumFullDistances; i++)
{
UInt32 posSlot = GetPosSlot(i);
int footerBits = (int)((posSlot >> 1) - 1);
UInt32 baseVal = ((2 | (posSlot & 1)) << footerBits);
tempPrices[i] = BitTreeEncoder.ReverseGetPrice(_posEncoders,
baseVal - posSlot - 1, footerBits, i - baseVal);
}
for (UInt32 lenToPosState = 0; lenToPosState < Base.kNumLenToPosStates; lenToPosState++)
{
UInt32 posSlot;
RangeCoder.BitTreeEncoder encoder = _posSlotEncoder[lenToPosState];
UInt32 st = (lenToPosState << Base.kNumPosSlotBits);
for (posSlot = 0; posSlot < _distTableSize; posSlot++)
_posSlotPrices[st + posSlot] = encoder.GetPrice(posSlot);
for (posSlot = Base.kEndPosModelIndex; posSlot < _distTableSize; posSlot++)
_posSlotPrices[st + posSlot] += ((((posSlot >> 1) - 1) - Base.kNumAlignBits) << RangeCoder.BitEncoder.kNumBitPriceShiftBits);
UInt32 st2 = lenToPosState * Base.kNumFullDistances;
UInt32 i;
for (i = 0; i < Base.kStartPosModelIndex; i++)
_distancesPrices[st2 + i] = _posSlotPrices[st + i];
for (; i < Base.kNumFullDistances; i++)
_distancesPrices[st2 + i] = _posSlotPrices[st + GetPosSlot(i)] + tempPrices[i];
}
_matchPriceCount = 0;
}
void FillAlignPrices()
{
for (UInt32 i = 0; i < Base.kAlignTableSize; i++)
_alignPrices[i] = _posAlignEncoder.ReverseGetPrice(i);
_alignPriceCount = 0;
}
static string[] kMatchFinderIDs =
{
"BT2",
"BT4",
};
static int FindMatchFinder(string s)
{
for (int m = 0; m < kMatchFinderIDs.Length; m++)
if (s == kMatchFinderIDs[m])
return m;
return -1;
}
public void SetCoderProperties(CoderPropID[] propIDs, object[] properties)
{
for (UInt32 i = 0; i < properties.Length; i++)
{
object prop = properties[i];
switch (propIDs[i])
{
case CoderPropID.NumFastBytes:
{
if (!(prop is Int32))
throw new InvalidParamException();
Int32 numFastBytes = (Int32)prop;
if (numFastBytes < 5 || numFastBytes > Base.kMatchMaxLen)
throw new InvalidParamException();
_numFastBytes = (UInt32)numFastBytes;
break;
}
case CoderPropID.Algorithm:
{
/*
if (!(prop is Int32))
throw new InvalidParamException();
Int32 maximize = (Int32)prop;
_fastMode = (maximize == 0);
_maxMode = (maximize >= 2);
*/
break;
}
case CoderPropID.MatchFinder:
{
if (!(prop is String))
throw new InvalidParamException();
EMatchFinderType matchFinderIndexPrev = _matchFinderType;
int m = FindMatchFinder(((string)prop).ToUpper());
if (m < 0)
throw new InvalidParamException();
_matchFinderType = (EMatchFinderType)m;
if (_matchFinder != null && matchFinderIndexPrev != _matchFinderType)
{
_dictionarySizePrev = 0xFFFFFFFF;
_matchFinder = null;
}
break;
}
case CoderPropID.DictionarySize:
{
const int kDicLogSizeMaxCompress = 30;
if (!(prop is Int32))
throw new InvalidParamException(); ;
Int32 dictionarySize = (Int32)prop;
if (dictionarySize < (UInt32)(1 << Base.kDicLogSizeMin) ||
dictionarySize > (UInt32)(1 << kDicLogSizeMaxCompress))
throw new InvalidParamException();
_dictionarySize = (UInt32)dictionarySize;
int dicLogSize;
for (dicLogSize = 0; dicLogSize < (UInt32)kDicLogSizeMaxCompress; dicLogSize++)
if (dictionarySize <= ((UInt32)(1) << dicLogSize))
break;
_distTableSize = (UInt32)dicLogSize * 2;
break;
}
case CoderPropID.PosStateBits:
{
if (!(prop is Int32))
throw new InvalidParamException();
Int32 v = (Int32)prop;
if (v < 0 || v > (UInt32)Base.kNumPosStatesBitsEncodingMax)
throw new InvalidParamException();
_posStateBits = (int)v;
_posStateMask = (((UInt32)1) << (int)_posStateBits) - 1;
break;
}
case CoderPropID.LitPosBits:
{
if (!(prop is Int32))
throw new InvalidParamException();
Int32 v = (Int32)prop;
if (v < 0 || v > (UInt32)Base.kNumLitPosStatesBitsEncodingMax)
throw new InvalidParamException();
_numLiteralPosStateBits = (int)v;
break;
}
case CoderPropID.LitContextBits:
{
if (!(prop is Int32))
throw new InvalidParamException();
Int32 v = (Int32)prop;
if (v < 0 || v > (UInt32)Base.kNumLitContextBitsMax)
throw new InvalidParamException(); ;
_numLiteralContextBits = (int)v;
break;
}
case CoderPropID.EndMarker:
{
if (!(prop is Boolean))
throw new InvalidParamException();
SetWriteEndMarkerMode((Boolean)prop);
break;
}
default:
throw new InvalidParamException();
}
}
}
uint _trainSize = 0;
public void SetTrainSize(uint trainSize)
{
_trainSize = trainSize;
}
}
}
| |
using DevExpress.Internal;
using DevExpress.Mvvm.UI.Interactivity;
using DevExpress.Mvvm.UI.Native;
using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace DevExpress.Mvvm.UI {
public enum NotificationSetting {
Enabled = 0,
DisabledForApplication = 1,
DisabledForUser = 2,
DisabledByGroupPolicy = 3,
DisabledByManifest = 4
}
public enum ToastDismissalReason : long {
UserCanceled = 0,
ApplicationHidden = 1,
TimedOut = 2
}
public enum PredefinedSound {
Notification_Default,
NoSound,
Notification_IM,
Notification_Mail,
Notification_Reminder,
Notification_SMS,
Notification_Looping_Alarm,
Notification_Looping_Alarm2,
Notification_Looping_Alarm3,
Notification_Looping_Alarm4,
Notification_Looping_Alarm5,
Notification_Looping_Alarm6,
Notification_Looping_Alarm7,
Notification_Looping_Alarm8,
Notification_Looping_Alarm9,
Notification_Looping_Alarm10,
Notification_Looping_Call,
Notification_Looping_Call2,
Notification_Looping_Call3,
Notification_Looping_Call4,
Notification_Looping_Call5,
Notification_Looping_Call6,
Notification_Looping_Call7,
Notification_Looping_Call8,
Notification_Looping_Call9,
Notification_Looping_Call10,
}
public enum PredefinedNotificationDuration {
Default,
Long
}
public enum NotificationTemplate {
LongText,
ShortHeaderAndLongText,
LongHeaderAndShortText,
ShortHeaderAndTwoTextFields
}
public enum NotificationPosition {
BottomRight, TopRight
}
[TargetTypeAttribute(typeof(UserControl))]
[TargetTypeAttribute(typeof(Window))]
public class NotificationService : ServiceBase, INotificationService {
class MvvmPredefinedNotification : INotification {
public IPredefinedToastNotification Notification { get; set; }
public Task<NotificationResult> ShowAsync() {
return Notification.ShowAsync().ContinueWith(t => (NotificationResult)t.Result);
}
public void Hide() {
Notification.Hide();
}
}
class MvvmCustomNotification : INotification {
CustomNotifier notifier;
CustomNotification notification;
int duration;
public MvvmCustomNotification(object viewModel, CustomNotifier notifier, int duration) {
this.notifier = notifier;
this.duration = duration;
this.notification = new CustomNotification(viewModel, notifier);
}
public void Hide() {
notifier.Hide(notification);
}
public Task<NotificationResult> ShowAsync() {
return notifier.ShowAsync(notification, duration);
}
}
public static readonly DependencyProperty UseWin8NotificationsIfAvailableProperty =
DependencyProperty.Register("UseWin8NotificationsIfAvailable", typeof(bool), typeof(NotificationService), new PropertyMetadata(true,
(d, e) => ((NotificationService)d).OnUseWin8NotificationsIfAvailableChanged()));
public static readonly DependencyProperty CustomNotificationStyleProperty =
DependencyProperty.Register("CustomNotificationStyle", typeof(Style), typeof(NotificationService), new PropertyMetadata(null,
(d, e) => ((NotificationService)d).OnCustomNotificationStyleChanged()));
public static readonly DependencyProperty CustomNotificationTemplateProperty =
DependencyProperty.Register("CustomNotificationTemplate", typeof(DataTemplate), typeof(NotificationService), new PropertyMetadata(null,
(d, e) => ((NotificationService)d).OnCustomNotificationTemplateChanged()));
public static readonly DependencyProperty CustomNotificationTemplateSelectorProperty =
DependencyProperty.Register("CustomNotificationTemplateSelector", typeof(DataTemplateSelector), typeof(NotificationService), new PropertyMetadata(null,
(d, e) => ((NotificationService)d).OnCustomNotificationTemplateSelectorChanged()));
public static readonly DependencyProperty CustomNotificationDurationProperty =
DependencyProperty.Register("CustomNotificationDuration", typeof(TimeSpan), typeof(NotificationService), new PropertyMetadata(TimeSpan.FromMilliseconds(6000)));
public static readonly DependencyProperty CustomNotificationPositionProperty =
DependencyProperty.Register("CustomNotificationPosition", typeof(NotificationPosition), typeof(NotificationService), new PropertyMetadata(NotificationPosition.TopRight,
(d, e) => ((NotificationService)d).UpdateCustomNotifierPositioner()));
public static readonly DependencyProperty CustomNotificationVisibleMaxCountProperty =
DependencyProperty.Register("CustomNotificationVisibleMaxCount", typeof(int), typeof(NotificationService), new PropertyMetadata(3,
(d, e) => ((NotificationService)d).UpdateCustomNotifierPositioner()));
public static readonly DependencyProperty PredefinedNotificationTemplateProperty =
DependencyProperty.Register("PredefinedNotificationTemplate", typeof(NotificationTemplate), typeof(NotificationService), new PropertyMetadata(NotificationTemplate.LongText));
public static readonly DependencyProperty ApplicationIdProperty =
DependencyProperty.Register("ApplicationId", typeof(string), typeof(NotificationService), new PropertyMetadata(null));
public static readonly DependencyProperty PredefinedNotificationDurationProperty =
DependencyProperty.Register("PredefinedNotificationDuration", typeof(PredefinedNotificationDuration), typeof(NotificationService), new PropertyMetadata(PredefinedNotificationDuration.Default));
public static readonly DependencyProperty SoundProperty =
DependencyProperty.Register("Sound", typeof(PredefinedSound), typeof(NotificationService), new PropertyMetadata(PredefinedSound.Notification_Default));
IPredefinedToastNotificationFactory factory;
IPredefinedToastNotificationFactory Factory {
get {
if(factory == null) {
if(UseWin8NotificationsIfAvailable && AreWin8NotificationsAvailable) {
if(ApplicationId == null)
throw new ArgumentNullException("ApplicationId");
factory = new WinRTToastNotificationFactory(ApplicationId);
} else {
factory = new WpfToastNotificationFactory();
}
}
return factory;
}
}
CustomNotifier customNotifier;
CustomNotifier CustomNotifier {
get {
if(customNotifier == null) {
customNotifier = new CustomNotifier();
}
return customNotifier;
}
}
public bool UseWin8NotificationsIfAvailable {
get { return (bool)GetValue(UseWin8NotificationsIfAvailableProperty); }
set { SetValue(UseWin8NotificationsIfAvailableProperty, value); }
}
public Style CustomNotificationStyle {
get { return (Style)GetValue(CustomNotificationStyleProperty); }
set { SetValue(CustomNotificationStyleProperty, value); }
}
public DataTemplate CustomNotificationTemplate {
get { return (DataTemplate)GetValue(CustomNotificationTemplateProperty); }
set { SetValue(CustomNotificationTemplateProperty, value); }
}
public DataTemplateSelector CustomNotificationTemplateSelector {
get { return (DataTemplateSelector)GetValue(CustomNotificationTemplateSelectorProperty); }
set { SetValue(CustomNotificationTemplateSelectorProperty, value); }
}
public TimeSpan CustomNotificationDuration {
get { return (TimeSpan)GetValue(CustomNotificationDurationProperty); }
set { SetValue(CustomNotificationDurationProperty, value); }
}
public NotificationPosition CustomNotificationPosition {
get { return (NotificationPosition)GetValue(CustomNotificationPositionProperty); }
set { SetValue(CustomNotificationPositionProperty, value); }
}
public int CustomNotificationVisibleMaxCount {
get { return (int)GetValue(CustomNotificationVisibleMaxCountProperty); }
set { SetValue(CustomNotificationVisibleMaxCountProperty, value); }
}
void UpdateCustomNotifierPositioner() {
CustomNotifier.UpdatePositioner(CustomNotificationPosition, CustomNotificationVisibleMaxCount);
}
void OnCustomNotificationTemplateChanged() {
CustomNotifier.ContentTemplate = CustomNotificationTemplate;
}
void OnCustomNotificationTemplateSelectorChanged() {
CustomNotifier.ContentTemplateSelector = CustomNotificationTemplateSelector;
}
void OnCustomNotificationStyleChanged() {
CustomNotifier.Style = CustomNotificationStyle;
}
void OnUseWin8NotificationsIfAvailableChanged() {
factory = null;
}
public string ApplicationId {
get { return (string)GetValue(ApplicationIdProperty); }
set { SetValue(ApplicationIdProperty, value); }
}
public NotificationTemplate PredefinedNotificationTemplate {
get { return (NotificationTemplate)GetValue(PredefinedNotificationTemplateProperty); }
set { SetValue(PredefinedNotificationTemplateProperty, value); }
}
public PredefinedSound Sound {
get { return (PredefinedSound)GetValue(SoundProperty); }
set { SetValue(SoundProperty, value); }
}
public PredefinedNotificationDuration PredefinedNotificationDuration {
get { return (PredefinedNotificationDuration)GetValue(PredefinedNotificationDurationProperty); }
set { SetValue(PredefinedNotificationDurationProperty, value); }
}
public bool AreWin8NotificationsAvailable {
get { return DevExpress.Internal.WinApi.ToastNotificationManager.AreToastNotificationsSupported; }
}
public INotification CreateCustomNotification(object viewModel) {
return new MvvmCustomNotification(viewModel, CustomNotifier, (int)CustomNotificationDuration.TotalMilliseconds);
}
public INotification CreatePredefinedNotification(
string text1,
string text2,
string text3,
ImageSource image = null)
{
IPredefinedToastNotificationContentFactory cf = Factory.CreateContentFactory();
IPredefinedToastNotificationContent content = null;
switch(PredefinedNotificationTemplate) {
case NotificationTemplate.LongText:
content = cf.CreateContent(text1);
break;
case NotificationTemplate.ShortHeaderAndLongText:
content = cf.CreateOneLineHeaderContent(text1, text2);
break;
case NotificationTemplate.LongHeaderAndShortText:
content = cf.CreateTwoLineHeaderContent(text1, text2);
break;
case NotificationTemplate.ShortHeaderAndTwoTextFields:
content = cf.CreateOneLineHeaderContent(text1, text2, text3);
break;
}
if(image != null) {
content.SetImage(ImageLoader2.ImageToByteArray(image, GetBaseUri));
}
content.SetDuration((DevExpress.Internal.NotificationDuration)PredefinedNotificationDuration);
content.SetSound((DevExpress.Internal.PredefinedSound)Sound);
return new MvvmPredefinedNotification { Notification = Factory.CreateToastNotification(content) };
}
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="Log.DestinationRemoteSyslogBinding", Namespace="urn:iControl")]
public partial class LogDestinationRemoteSyslog : iControlInterface {
public LogDestinationRemoteSyslog() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationRemoteSyslog",
RequestNamespace="urn:iControl:Log/DestinationRemoteSyslog", ResponseNamespace="urn:iControl:Log/DestinationRemoteSyslog")]
public void create(
string [] destinations,
LogSyslogFacility [] facilities,
LogSyslogLevel [] levels,
string [] hsl_destinations
) {
this.Invoke("create", new object [] {
destinations,
facilities,
levels,
hsl_destinations});
}
public System.IAsyncResult Begincreate(string [] destinations,LogSyslogFacility [] facilities,LogSyslogLevel [] levels,string [] hsl_destinations, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
destinations,
facilities,
levels,
hsl_destinations}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// create_v2
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationRemoteSyslog",
RequestNamespace="urn:iControl:Log/DestinationRemoteSyslog", ResponseNamespace="urn:iControl:Log/DestinationRemoteSyslog")]
public void create_v2(
string [] destinations,
LogSyslogFacility [] facilities,
LogSyslogLevel [] levels,
string [] forwarding_destinations
) {
this.Invoke("create_v2", new object [] {
destinations,
facilities,
levels,
forwarding_destinations});
}
public System.IAsyncResult Begincreate_v2(string [] destinations,LogSyslogFacility [] facilities,LogSyslogLevel [] levels,string [] forwarding_destinations, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create_v2", new object[] {
destinations,
facilities,
levels,
forwarding_destinations}, callback, asyncState);
}
public void Endcreate_v2(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_remote_syslog_destinations
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationRemoteSyslog",
RequestNamespace="urn:iControl:Log/DestinationRemoteSyslog", ResponseNamespace="urn:iControl:Log/DestinationRemoteSyslog")]
public void delete_all_remote_syslog_destinations(
) {
this.Invoke("delete_all_remote_syslog_destinations", new object [0]);
}
public System.IAsyncResult Begindelete_all_remote_syslog_destinations(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_remote_syslog_destinations", new object[0], callback, asyncState);
}
public void Enddelete_all_remote_syslog_destinations(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_remote_syslog_destination
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationRemoteSyslog",
RequestNamespace="urn:iControl:Log/DestinationRemoteSyslog", ResponseNamespace="urn:iControl:Log/DestinationRemoteSyslog")]
public void delete_remote_syslog_destination(
string [] destinations
) {
this.Invoke("delete_remote_syslog_destination", new object [] {
destinations});
}
public System.IAsyncResult Begindelete_remote_syslog_destination(string [] destinations, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_remote_syslog_destination", new object[] {
destinations}, callback, asyncState);
}
public void Enddelete_remote_syslog_destination(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_default_facility
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationRemoteSyslog",
RequestNamespace="urn:iControl:Log/DestinationRemoteSyslog", ResponseNamespace="urn:iControl:Log/DestinationRemoteSyslog")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LogSyslogFacility [] get_default_facility(
string [] destinations
) {
object [] results = this.Invoke("get_default_facility", new object [] {
destinations});
return ((LogSyslogFacility [])(results[0]));
}
public System.IAsyncResult Beginget_default_facility(string [] destinations, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_default_facility", new object[] {
destinations}, callback, asyncState);
}
public LogSyslogFacility [] Endget_default_facility(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LogSyslogFacility [])(results[0]));
}
//-----------------------------------------------------------------------
// get_default_severity
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationRemoteSyslog",
RequestNamespace="urn:iControl:Log/DestinationRemoteSyslog", ResponseNamespace="urn:iControl:Log/DestinationRemoteSyslog")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LogSyslogLevel [] get_default_severity(
string [] destinations
) {
object [] results = this.Invoke("get_default_severity", new object [] {
destinations});
return ((LogSyslogLevel [])(results[0]));
}
public System.IAsyncResult Beginget_default_severity(string [] destinations, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_default_severity", new object[] {
destinations}, callback, asyncState);
}
public LogSyslogLevel [] Endget_default_severity(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LogSyslogLevel [])(results[0]));
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationRemoteSyslog",
RequestNamespace="urn:iControl:Log/DestinationRemoteSyslog", ResponseNamespace="urn:iControl:Log/DestinationRemoteSyslog")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] destinations
) {
object [] results = this.Invoke("get_description", new object [] {
destinations});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] destinations, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
destinations}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_format
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationRemoteSyslog",
RequestNamespace="urn:iControl:Log/DestinationRemoteSyslog", ResponseNamespace="urn:iControl:Log/DestinationRemoteSyslog")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LogSyslogFormat [] get_format(
string [] destinations
) {
object [] results = this.Invoke("get_format", new object [] {
destinations});
return ((LogSyslogFormat [])(results[0]));
}
public System.IAsyncResult Beginget_format(string [] destinations, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_format", new object[] {
destinations}, callback, asyncState);
}
public LogSyslogFormat [] Endget_format(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LogSyslogFormat [])(results[0]));
}
//-----------------------------------------------------------------------
// get_forwarding_destination
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationRemoteSyslog",
RequestNamespace="urn:iControl:Log/DestinationRemoteSyslog", ResponseNamespace="urn:iControl:Log/DestinationRemoteSyslog")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_forwarding_destination(
string [] destinations
) {
object [] results = this.Invoke("get_forwarding_destination", new object [] {
destinations});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_forwarding_destination(string [] destinations, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_forwarding_destination", new object[] {
destinations}, callback, asyncState);
}
public string [] Endget_forwarding_destination(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationRemoteSyslog",
RequestNamespace="urn:iControl:Log/DestinationRemoteSyslog", ResponseNamespace="urn:iControl:Log/DestinationRemoteSyslog")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_remote_high_speed_log_destination
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationRemoteSyslog",
RequestNamespace="urn:iControl:Log/DestinationRemoteSyslog", ResponseNamespace="urn:iControl:Log/DestinationRemoteSyslog")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_remote_high_speed_log_destination(
string [] destinations
) {
object [] results = this.Invoke("get_remote_high_speed_log_destination", new object [] {
destinations});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_remote_high_speed_log_destination(string [] destinations, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_remote_high_speed_log_destination", new object[] {
destinations}, callback, asyncState);
}
public string [] Endget_remote_high_speed_log_destination(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationRemoteSyslog",
RequestNamespace="urn:iControl:Log/DestinationRemoteSyslog", ResponseNamespace="urn:iControl:Log/DestinationRemoteSyslog")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// set_default_facility
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationRemoteSyslog",
RequestNamespace="urn:iControl:Log/DestinationRemoteSyslog", ResponseNamespace="urn:iControl:Log/DestinationRemoteSyslog")]
public void set_default_facility(
string [] destinations,
LogSyslogFacility [] facilities
) {
this.Invoke("set_default_facility", new object [] {
destinations,
facilities});
}
public System.IAsyncResult Beginset_default_facility(string [] destinations,LogSyslogFacility [] facilities, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_default_facility", new object[] {
destinations,
facilities}, callback, asyncState);
}
public void Endset_default_facility(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_default_severity
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationRemoteSyslog",
RequestNamespace="urn:iControl:Log/DestinationRemoteSyslog", ResponseNamespace="urn:iControl:Log/DestinationRemoteSyslog")]
public void set_default_severity(
string [] destinations,
LogSyslogLevel [] levels
) {
this.Invoke("set_default_severity", new object [] {
destinations,
levels});
}
public System.IAsyncResult Beginset_default_severity(string [] destinations,LogSyslogLevel [] levels, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_default_severity", new object[] {
destinations,
levels}, callback, asyncState);
}
public void Endset_default_severity(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationRemoteSyslog",
RequestNamespace="urn:iControl:Log/DestinationRemoteSyslog", ResponseNamespace="urn:iControl:Log/DestinationRemoteSyslog")]
public void set_description(
string [] destinations,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
destinations,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] destinations,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
destinations,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_format
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationRemoteSyslog",
RequestNamespace="urn:iControl:Log/DestinationRemoteSyslog", ResponseNamespace="urn:iControl:Log/DestinationRemoteSyslog")]
public void set_format(
string [] destinations,
LogSyslogFormat [] formats
) {
this.Invoke("set_format", new object [] {
destinations,
formats});
}
public System.IAsyncResult Beginset_format(string [] destinations,LogSyslogFormat [] formats, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_format", new object[] {
destinations,
formats}, callback, asyncState);
}
public void Endset_format(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_forwarding_destination
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationRemoteSyslog",
RequestNamespace="urn:iControl:Log/DestinationRemoteSyslog", ResponseNamespace="urn:iControl:Log/DestinationRemoteSyslog")]
public void set_forwarding_destination(
string [] destinations,
string [] forwarding_destinations
) {
this.Invoke("set_forwarding_destination", new object [] {
destinations,
forwarding_destinations});
}
public System.IAsyncResult Beginset_forwarding_destination(string [] destinations,string [] forwarding_destinations, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_forwarding_destination", new object[] {
destinations,
forwarding_destinations}, callback, asyncState);
}
public void Endset_forwarding_destination(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_remote_high_speed_log_destination
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationRemoteSyslog",
RequestNamespace="urn:iControl:Log/DestinationRemoteSyslog", ResponseNamespace="urn:iControl:Log/DestinationRemoteSyslog")]
public void set_remote_high_speed_log_destination(
string [] destinations,
string [] hsl_destinations
) {
this.Invoke("set_remote_high_speed_log_destination", new object [] {
destinations,
hsl_destinations});
}
public System.IAsyncResult Beginset_remote_high_speed_log_destination(string [] destinations,string [] hsl_destinations, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_remote_high_speed_log_destination", new object[] {
destinations,
hsl_destinations}, callback, asyncState);
}
public void Endset_remote_high_speed_log_destination(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
//=======================================================================
// Structs
//=======================================================================
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Threading;
using System.Threading.Tasks;
using NuGet;
using NuGet.VisualStudio;
using NuGet.VisualStudio.Resources;
namespace NuGetConsole.Host.PowerShell.Implementation
{
internal abstract class PowerShellHost : IHost, IPathExpansion, IDisposable
{
private static readonly object _initScriptsLock = new object();
private readonly string _name;
private readonly IRunspaceManager _runspaceManager;
private readonly IVsPackageSourceProvider _packageSourceProvider;
private readonly ISolutionManager _solutionManager;
private IConsole _activeConsole;
private RunspaceDispatcher _runspace;
private NuGetPSHost _nugetHost;
// indicates whether this host has been initialized.
// null = not initilized, true = initialized successfully, false = initialized unsuccessfully
private bool? _initialized;
// store the current (non-truncated) project names displayed in the project name combobox
private string[] _projectSafeNames;
// store the current command typed so far
private ComplexCommand _complexCommand;
protected PowerShellHost(string name, IRunspaceManager runspaceManager)
{
_runspaceManager = runspaceManager;
// TODO: Take these as ctor arguments
_packageSourceProvider = ServiceLocator.GetInstance<IVsPackageSourceProvider>();
_solutionManager = ServiceLocator.GetInstance<ISolutionManager>();
_name = name;
IsCommandEnabled = true;
}
protected Pipeline ExecutingPipeline { get; set; }
/// <summary>
/// The host is associated with a particular console on a per-command basis.
/// This gets set every time a command is executed on this host.
/// </summary>
protected IConsole ActiveConsole
{
get
{
return _activeConsole;
}
set
{
_activeConsole = value;
if (_nugetHost != null)
{
_nugetHost.ActiveConsole = value;
}
}
}
public bool IsCommandEnabled
{
get;
private set;
}
protected RunspaceDispatcher Runspace
{
get
{
return _runspace;
}
}
private ComplexCommand ComplexCommand
{
get
{
if (_complexCommand == null)
{
_complexCommand = new ComplexCommand((allLines, lastLine) =>
{
Collection<PSParseError> errors;
PSParser.Tokenize(allLines, out errors);
// If there is a parse error token whose END is past input END, consider
// it a multi-line command.
if (errors.Count > 0)
{
if (errors.Any(e => (e.Token.Start + e.Token.Length) >= allLines.Length))
{
return false;
}
}
return true;
});
}
return _complexCommand;
}
}
public string Prompt
{
get
{
return ComplexCommand.IsComplete ? EvaluatePrompt() : ">> ";
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private string EvaluatePrompt()
{
string prompt = "PM>";
try
{
PSObject output = this.Runspace.Invoke("prompt", null, outputResults: false).FirstOrDefault();
if (output != null)
{
string result = output.BaseObject.ToString();
if (!String.IsNullOrEmpty(result))
{
prompt = result;
}
}
}
catch (Exception ex)
{
ExceptionHelper.WriteToActivityLog(ex);
}
return prompt;
}
/// <summary>
/// Doing all necessary initialization works before the console accepts user inputs
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public void Initialize(IConsole console)
{
ActiveConsole = console;
if (_initialized.HasValue)
{
if (_initialized.Value && console.ShowDisclaimerHeader)
{
DisplayDisclaimerAndHelpText();
}
}
else
{
try
{
Tuple<RunspaceDispatcher, NuGetPSHost> result = _runspaceManager.GetRunspace(console, _name);
_runspace = result.Item1;
_nugetHost = result.Item2;
_initialized = true;
if (console.ShowDisclaimerHeader)
{
DisplayDisclaimerAndHelpText();
}
UpdateWorkingDirectory();
ExecuteInitScripts();
// Hook up solution events
_solutionManager.SolutionOpened += (o, e) =>
{
Task.Factory.StartNew(() =>
{
UpdateWorkingDirectory();
ExecuteInitScripts();
},
CancellationToken.None,
TaskCreationOptions.None,
TaskScheduler.Default);
};
_solutionManager.SolutionClosed += (o, e) => UpdateWorkingDirectory();
}
catch (Exception ex)
{
// catch all exception as we don't want it to crash VS
_initialized = false;
IsCommandEnabled = false;
ReportError(ex);
ExceptionHelper.WriteToActivityLog(ex);
}
}
}
private void UpdateWorkingDirectory()
{
if (Runspace.RunspaceAvailability == RunspaceAvailability.Available)
{
// if there is no solution open, we set the active directory to be user profile folder
string targetDir = _solutionManager.IsSolutionOpen ?
_solutionManager.SolutionDirectory :
Environment.GetEnvironmentVariable("USERPROFILE");
Runspace.ChangePSDirectory(targetDir);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We don't want execution of init scripts to crash our console.")]
private void ExecuteInitScripts()
{
// Fix for Bug 1426 Disallow ExecuteInitScripts from being executed concurrently by multiple threads.
lock (_initScriptsLock)
{
if (!_solutionManager.IsSolutionOpen)
{
return;
}
IRepositorySettings repositorySettings = ServiceLocator.GetInstance<IRepositorySettings>();
Debug.Assert(repositorySettings != null);
if (repositorySettings == null)
{
return;
}
try
{
var localRepository = new SharedPackageRepository(repositorySettings.RepositoryPath);
// invoke init.ps1 files in the order of package dependency.
// if A -> B, we invoke B's init.ps1 before A's.
var sorter = new PackageSorter(targetFramework: null);
var sortedPackages = sorter.GetPackagesByDependencyOrder(localRepository);
foreach (var package in sortedPackages)
{
string installPath = localRepository.PathResolver.GetInstallPath(package);
AddPathToEnvironment(Path.Combine(installPath, "tools"));
Runspace.ExecuteScript(installPath, "tools\\init.ps1", package);
}
}
catch (Exception ex)
{
// if execution of Init scripts fails, do not let it crash our console
ReportError(ex);
ExceptionHelper.WriteToActivityLog(ex);
}
}
}
private static void AddPathToEnvironment(string path)
{
if (Directory.Exists(path))
{
string environmentPath = Environment.GetEnvironmentVariable("path", EnvironmentVariableTarget.Process);
environmentPath = environmentPath + ";" + path;
Environment.SetEnvironmentVariable("path", environmentPath, EnvironmentVariableTarget.Process);
}
}
protected abstract bool ExecuteHost(string fullCommand, string command, params object[] inputs);
public bool Execute(IConsole console, string command, params object[] inputs)
{
if (console == null)
{
throw new ArgumentNullException("console");
}
if (command == null)
{
throw new ArgumentNullException("command");
}
NuGetEventTrigger.Instance.TriggerEvent(NuGetEvent.PackageManagerConsoleCommandExecutionBegin);
ActiveConsole = console;
string fullCommand;
if (ComplexCommand.AddLine(command, out fullCommand) && !string.IsNullOrEmpty(fullCommand))
{
return ExecuteHost(fullCommand, command, inputs);
}
return false; // constructing multi-line command
}
protected static void OnExecuteCommandEnd()
{
NuGetEventTrigger.Instance.TriggerEvent(NuGetEvent.PackageManagerConsoleCommandExecutionEnd);
}
public void Abort()
{
if (ExecutingPipeline != null)
{
ExecutingPipeline.StopAsync();
}
ComplexCommand.Clear();
}
protected void SetSyncModeOnHost(bool isSync)
{
if (_nugetHost != null)
{
PSPropertyInfo property = _nugetHost.PrivateData.Properties["IsSyncMode"];
if (property == null)
{
property = new PSNoteProperty("IsSyncMode", isSync);
_nugetHost.PrivateData.Properties.Add(property);
}
else
{
property.Value = isSync;
}
}
}
public void SetDefaultRunspace()
{
Runspace.MakeDefault();
}
private void DisplayDisclaimerAndHelpText()
{
WriteLine(VsResources.Console_DisclaimerText);
WriteLine();
WriteLine(String.Format(CultureInfo.CurrentCulture, Resources.PowerShellHostTitle, _nugetHost.Version.ToString()));
WriteLine();
WriteLine(VsResources.Console_HelpText);
WriteLine();
}
protected void ReportError(ErrorRecord record)
{
WriteErrorLine(Runspace.ExtractErrorFromErrorRecord(record));
}
protected void ReportError(Exception exception)
{
exception = ExceptionUtility.Unwrap(exception);
WriteErrorLine(exception.Message);
}
private void WriteErrorLine(string message)
{
if (ActiveConsole != null)
{
ActiveConsole.Write(message + Environment.NewLine, System.Windows.Media.Colors.Red, null);
}
}
private void WriteLine(string message = "")
{
if (ActiveConsole != null)
{
ActiveConsole.WriteLine(message);
}
}
public string ActivePackageSource
{
get
{
var activePackageSource = _packageSourceProvider.ActivePackageSource;
if (activePackageSource.IsAggregate())
{
// Starting from 2.7, we will not show the All option if there's only one package source.
// Hence, if All is the active package source in that case, we set the sole package source as active,
// and save it to settings
PackageSource[] packageSources = _packageSourceProvider.GetEnabledPackageSourcesWithAggregate().ToArray();
if (packageSources.Length == 1)
{
_packageSourceProvider.ActivePackageSource = packageSources[0];
return packageSources[0].Name;
}
}
return activePackageSource == null ? null : activePackageSource.Name;
}
set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentNullException("value");
}
_packageSourceProvider.ActivePackageSource =
_packageSourceProvider.GetEnabledPackageSourcesWithAggregate().FirstOrDefault(
ps => ps.Name.Equals(value, StringComparison.OrdinalIgnoreCase));
}
}
public string[] GetPackageSources()
{
return _packageSourceProvider.GetEnabledPackageSourcesWithAggregate().Select(ps => ps.Name).ToArray();
}
public string DefaultProject
{
get
{
Debug.Assert(_solutionManager != null);
if (_solutionManager.DefaultProject == null)
{
return null;
}
return _solutionManager.DefaultProject.GetDisplayName(_solutionManager);
}
}
public void SetDefaultProjectIndex(int selectedIndex)
{
Debug.Assert(_solutionManager != null);
if (_projectSafeNames != null && selectedIndex >= 0 && selectedIndex < _projectSafeNames.Length)
{
_solutionManager.DefaultProjectName = _projectSafeNames[selectedIndex];
}
else
{
_solutionManager.DefaultProjectName = null;
}
}
public string[] GetAvailableProjects()
{
Debug.Assert(_solutionManager != null);
var allProjects = _solutionManager.GetProjects();
_projectSafeNames = allProjects.Select(_solutionManager.GetProjectSafeName).ToArray();
var displayNames = allProjects.Select(p => p.GetDisplayName(_solutionManager)).ToArray();
Array.Sort(displayNames, _projectSafeNames, StringComparer.CurrentCultureIgnoreCase);
return displayNames;
}
#region ITabExpansion
public string[] GetExpansions(string line, string lastWord)
{
var query = from s in Runspace.Invoke(
@"$__pc_args=@();$input|%{$__pc_args+=$_};if(Test-Path Function:\TabExpansion2){(TabExpansion2 $__pc_args[0] $__pc_args[0].length).CompletionMatches|%{$_.CompletionText}}else{TabExpansion $__pc_args[0] $__pc_args[1]};Remove-Variable __pc_args -Scope 0;",
new string[] { line, lastWord },
outputResults: false)
select (s == null ? null : s.ToString());
return query.ToArray();
}
#endregion
#region IPathExpansion
public SimpleExpansion GetPathExpansions(string line)
{
PSObject expansion = Runspace.Invoke(
"$input|%{$__pc_args=$_}; _TabExpansionPath $__pc_args; Remove-Variable __pc_args -Scope 0",
new object[] { line },
outputResults: false).FirstOrDefault();
if (expansion != null)
{
int replaceStart = (int)expansion.Properties["ReplaceStart"].Value;
IList<string> paths = ((IEnumerable<object>)expansion.Properties["Paths"].Value).Select(o => o.ToString()).ToList();
return new SimpleExpansion(replaceStart, line.Length - replaceStart, paths);
}
return null;
}
#endregion
#region IDisposable
public void Dispose()
{
if (_runspace != null)
{
_runspace.Dispose();
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace Lucene.Net.Util.Automaton
{
/*
* 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.
*/
/// <summary>
/// Just holds a set of <see cref="T:int[]"/> states, plus a corresponding
/// <see cref="T:int[]"/> count per state. Used by
/// <see cref="BasicOperations.Determinize(Automaton)"/>.
/// <para/>
/// NOTE: This was SortedIntSet in Lucene
/// </summary>
internal sealed class SortedInt32Set : IEquatable<SortedInt32Set>, IEquatable<SortedInt32Set.FrozenInt32Set>
{
internal int[] values;
internal int[] counts;
internal int upto;
private int hashCode;
// If we hold more than this many states, we switch from
// O(N^2) linear ops to O(N log(N)) TreeMap
private const int TREE_MAP_CUTOVER = 30;
private readonly IDictionary<int, int> map = new SortedDictionary<int, int>();
private bool useTreeMap;
internal State state;
public SortedInt32Set(int capacity)
{
values = new int[capacity];
counts = new int[capacity];
}
// Adds this state to the set
public void Incr(int num)
{
if (useTreeMap)
{
int key = num;
int val;
if (!map.TryGetValue(key, out val))
{
map[key] = 1;
}
else
{
map[key] = 1 + val;
}
return;
}
if (upto == values.Length)
{
values = ArrayUtil.Grow(values, 1 + upto);
counts = ArrayUtil.Grow(counts, 1 + upto);
}
for (int i = 0; i < upto; i++)
{
if (values[i] == num)
{
counts[i]++;
return;
}
else if (num < values[i])
{
// insert here
int j = upto - 1;
while (j >= i)
{
values[1 + j] = values[j];
counts[1 + j] = counts[j];
j--;
}
values[i] = num;
counts[i] = 1;
upto++;
return;
}
}
// append
values[upto] = num;
counts[upto] = 1;
upto++;
if (upto == TREE_MAP_CUTOVER)
{
useTreeMap = true;
for (int i = 0; i < upto; i++)
{
map[values[i]] = counts[i];
}
}
}
// Removes this state from the set, if count decrs to 0
public void Decr(int num)
{
if (useTreeMap)
{
int count = map[num];
if (count == 1)
{
map.Remove(num);
}
else
{
map[num] = count - 1;
}
// Fall back to simple arrays once we touch zero again
if (map.Count == 0)
{
useTreeMap = false;
upto = 0;
}
return;
}
for (int i = 0; i < upto; i++)
{
if (values[i] == num)
{
counts[i]--;
if (counts[i] == 0)
{
int limit = upto - 1;
while (i < limit)
{
values[i] = values[i + 1];
counts[i] = counts[i + 1];
i++;
}
upto = limit;
}
return;
}
}
Debug.Assert(false);
}
public void ComputeHash()
{
if (useTreeMap)
{
if (map.Count > values.Length)
{
int size = ArrayUtil.Oversize(map.Count, RamUsageEstimator.NUM_BYTES_INT32);
values = new int[size];
counts = new int[size];
}
hashCode = map.Count;
upto = 0;
foreach (int state in map.Keys)
{
hashCode = 683 * hashCode + state;
values[upto++] = state;
}
}
else
{
hashCode = upto;
for (int i = 0; i < upto; i++)
{
hashCode = 683 * hashCode + values[i];
}
}
}
public FrozenInt32Set ToFrozenInt32Set() // LUCENENET TODO: This didn't exist in the original
{
int[] c = new int[upto];
Array.Copy(values, 0, c, 0, upto);
return new FrozenInt32Set(c, this.hashCode, this.state);
}
public FrozenInt32Set Freeze(State state)
{
int[] c = new int[upto];
Array.Copy(values, 0, c, 0, upto);
return new FrozenInt32Set(c, hashCode, state);
}
public override int GetHashCode()
{
return hashCode;
}
public override bool Equals(object other)
{
if (other == null)
{
return false;
}
if (!(other is FrozenInt32Set))
{
return false;
}
FrozenInt32Set other2 = (FrozenInt32Set)other;
if (hashCode != other2.hashCode)
{
return false;
}
if (other2.values.Length != upto)
{
return false;
}
for (int i = 0; i < upto; i++)
{
if (other2.values[i] != values[i])
{
return false;
}
}
return true;
}
public bool Equals(SortedInt32Set other) // LUCENENET TODO: This didn't exist in the original
{
throw new NotImplementedException("SortedIntSet Equals");
}
public bool Equals(FrozenInt32Set other) // LUCENENET TODO: This didn't exist in the original
{
if (other == null)
{
return false;
}
if (hashCode != other.hashCode)
{
return false;
}
if (other.values.Length != upto)
{
return false;
}
for (int i = 0; i < upto; i++)
{
if (other.values[i] != values[i])
{
return false;
}
}
return true;
}
public override string ToString()
{
StringBuilder sb = (new StringBuilder()).Append('[');
for (int i = 0; i < upto; i++)
{
if (i > 0)
{
sb.Append(' ');
}
sb.Append(values[i]).Append(':').Append(counts[i]);
}
sb.Append(']');
return sb.ToString();
}
/// <summary>
/// NOTE: This was FrozenIntSet in Lucene
/// </summary>
public sealed class FrozenInt32Set : IEquatable<SortedInt32Set>, IEquatable<FrozenInt32Set>
{
internal readonly int[] values;
internal readonly int hashCode;
internal readonly State state;
public FrozenInt32Set(int[] values, int hashCode, State state)
{
this.values = values;
this.hashCode = hashCode;
this.state = state;
}
public FrozenInt32Set(int num, State state)
{
this.values = new int[] { num };
this.state = state;
this.hashCode = 683 + num;
}
public override int GetHashCode()
{
return hashCode;
}
public override bool Equals(object other)
{
if (other == null)
{
return false;
}
if (other is FrozenInt32Set)
{
FrozenInt32Set other2 = (FrozenInt32Set)other;
if (hashCode != other2.hashCode)
{
return false;
}
if (other2.values.Length != values.Length)
{
return false;
}
for (int i = 0; i < values.Length; i++)
{
if (other2.values[i] != values[i])
{
return false;
}
}
return true;
}
else if (other is SortedInt32Set)
{
SortedInt32Set other3 = (SortedInt32Set)other;
if (hashCode != other3.hashCode)
{
return false;
}
if (other3.values.Length != values.Length)
{
return false;
}
for (int i = 0; i < values.Length; i++)
{
if (other3.values[i] != values[i])
{
return false;
}
}
return true;
}
return false;
}
public bool Equals(SortedInt32Set other) // LUCENENET TODO: This didn't exist in the original
{
if (other == null)
{
return false;
}
if (hashCode != other.hashCode)
{
return false;
}
if (other.values.Length != values.Length)
{
return false;
}
for (int i = 0; i < values.Length; i++)
{
if (other.values[i] != values[i])
{
return false;
}
}
return true;
}
public bool Equals(FrozenInt32Set other) // LUCENENET TODO: This didn't exist in the original
{
if (other == null)
{
return false;
}
if (hashCode != other.hashCode)
{
return false;
}
if (other.values.Length != values.Length)
{
return false;
}
for (int i = 0; i < values.Length; i++)
{
if (other.values[i] != values[i])
{
return false;
}
}
return true;
}
public override string ToString()
{
StringBuilder sb = (new StringBuilder()).Append('[');
for (int i = 0; i < values.Length; i++)
{
if (i > 0)
{
sb.Append(' ');
}
sb.Append(values[i]);
}
sb.Append(']');
return sb.ToString();
}
}
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace Branding.DisplayTemplatesWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
using System;
namespace NPSharp.Steam
{
public class CSteamID
{
private readonly InteropHelp.BitVector64 steamid;
public CSteamID()
: this(0)
{
}
internal CSteamID(UInt32 unAccountID, EUniverse eUniverse, EAccountType eAccountType)
: this()
{
Set(unAccountID, eUniverse, eAccountType);
}
internal CSteamID(UInt32 unAccountID, UInt32 unInstance, EUniverse eUniverse, EAccountType eAccountType)
: this()
{
InstancedSet(unAccountID, unInstance, eUniverse, eAccountType);
}
internal CSteamID(UInt64 id)
{
steamid = new InteropHelp.BitVector64(id);
}
internal CSteamID(SteamID_t sid)
: this(
sid.low32Bits, sid.high32Bits & 0xFFFFF, (EUniverse) (sid.high32Bits >> 24),
(EAccountType) ((sid.high32Bits >> 20) & 0xF))
{
}
public UInt32 AccountID
{
get { return (UInt32) steamid[0, 0xFFFFFFFF]; }
set { steamid[0, 0xFFFFFFFF] = value; }
}
public UInt32 AccountInstance
{
get { return (UInt32) steamid[32, 0xFFFFF]; }
set { steamid[32, 0xFFFFF] = value; }
}
public EAccountType AccountType
{
get { return (EAccountType) steamid[52, 0xF]; }
set { steamid[52, 0xF] = (UInt64) value; }
}
public EUniverse AccountUniverse
{
get { return (EUniverse) steamid[56, 0xFF]; }
set { steamid[56, 0xFF] = (UInt64) value; }
}
public static implicit operator UInt64(CSteamID sid)
{
return sid.steamid.Data;
}
public static implicit operator CSteamID(UInt64 id)
{
return new CSteamID(id);
}
public void Set(UInt32 unAccountID, EUniverse eUniverse, EAccountType eAccountType)
{
AccountID = unAccountID;
AccountUniverse = eUniverse;
AccountType = eAccountType;
if (eAccountType == EAccountType.Clan)
{
AccountInstance = 0;
}
else
{
AccountInstance = 1;
}
}
public void InstancedSet(UInt32 unAccountID, UInt32 unInstance, EUniverse eUniverse, EAccountType eAccountType)
{
AccountID = unAccountID;
AccountUniverse = eUniverse;
AccountType = eAccountType;
AccountInstance = unInstance;
}
public void SetFromUint64(UInt64 ulSteamID)
{
steamid.Data = ulSteamID;
}
public UInt64 ConvertToUint64()
{
return steamid.Data;
}
public bool BBlankAnonAccount()
{
return AccountID == 0 && BAnonAccount() && AccountInstance == 0;
}
public bool BGameServerAccount()
{
return AccountType == EAccountType.GameServer ||
AccountType == EAccountType.AnonGameServer;
}
public bool BContentServerAccount()
{
return AccountType == EAccountType.ContentServer;
}
public bool BClanAccount()
{
return AccountType == EAccountType.Clan;
}
public bool BChatAccount()
{
return AccountType == EAccountType.Chat;
}
public bool IsLobby()
{
return (AccountType == EAccountType.Chat) && ((AccountInstance & (0x000FFFFF + 1) >> 2) != 0);
}
public bool BAnonAccount()
{
return AccountType == EAccountType.AnonUser ||
AccountType == EAccountType.AnonGameServer;
}
public bool BAnonUserAccount()
{
return AccountType == EAccountType.AnonUser;
}
public bool IsValid()
{
if (AccountType <= EAccountType.Invalid || AccountType >= EAccountType.Max)
return false;
if (AccountUniverse <= EUniverse.Invalid || AccountUniverse >= EUniverse.Max)
return false;
if (AccountType == EAccountType.Individual)
{
if (AccountID == 0 || AccountInstance != 1)
return false;
}
if (AccountType == EAccountType.Clan)
{
if (AccountID == 0 || AccountInstance != 0)
return false;
}
return true;
}
public string Render()
{
switch (AccountType)
{
case EAccountType.Invalid:
case EAccountType.Individual:
return AccountUniverse <= EUniverse.Public
? String.Format("STEAM_0:{0}:{1}", AccountID & 1, AccountID >> 1)
: String.Format("STEAM_{2}:{0}:{1}", AccountID & 1, AccountID >> 1, (int) AccountUniverse);
default:
return Convert.ToString(this);
}
}
public override string ToString()
{
return Render();
}
public override bool Equals(Object obj)
{
if (obj == null)
return false;
var sid = obj as CSteamID;
if (sid == null)
return false;
return steamid.Data == sid.steamid.Data;
}
public bool Equals(CSteamID sid)
{
if (sid == null)
return false;
return steamid.Data == sid.steamid.Data;
}
public static bool operator ==(CSteamID a, CSteamID b)
{
if (ReferenceEquals(a, b))
return true;
if (Equals(a, null) || Equals(b, null))
return false;
return a.steamid.Data == b.steamid.Data;
}
public static bool operator !=(CSteamID a, CSteamID b)
{
return !(a == b);
}
public override int GetHashCode()
{
return steamid.Data.GetHashCode();
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Targets
{
using System;
using System.Collections.Generic;
using System.Threading;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Layouts;
/// <summary>
/// Represents logging target.
/// </summary>
[NLogConfigurationItem]
public abstract class Target : ISupportsInitialize, IDisposable
{
private object lockObject = new object();
private List<Layout> allLayouts;
private bool scannedForLayouts;
private Exception initializeException;
/// <summary>
/// Gets or sets the name of the target.
/// </summary>
/// <docgen category='General Options' order='10' />
public string Name { get; set; }
/// <summary>
/// Gets the object which can be used to synchronize asynchronous operations that must rely on the .
/// </summary>
protected object SyncRoot
{
get { return this.lockObject; }
}
/// <summary>
/// Gets the logging configuration this target is part of.
/// </summary>
protected LoggingConfiguration LoggingConfiguration { get; private set; }
/// <summary>
/// Gets a value indicating whether the target has been initialized.
/// </summary>
protected bool IsInitialized { get; private set; }
/// <summary>
/// Get all used layouts in this target.
/// </summary>
/// <returns></returns>
internal List<Layout> GetAllLayouts()
{
if (!scannedForLayouts)
{
FindAllLayouts();
}
return allLayouts;
}
/// <summary>
/// Initializes this instance.
/// </summary>
/// <param name="configuration">The configuration.</param>
void ISupportsInitialize.Initialize(LoggingConfiguration configuration)
{
this.Initialize(configuration);
}
/// <summary>
/// Closes this instance.
/// </summary>
void ISupportsInitialize.Close()
{
this.Close();
}
/// <summary>
/// Closes the target.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
public void Flush(AsyncContinuation asyncContinuation)
{
if (asyncContinuation == null)
{
throw new ArgumentNullException("asyncContinuation");
}
lock (this.SyncRoot)
{
if (!this.IsInitialized)
{
asyncContinuation(null);
return;
}
asyncContinuation = AsyncHelpers.PreventMultipleCalls(asyncContinuation);
try
{
this.FlushAsync(asyncContinuation);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
asyncContinuation(exception);
}
}
}
/// <summary>
/// Calls the <see cref="Layout.Precalculate"/> on each volatile layout
/// used by this target.
/// </summary>
/// <param name="logEvent">
/// The log event.
/// </param>
public void PrecalculateVolatileLayouts(LogEventInfo logEvent)
{
lock (this.SyncRoot)
{
if (this.IsInitialized)
{
if (this.allLayouts != null)
{
foreach (Layout l in this.allLayouts)
{
l.Precalculate(logEvent);
}
}
}
}
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
var targetAttribute = (TargetAttribute)Attribute.GetCustomAttribute(this.GetType(), typeof(TargetAttribute));
if (targetAttribute != null)
{
return targetAttribute.Name + " Target[" + (this.Name ?? "(unnamed)") + "]";
}
return this.GetType().Name;
}
/// <summary>
/// Writes the log to the target.
/// </summary>
/// <param name="logEvent">Log event to write.</param>
public void WriteAsyncLogEvent(AsyncLogEventInfo logEvent)
{
lock (this.SyncRoot)
{
if (!this.IsInitialized)
{
logEvent.Continuation(null);
return;
}
if (this.initializeException != null)
{
logEvent.Continuation(this.CreateInitException());
return;
}
var wrappedContinuation = AsyncHelpers.PreventMultipleCalls(logEvent.Continuation);
try
{
this.Write(logEvent.LogEvent.WithContinuation(wrappedContinuation));
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
wrappedContinuation(exception);
}
}
}
/// <summary>
/// Writes the array of log events.
/// </summary>
/// <param name="logEvents">The log events.</param>
public void WriteAsyncLogEvents(params AsyncLogEventInfo[] logEvents)
{
if (logEvents == null || logEvents.Length == 0)
{
return;
}
lock (this.SyncRoot)
{
if (!this.IsInitialized)
{
foreach (var ev in logEvents)
{
ev.Continuation(null);
}
return;
}
if (this.initializeException != null)
{
foreach (var ev in logEvents)
{
ev.Continuation(this.CreateInitException());
}
return;
}
var wrappedEvents = new AsyncLogEventInfo[logEvents.Length];
for (int i = 0; i < logEvents.Length; ++i)
{
wrappedEvents[i] = logEvents[i].LogEvent.WithContinuation(AsyncHelpers.PreventMultipleCalls(logEvents[i].Continuation));
}
try
{
this.Write(wrappedEvents);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
// in case of synchronous failure, assume that nothing is running asynchronously
foreach (var ev in wrappedEvents)
{
ev.Continuation(exception);
}
}
}
}
/// <summary>
/// Initializes this instance.
/// </summary>
/// <param name="configuration">The configuration.</param>
internal void Initialize(LoggingConfiguration configuration)
{
lock (this.SyncRoot)
{
this.LoggingConfiguration = configuration;
if (!this.IsInitialized)
{
PropertyHelper.CheckRequiredParameters(this);
this.IsInitialized = true;
try
{
this.InitializeTarget();
this.initializeException = null;
if (this.allLayouts == null)
{
throw new NLogRuntimeException("{0}.allLayouts is null. Call base.InitializeTarget() in {0}", this.GetType());
}
}
catch (Exception exception)
{
InternalLogger.Error(exception, "Error initializing target '{0}'.", this);
this.initializeException = exception;
if (exception.MustBeRethrown())
{
throw;
}
}
}
}
}
/// <summary>
/// Closes this instance.
/// </summary>
internal void Close()
{
lock (this.SyncRoot)
{
this.LoggingConfiguration = null;
if (this.IsInitialized)
{
this.IsInitialized = false;
try
{
if (this.initializeException == null)
{
// if Init succeeded, call Close()
this.CloseTarget();
}
}
catch (Exception exception)
{
InternalLogger.Error(exception, "Error closing target '{0}'.", this);
if (exception.MustBeRethrown())
{
throw;
}
}
}
}
}
internal void WriteAsyncLogEvents(AsyncLogEventInfo[] logEventInfos, AsyncContinuation continuation)
{
if (logEventInfos.Length == 0)
{
continuation(null);
}
else
{
var wrappedLogEventInfos = new AsyncLogEventInfo[logEventInfos.Length];
int remaining = logEventInfos.Length;
for (int i = 0; i < logEventInfos.Length; ++i)
{
AsyncContinuation originalContinuation = logEventInfos[i].Continuation;
AsyncContinuation wrappedContinuation = ex =>
{
originalContinuation(ex);
if (0 == Interlocked.Decrement(ref remaining))
{
continuation(null);
}
};
wrappedLogEventInfos[i] = logEventInfos[i].LogEvent.WithContinuation(wrappedContinuation);
}
this.WriteAsyncLogEvents(wrappedLogEventInfos);
}
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing">True to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this.CloseTarget();
}
}
/// <summary>
/// Initializes the target. Can be used by inheriting classes
/// to initialize logging.
/// </summary>
protected virtual void InitializeTarget()
{
//rescan as amount layouts can be changed.
FindAllLayouts();
}
private void FindAllLayouts()
{
this.allLayouts = new List<Layout>(ObjectGraphScanner.FindReachableObjects<Layout>(this));
InternalLogger.Trace("{0} has {1} layouts", this, this.allLayouts.Count);
this.scannedForLayouts = true;
}
/// <summary>
/// Closes the target and releases any unmanaged resources.
/// </summary>
protected virtual void CloseTarget()
{
}
/// <summary>
/// Flush any pending log messages asynchronously (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
protected virtual void FlushAsync(AsyncContinuation asyncContinuation)
{
asyncContinuation(null);
}
/// <summary>
/// Writes logging event to the log target.
/// classes.
/// </summary>
/// <param name="logEvent">
/// Logging event to be written out.
/// </param>
protected virtual void Write(LogEventInfo logEvent)
{
// do nothing
}
/// <summary>
/// Writes log event to the log target. Must be overridden in inheriting
/// classes.
/// </summary>
/// <param name="logEvent">Log event to be written out.</param>
protected virtual void Write(AsyncLogEventInfo logEvent)
{
try
{
this.MergeEventProperties(logEvent.LogEvent);
this.Write(logEvent.LogEvent);
logEvent.Continuation(null);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
logEvent.Continuation(exception);
}
}
/// <summary>
/// Writes an array of logging events to the log target. By default it iterates on all
/// events and passes them to "Write" method. Inheriting classes can use this method to
/// optimize batch writes.
/// </summary>
/// <param name="logEvents">Logging events to be written out.</param>
protected virtual void Write(AsyncLogEventInfo[] logEvents)
{
for (int i = 0; i < logEvents.Length; ++i)
{
this.Write(logEvents[i]);
}
}
private Exception CreateInitException()
{
return new NLogRuntimeException("Target " + this + " failed to initialize.", this.initializeException);
}
/// <summary>
/// Merges (copies) the event context properties from any event info object stored in
/// parameters of the given event info object.
/// </summary>
/// <param name="logEvent">The event info object to perform the merge to.</param>
protected void MergeEventProperties(LogEventInfo logEvent)
{
if (logEvent.Parameters == null)
{
return;
}
foreach (var item in logEvent.Parameters)
{
var logEventParameter = item as LogEventInfo;
if (logEventParameter != null)
{
foreach (var key in logEventParameter.Properties.Keys)
{
logEvent.Properties.Add(key, logEventParameter.Properties[key]);
}
logEventParameter.Properties.Clear();
}
}
}
}
}
| |
#region Apache Notice
/*****************************************************************************
* $Revision: 476843 $
* $LastChangedDate: 2006-11-19 17:07:45 +0100 (dim., 19 nov. 2006) $
* $LastChangedBy: gbayon $
*
* iBATIS.NET Data Mapper
* Copyright (C) 2006/2005 - The Apache Software Foundation
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
********************************************************************************/
#endregion
using System.Collections;
using System.Data;
using System.Text;
using IBatisNet.DataMapper.Configuration.ParameterMapping;
using IBatisNet.DataMapper.Configuration.Sql.Dynamic.Elements;
using IBatisNet.DataMapper.Configuration.Sql.Dynamic.Handlers;
using IBatisNet.DataMapper.Configuration.Sql.SimpleDynamic;
using IBatisNet.DataMapper.Configuration.Statements;
using IBatisNet.DataMapper.DataExchange;
using IBatisNet.DataMapper.MappedStatements;
using IBatisNet.DataMapper.Scope;
namespace IBatisNet.DataMapper.Configuration.Sql.Dynamic
{
/// <summary>
/// DynamicSql represent the root element of a dynamic sql statement
/// </summary>
/// <example>
/// <dynamic prepend="where">...</dynamic>
/// </example>
internal sealed class DynamicSql : ISql, IDynamicParent
{
#region Fields
private IList _children = new ArrayList();
private IStatement _statement = null;
private bool _usePositionalParameters = false;
private InlineParameterMapParser _paramParser = null;
private DataExchangeFactory _dataExchangeFactory = null;
#endregion
#region Constructor (s) / Destructor
/// <summary>
/// Initializes a new instance of the <see cref="DynamicSql"/> class.
/// </summary>
/// <param name="configScope">The config scope.</param>
/// <param name="statement">The statement.</param>
internal DynamicSql(ConfigurationScope configScope, IStatement statement)
{
_statement = statement;
_usePositionalParameters = configScope.DataSource.DbProvider.UsePositionalParameters;
_dataExchangeFactory = configScope.DataExchangeFactory;
}
#endregion
#region Methods
#region ISql IDynamicParent
/// <summary>
///
/// </summary>
/// <param name="child"></param>
public void AddChild(ISqlChild child)
{
_children.Add(child);
}
#endregion
#region ISql Members
/// <summary>
/// Builds a new <see cref="RequestScope"/> and the <see cref="IDbCommand"/> text to execute.
/// </summary>
/// <param name="parameterObject">The parameter object (used in DynamicSql)</param>
/// <param name="session">The current session</param>
/// <param name="mappedStatement">The <see cref="IMappedStatement"/>.</param>
/// <returns>A new <see cref="RequestScope"/>.</returns>
public RequestScope GetRequestScope(IMappedStatement mappedStatement,
object parameterObject, ISqlMapSession session)
{
RequestScope request = new RequestScope(_dataExchangeFactory, session, _statement);
_paramParser = new InlineParameterMapParser();
string sqlStatement = Process(request, parameterObject);
request.PreparedStatement = BuildPreparedStatement(session, request, sqlStatement);
request.MappedStatement = mappedStatement;
return request;
}
#endregion
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="parameterObject"></param>
/// <returns></returns>
private string Process(RequestScope request, object parameterObject)
{
SqlTagContext ctx = new SqlTagContext();
IList localChildren = _children;
ProcessBodyChildren(request, ctx, parameterObject, localChildren);
// Builds a 'dynamic' ParameterMap
ParameterMap map = new ParameterMap(request.DataExchangeFactory);
map.Id = _statement.Id + "-InlineParameterMap";
map.Initialize(_usePositionalParameters, request);
map.Class = _statement.ParameterClass;
// Adds 'dynamic' ParameterProperty
IList parameters = ctx.GetParameterMappings();
int count = parameters.Count;
for (int i = 0; i < count; i++)
{
map.AddParameterProperty((ParameterProperty)parameters[i]);
}
request.ParameterMap = map;
string dynSql = ctx.BodyText;
// Processes $substitutions$ after DynamicSql
if (SimpleDynamicSql.IsSimpleDynamicSql(dynSql))
{
dynSql = new SimpleDynamicSql(request, dynSql, _statement).GetSql(parameterObject);
}
return dynSql;
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="ctx"></param>
/// <param name="parameterObject"></param>
/// <param name="localChildren"></param>
private void ProcessBodyChildren(RequestScope request, SqlTagContext ctx,
object parameterObject, IList localChildren)
{
StringBuilder buffer = ctx.GetWriter();
ProcessBodyChildren(request, ctx, parameterObject, localChildren.GetEnumerator(), buffer);
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="ctx"></param>
/// <param name="parameterObject"></param>
/// <param name="localChildren"></param>
/// <param name="buffer"></param>
private void ProcessBodyChildren(RequestScope request, SqlTagContext ctx,
object parameterObject, IEnumerator localChildren, StringBuilder buffer)
{
while (localChildren.MoveNext())
{
ISqlChild child = (ISqlChild)localChildren.Current;
if (child is SqlText)
{
SqlText sqlText = (SqlText)child;
string sqlStatement = sqlText.Text;
if (sqlText.IsWhiteSpace)
{
buffer.Append(sqlStatement);
}
else
{
// if (SimpleDynamicSql.IsSimpleDynamicSql(sqlStatement))
// {
// sqlStatement = new SimpleDynamicSql(sqlStatement, _statement).GetSql(parameterObject);
// SqlText newSqlText = _paramParser.ParseInlineParameterMap( null, sqlStatement );
// sqlStatement = newSqlText.Text;
// ParameterProperty[] mappings = newSqlText.Parameters;
// if (mappings != null)
// {
// for (int i = 0; i < mappings.Length; i++)
// {
// ctx.AddParameterMapping(mappings[i]);
// }
// }
// }
// BODY OUT
buffer.Append(" ");
buffer.Append(sqlStatement);
ParameterProperty[] parameters = sqlText.Parameters;
if (parameters != null)
{
int length = parameters.Length;
for (int i = 0; i < length; i++)
{
ctx.AddParameterMapping(parameters[i]);
}
}
}
}
else if (child is SqlTag)
{
SqlTag tag = (SqlTag)child;
ISqlTagHandler handler = tag.Handler;
int response = BaseTagHandler.INCLUDE_BODY;
do
{
StringBuilder body = new StringBuilder();
response = handler.DoStartFragment(ctx, tag, parameterObject);
if (response != BaseTagHandler.SKIP_BODY)
{
if (ctx.IsOverridePrepend
&& ctx.FirstNonDynamicTagWithPrepend == null
&& tag.IsPrependAvailable
&& !(tag.Handler is DynamicTagHandler))
{
ctx.FirstNonDynamicTagWithPrepend = tag;
}
ProcessBodyChildren(request, ctx, parameterObject, tag.GetChildrenEnumerator(), body);
response = handler.DoEndFragment(ctx, tag, parameterObject, body);
handler.DoPrepend(ctx, tag, parameterObject, body);
if (response != BaseTagHandler.SKIP_BODY)
{
if (body.Length > 0)
{
// BODY OUT
if (handler.IsPostParseRequired)
{
SqlText sqlText = _paramParser.ParseInlineParameterMap(request, null, body.ToString());
buffer.Append(sqlText.Text);
ParameterProperty[] mappings = sqlText.Parameters;
if (mappings != null)
{
int length = mappings.Length;
for (int i = 0; i < length; i++)
{
ctx.AddParameterMapping(mappings[i]);
}
}
}
else
{
buffer.Append(" ");
buffer.Append(body.ToString());
}
if (tag.IsPrependAvailable && tag == ctx.FirstNonDynamicTagWithPrepend)
{
ctx.IsOverridePrepend = false;
}
}
}
}
}
while (response == BaseTagHandler.REPEAT_BODY);
}
}
}
/// <summary>
///
/// </summary>
/// <param name="session"></param>
/// <param name="request"></param>
/// <param name="sqlStatement"></param>
/// <returns></returns>
private PreparedStatement BuildPreparedStatement(ISqlMapSession session, RequestScope request, string sqlStatement)
{
PreparedStatementFactory factory = new PreparedStatementFactory(session, request, _statement, sqlStatement);
return factory.Prepare();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Content;
using IRTaktiks.Components.Playables;
using IRTaktiks.Components.Managers;
using IRTaktiks.Input;
using IRTaktiks.Input.EventArgs;
namespace IRTaktiks.Components.Menu
{
/// <summary>
/// Representation of the aim of attack of the unit.
/// </summary>
public class AimMenu
{
#region Properties
/// <summary>
/// The unit who will be the owner of the aim.
/// </summary>
private Unit UnitField;
/// <summary>
/// The unit who will be the owner of the aim.
/// </summary>
public Unit Unit
{
get { return UnitField; }
}
/// <summary>
/// Indicates if the aim is enabled.
/// </summary>
private bool EnabledField;
/// <summary>
/// Indicates if the aim is enabled.
/// </summary>
public bool Enabled
{
get { return EnabledField; }
}
/// <summary>
/// The position of the aim.
/// </summary>
private Vector2 PositionField;
/// <summary>
/// The position of the aim.
/// </summary>
public Vector2 Position
{
get { return PositionField; }
}
/// <summary>
/// Indicates if the aim is being moved.
/// </summary>
private bool AimingField;
/// <summary>
/// Indicates if the aim is being moved.
/// </summary>
public bool Aiming
{
get { return AimingField; }
}
/// <summary>
/// The limit distance that the aim can be away from the unit.
/// </summary>
private float LimitField;
/// <summary>
/// The limit distance that the aim can be away from the unit.
/// </summary>
public float Limit
{
get { return LimitField; }
}
/// <summary>
/// The unit targeted by the aim. Null when the unit is over anything.
/// </summary>
private Unit Target;
/// <summary>
/// The texture of the aim when its over nothing.
/// </summary>
private Texture2D AimNothing;
/// <summary>
/// The texture of the aim when its over some ally.
/// </summary>
private Texture2D AimAlly;
/// <summary>
/// The texture of the aim when its over some enemy.
/// </summary>
private Texture2D AimEnemy;
/// <summary>
/// The texture that will be used to draw the aim.
/// </summary>
private Texture2D TextureToDraw;
#endregion
#region Event
/// <summary>
/// The method template who will used to handle the Aimed event.
/// </summary>
/// <param name="target">The unit targeted by the aim. Null when the aim is over nothing.</param>
public delegate void AimedEventHandler(Unit target);
/// <summary>
/// The Aimed event.
/// </summary>
public event AimedEventHandler Aimed;
#endregion
#region Constructor
/// <summary>
/// Constructor of class.
/// </summary>
/// <param name="unit">The unit who will be the owner of the aim.</param>
public AimMenu(Unit unit)
{
this.UnitField = unit;
this.PositionField = new Vector2(unit.Position.X + unit.Texture.Width / 2, unit.Position.Y + unit.Texture.Height / 8);
this.AimingField = false;
this.EnabledField = false;
this.AimAlly = TextureManager.Instance.Sprites.Menu.AimAlly;
this.AimEnemy = TextureManager.Instance.Sprites.Menu.AimEnemy;
this.AimNothing = TextureManager.Instance.Sprites.Menu.AimNothing;
this.TextureToDraw = TextureManager.Instance.Sprites.Menu.AimAlly;
}
#endregion
#region Methods
/// <summary>
/// Activate the input handling.
/// </summary>
/// <param name="limit">The limit distance that the aim can be away from the unit.</param>
public void Activate(float limit)
{
this.EnabledField = true;
this.LimitField = limit;
InputManager.Instance.CursorDown += new EventHandler<CursorDownArgs>(CursorDown_Handler);
InputManager.Instance.CursorUpdate += new EventHandler<CursorUpdateArgs>(CursorUpdate_Handler);
InputManager.Instance.CursorUp += new EventHandler<CursorUpArgs>(CursorUp_Handler);
}
/// <summary>
/// Deactivate the input handling.
/// </summary>
public void Deactivate()
{
this.EnabledField = false;
this.LimitField = 0;
InputManager.Instance.CursorDown -= new EventHandler<CursorDownArgs>(CursorDown_Handler);
InputManager.Instance.CursorUpdate -= new EventHandler<CursorUpdateArgs>(CursorUpdate_Handler);
InputManager.Instance.CursorUp -= new EventHandler<CursorUpArgs>(CursorUp_Handler);
}
/// <summary>
/// Reset the logic properties of the aim.
/// </summary>
public void Reset()
{
this.PositionField = new Vector2(this.Unit.Position.X + this.Unit.Texture.Width / 2, this.Unit.Position.Y + this.Unit.Texture.Height / 8);
}
/// <summary>
/// Draws the aim.
/// </summary>
/// <param name="spriteBatchManager">SpriteBatchManager used to draw.</param>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
public void Draw(SpriteManager spriteBatchManager, GameTime gameTime)
{
// If the aim is enabled.
if (this.Enabled)
{
// Updates the aim ten times per second.
if (gameTime.TotalGameTime.Milliseconds % 100 == 0)
{
// Get all the units of the game.
List<Unit> units = new List<Unit>();
units.AddRange(this.Unit.Player.Units);
units.AddRange(this.Unit.Player.Enemy.Units);
bool isOverSomething = false;
// Check if the aim is over some unit.
for (int index = 0; index < units.Count; index++)
{
// Get the center position of the unit.
Vector2 unitPosition = new Vector2(units[index].Position.X + units[index].Texture.Width / 2, units[index].Position.Y + units[index].Texture.Height / 8);
// Calculates the distance between the unit and the aim.
if (Vector2.Distance(this.Position, unitPosition) < 40)
{
isOverSomething = true;
// Determine if the player owner of the unit is the enemy;
if (units[index].Player != this.Unit.Player)
{
this.TextureToDraw = this.AimEnemy;
}
else
{
this.TextureToDraw = this.AimAlly;
}
this.Target = units[index];
}
}
if (!isOverSomething)
{
this.TextureToDraw = this.AimNothing;
this.Target = null;
}
}
Vector2 position = new Vector2(this.Position.X - this.AimAlly.Width / 2, this.Position.Y - this.AimAlly.Height / 2);
spriteBatchManager.Draw(this.TextureToDraw, position, Color.White, 60);
}
}
#endregion
#region Input Handling
/// <summary>
/// Handles the CursorDown event.
/// </summary>
/// <param name="sender">Always null.</param>
/// <param name="e">Data of event.</param>
private void CursorDown_Handler(object sender, CursorDownArgs e)
{
// Handles the event only if the aim is enabled.
if (this.Enabled)
{
// If the touch was in the area of the aim
if ((e.Position.X < (this.Position.X + this.AimAlly.Width / 2) && e.Position.X > (this.Position.X - this.AimAlly.Width / 2)) &&
(e.Position.Y < (this.Position.Y + this.AimAlly.Height / 2) && e.Position.Y > (this.Position.Y - this.AimAlly.Height / 2)))
{
this.AimingField = true;
}
}
}
/// <summary>
/// Handles the CursorUpdate event.
/// </summary>
/// <param name="sender">Always null.</param>
/// <param name="e">Data of event.</param>
private void CursorUpdate_Handler(object sender, CursorUpdateArgs e)
{
// If the aim is enabled and aiming.
if (this.Enabled && this.Aiming)
{
// If the aim is inside the area
Vector2 areaPosition = new Vector2(this.Unit.Position.X + this.Unit.Texture.Width / 2, this.Unit.Position.Y + this.Unit.Texture.Height / 4);
if (Vector2.Distance(e.Position, areaPosition) < (this.Limit / 2) - (this.AimAlly.Width / 2))
{
// Updates the position of the aim.
this.PositionField = e.Position;
}
}
}
/// <summary>
/// Handles the CursorUp event.
/// </summary>
/// <param name="sender">Always null.</param>
/// <param name="e">Data of event.</param>
private void CursorUp_Handler(object sender, CursorUpArgs e)
{
// If the aim is enabled and aiming.
if (this.Enabled && this.Aiming)
{
// End the aiming and set the aimed true.
this.AimingField = false;
// Dispatch the Aimed event.
if (this.Aimed != null)
{
this.Aimed(this.Target);
}
// Unregister the event handler.
this.Deactivate();
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Terraria.ModLoader.IO;
namespace Terraria.ModLoader
{
//todo: further documentation
internal class BuildProperties
{
internal struct ModReference
{
public string mod;
public Version target;
public ModReference(string mod, Version target)
{
this.mod = mod;
this.target = target;
}
public override string ToString() => target == null ? mod : mod + '@' + target;
public static ModReference Parse(string spec)
{
var split = spec.Split('@');
if (split.Length == 1)
return new ModReference(split[0], null);
if (split.Length > 2)
throw new Exception("Invalid mod reference: " + spec);
try
{
return new ModReference(split[0], new Version(split[1]));
}
catch
{
throw new Exception("Invalid mod reference: " + spec);
}
}
}
internal string[] dllReferences = new string[0];
internal ModReference[] modReferences = new ModReference[0];
internal ModReference[] weakReferences = new ModReference[0];
//this mod will load after any mods in this list
//sortAfter includes (mod|weak)References that are not in sortBefore
internal string[] sortAfter = new string[0];
//this mod will load before any mods in this list
internal string[] sortBefore = new string[0];
internal string[] buildIgnores = new string[0];
internal string author = "";
internal Version version = new Version(1, 0);
internal string displayName = "";
internal bool noCompile = false;
internal bool hideCode = false;
internal bool hideResources = false;
internal bool includeSource = false;
internal bool includePDB = false;
internal bool editAndContinue = false;
internal int languageVersion = 4;
internal string homepage = "";
internal string description = "";
internal ModSide side;
public IEnumerable<ModReference> Refs(bool build) =>
build ? modReferences.Concat(weakReferences) : modReferences;
public IEnumerable<string> RefNames(bool build) => Refs(build).Select(dep => dep.mod);
private static IEnumerable<string> ReadList(string value)
=> value.Split(',').Select(s => s.Trim()).Where(s => s.Length > 0);
private static IEnumerable<string> ReadList(BinaryReader reader)
{
var list = new List<string>();
for (string item = reader.ReadString(); item.Length > 0; item = reader.ReadString())
list.Add(item);
return list;
}
private static void WriteList<T>(IEnumerable<T> list, BinaryWriter writer)
{
foreach (var item in list)
writer.Write(item.ToString());
writer.Write("");
}
internal static BuildProperties ReadBuildFile(string modDir)
{
string propertiesFile = modDir + Path.DirectorySeparatorChar + "build.txt";
string descriptionfile = modDir + Path.DirectorySeparatorChar + "description.txt";
BuildProperties properties = new BuildProperties();
if (!File.Exists(propertiesFile))
{
return properties;
}
if (File.Exists(descriptionfile))
{
properties.description = File.ReadAllText(descriptionfile);
}
string[] lines = File.ReadAllLines(propertiesFile);
foreach (string line in lines)
{
if (line.Length == 0)
{
continue;
}
int split = line.IndexOf('=');
string property = line.Substring(0, split).Trim();
string value = line.Substring(split + 1).Trim();
if (value.Length == 0)
{
continue;
}
switch (property)
{
case "dllReferences":
properties.dllReferences = ReadList(value).ToArray();
break;
case "modReferences":
properties.modReferences = ReadList(value).Select(ModReference.Parse).ToArray();
break;
case "weakReferences":
properties.weakReferences = ReadList(value).Select(ModReference.Parse).ToArray();
break;
case "sortBefore":
properties.sortAfter = ReadList(value).ToArray();
break;
case "sortAfter":
properties.sortBefore = ReadList(value).ToArray();
break;
case "author":
properties.author = value;
break;
case "version":
properties.version = new Version(value);
break;
case "displayName":
properties.displayName = value;
break;
case "homepage":
properties.homepage = value;
break;
case "noCompile":
properties.noCompile = value.ToLower() == "true";
break;
case "hideCode":
properties.hideCode = value.ToLower() == "true";
break;
case "hideResources":
properties.hideResources = value.ToLower() == "true";
break;
case "includeSource":
properties.includeSource = value.ToLower() == "true";
break;
case "includePDB":
properties.includePDB = value.ToLower() == "true";
break;
case "buildIgnore":
properties.buildIgnores = value.Split(',').Select(s => s.Trim().Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar)).Where(s => s.Length > 0).ToArray();
break;
case "languageVersion":
if (!int.TryParse(value, out properties.languageVersion))
throw new Exception("languageVersion not an int: " + value);
if (properties.languageVersion < 4 || properties.languageVersion > 6)
throw new Exception("languageVersion (" + properties.languageVersion + ") must be between 4 and 6");
break;
case "side":
if (!Enum.TryParse(value, true, out properties.side))
throw new Exception("side is not one of (Both, Client, Server, NoSync): " + value);
break;
}
}
var refs = properties.RefNames(true).ToList();
if (refs.Count != refs.Distinct().Count())
throw new Exception("Duplicate mod/weak reference");
//add (mod|weak)References that are not in sortBefore to sortAfter
properties.sortAfter = properties.RefNames(true).Where(dep => !properties.sortBefore.Contains(dep))
.Concat(properties.sortAfter).Distinct().ToArray();
return properties;
}
internal byte[] ToBytes()
{
byte[] data;
using (MemoryStream memoryStream = new MemoryStream())
{
using (BinaryWriter writer = new BinaryWriter(memoryStream))
{
if (dllReferences.Length > 0)
{
writer.Write("dllReferences");
WriteList(dllReferences, writer);
}
if (modReferences.Length > 0)
{
writer.Write("modReferences");
WriteList(modReferences, writer);
}
if (weakReferences.Length > 0)
{
writer.Write("weakReferences");
WriteList(weakReferences, writer);
}
if (sortAfter.Length > 0)
{
writer.Write("sortAfter");
WriteList(sortAfter, writer);
}
if (sortBefore.Length > 0)
{
writer.Write("sortBefore");
WriteList(sortBefore, writer);
}
if (author.Length > 0)
{
writer.Write("author");
writer.Write(author);
}
writer.Write("version");
writer.Write(version.ToString());
if (displayName.Length > 0)
{
writer.Write("displayName");
writer.Write(displayName);
}
if (homepage.Length > 0)
{
writer.Write("homepage");
writer.Write(homepage);
}
if (description.Length > 0)
{
writer.Write("description");
writer.Write(description);
}
if (noCompile)
{
writer.Write("noCompile");
}
if (!hideCode)
{
writer.Write("!hideCode");
}
if (!hideResources)
{
writer.Write("!hideResources");
}
if (includeSource)
{
writer.Write("includeSource");
}
if (includePDB)
{
writer.Write("includePDB");
}
if (editAndContinue)
{
writer.Write("editAndContinue");
}
if (side != ModSide.Both)
{
writer.Write("side");
writer.Write((byte)side);
}
writer.Write("");
}
data = memoryStream.ToArray();
}
return data;
}
internal static BuildProperties ReadModFile(TmodFile modFile)
{
BuildProperties properties = new BuildProperties();
byte[] data = modFile.GetFile("Info");
if (data.Length == 0)
return properties;
using (BinaryReader reader = new BinaryReader(new MemoryStream(data)))
{
for (string tag = reader.ReadString(); tag.Length > 0; tag = reader.ReadString())
{
if (tag == "dllReferences")
{
properties.dllReferences = ReadList(reader).ToArray();
}
if (tag == "modReferences")
{
properties.modReferences = ReadList(reader).Select(ModReference.Parse).ToArray();
}
if (tag == "weakReferences")
{
properties.weakReferences = ReadList(reader).Select(ModReference.Parse).ToArray();
}
if (tag == "sortAfter")
{
properties.sortAfter = ReadList(reader).ToArray();
}
if (tag == "sortBefore")
{
properties.sortBefore = ReadList(reader).ToArray();
}
if (tag == "author")
{
properties.author = reader.ReadString();
}
if (tag == "version")
{
properties.version = new Version(reader.ReadString());
}
if (tag == "displayName")
{
properties.displayName = reader.ReadString();
}
if (tag == "homepage")
{
properties.homepage = reader.ReadString();
}
if (tag == "description")
{
properties.description = reader.ReadString();
}
if (tag == "noCompile")
{
properties.noCompile = true;
}
if (tag == "!hideCode")
{
properties.hideCode = false;
}
if (tag == "!hideResources")
{
properties.hideResources = false;
}
if (tag == "includeSource")
{
properties.includeSource = true;
}
if (tag == "includePDB")
{
properties.includePDB = true;
}
if (tag == "editAndContinue")
{
properties.editAndContinue = true;
}
if (tag == "side")
{
properties.side = (ModSide)reader.ReadByte();
}
}
}
return properties;
}
internal bool ignoreFile(string resource)
{
return this.buildIgnores.Any(fileMask => FitsMask(resource, fileMask));
}
private bool FitsMask(string fileName, string fileMask)
{
string pattern =
'^' +
Regex.Escape(fileMask.Replace(".", "__DOT__")
.Replace("*", "__STAR__")
.Replace("?", "__QM__"))
.Replace("__DOT__", "[.]")
.Replace("__STAR__", ".*")
.Replace("__QM__", ".")
+ '$';
return new Regex(pattern, RegexOptions.IgnoreCase).IsMatch(fileName);
}
}
}
| |
// This file was generated by CSLA Object Generator - CslaGenFork v4.5
//
// Filename: User
// ObjectType: User
// CSLAType: EditableRoot
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using DocStore.Business.Util;
using Csla.Rules;
using Csla.Rules.CommonRules;
using DocStore.Business.Security;
namespace DocStore.Business.Admin
{
/// <summary>
/// User (editable root object).<br/>
/// This is a generated <see cref="User"/> business object.
/// </summary>
[Serializable]
public partial class User : BusinessBase<User>
{
#region Static Fields
private static int _lastId;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="UserID"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<int> UserIDProperty = RegisterProperty<int>(p => p.UserID, "User ID");
/// <summary>
/// Gets the User ID.
/// </summary>
/// <value>The User ID.</value>
public int UserID
{
get { return GetProperty(UserIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> NameProperty = RegisterProperty<string>(p => p.Name, "Name");
/// <summary>
/// Gets or sets the Name.
/// </summary>
/// <value>The Name.</value>
public string Name
{
get { return GetProperty(NameProperty); }
set { SetProperty(NameProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="Login"/> property.
/// </summary>
public static readonly PropertyInfo<string> LoginProperty = RegisterProperty<string>(p => p.Login, "Login");
/// <summary>
/// Gets or sets the Login.
/// </summary>
/// <value>The Login.</value>
public string Login
{
get { return GetProperty(LoginProperty); }
set { SetProperty(LoginProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="Picture"/> property.
/// </summary>
public static readonly PropertyInfo<byte[]> PictureProperty = RegisterProperty<byte[]>(p => p.Picture, "Picture");
/// <summary>
/// Gets or sets the Picture.
/// </summary>
/// <value>The Picture.</value>
public byte[] Picture
{
get { return GetProperty(PictureProperty); }
set { SetProperty(PictureProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="Email"/> property.
/// </summary>
public static readonly PropertyInfo<string> EmailProperty = RegisterProperty<string>(p => p.Email, "Email");
/// <summary>
/// Gets or sets the Email.
/// </summary>
/// <value>The Email.</value>
public string Email
{
get { return GetProperty(EmailProperty); }
set { SetProperty(EmailProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="IsActive"/> property.
/// </summary>
public static readonly PropertyInfo<bool> IsActiveProperty = RegisterProperty<bool>(p => p.IsActive, "IsActive");
/// <summary>
/// Gets or sets the active or deleted state.
/// </summary>
/// <value><c>true</c> if IsActive; otherwise, <c>false</c>.</value>
public bool IsActive
{
get { return GetProperty(IsActiveProperty); }
set { SetProperty(IsActiveProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="CreateDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> CreateDateProperty = RegisterProperty<SmartDate>(p => p.CreateDate, "Create Date");
/// <summary>
/// Gets the Create Date.
/// </summary>
/// <value>The Create Date.</value>
public SmartDate CreateDate
{
get { return GetProperty(CreateDateProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="CreateUserID"/> property.
/// </summary>
public static readonly PropertyInfo<int> CreateUserIDProperty = RegisterProperty<int>(p => p.CreateUserID, "Create User ID");
/// <summary>
/// Gets the Create User ID.
/// </summary>
/// <value>The Create User ID.</value>
public int CreateUserID
{
get { return GetProperty(CreateUserIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="ChangeDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> ChangeDateProperty = RegisterProperty<SmartDate>(p => p.ChangeDate, "Change Date");
/// <summary>
/// Gets the Change Date.
/// </summary>
/// <value>The Change Date.</value>
public SmartDate ChangeDate
{
get { return GetProperty(ChangeDateProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="ChangeUserID"/> property.
/// </summary>
public static readonly PropertyInfo<int> ChangeUserIDProperty = RegisterProperty<int>(p => p.ChangeUserID, "Change User ID");
/// <summary>
/// Gets the Change User ID.
/// </summary>
/// <value>The Change User ID.</value>
public int ChangeUserID
{
get { return GetProperty(ChangeUserIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="RowVersion"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<byte[]> RowVersionProperty = RegisterProperty<byte[]>(p => p.RowVersion, "Row Version");
/// <summary>
/// Gets the Row Version.
/// </summary>
/// <value>The Row Version.</value>
public byte[] RowVersion
{
get { return GetProperty(RowVersionProperty); }
}
/// <summary>
/// Gets the Create User Name.
/// </summary>
/// <value>The Create User Name.</value>
public string CreateUserName
{
get
{
var result = string.Empty;
if (UserNVL.GetUserNVL().ContainsKey(CreateUserID))
result = UserNVL.GetUserNVL().GetItemByKey(CreateUserID).Value;
return result;
}
}
/// <summary>
/// Gets the Change User Name.
/// </summary>
/// <value>The Change User Name.</value>
public string ChangeUserName
{
get
{
var result = string.Empty;
if (UserNVL.GetUserNVL().ContainsKey(ChangeUserID))
result = UserNVL.GetUserNVL().GetItemByKey(ChangeUserID).Value;
return result;
}
}
#endregion
#region BusinessBase<T> overrides
/// <summary>
/// Returns a string that represents the current <see cref="User"/>
/// </summary>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public override string ToString()
{
// Return the Primary Key as a string
return Name.ToString();
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="User"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="User"/> object.</returns>
public static User NewUser()
{
return DataPortal.Create<User>();
}
/// <summary>
/// Factory method. Loads a <see cref="User"/> object, based on given parameters.
/// </summary>
/// <param name="userID">The UserID parameter of the User to fetch.</param>
/// <returns>A reference to the fetched <see cref="User"/> object.</returns>
public static User GetUser(int userID)
{
return DataPortal.Fetch<User>(userID);
}
/// <summary>
/// Factory method. Deletes a <see cref="User"/> object, based on given parameters.
/// </summary>
/// <param name="userID">The UserID of the User to delete.</param>
public static void DeleteUser(int userID)
{
DataPortal.Delete<User>(userID);
}
/// <summary>
/// Factory method. Undeletes a <see cref="User"/> object, based on given parameters.
/// </summary>
/// <param name="userID">The UserID of the User to undelete.</param>
/// <returns>A reference to the undeleted <see cref="User"/> object.</returns>
public static User UndeleteUser(int userID)
{
var obj = DataPortal.Fetch<User>(userID);
obj.IsActive = true;
return obj.Save();
}
/// <summary>
/// Factory method. Asynchronously creates a new <see cref="User"/> object.
/// </summary>
/// <param name="callback">The completion callback method.</param>
public static void NewUser(EventHandler<DataPortalResult<User>> callback)
{
DataPortal.BeginCreate<User>(callback);
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="User"/> object, based on given parameters.
/// </summary>
/// <param name="userID">The UserID parameter of the User to fetch.</param>
/// <param name="callback">The completion callback method.</param>
public static void GetUser(int userID, EventHandler<DataPortalResult<User>> callback)
{
DataPortal.BeginFetch<User>(userID, callback);
}
/// <summary>
/// Factory method. Asynchronously deletes a <see cref="User"/> object, based on given parameters.
/// </summary>
/// <param name="userID">The UserID of the User to delete.</param>
/// <param name="callback">The completion callback method.</param>
public static void DeleteUser(int userID, EventHandler<DataPortalResult<User>> callback)
{
DataPortal.BeginDelete<User>(userID, callback);
}
/// <summary>
/// Factory method. Asynchronously undeletes a <see cref="User"/> object, based on given parameters.
/// </summary>
/// <param name="userID">The UserID of the User to undelete.</param>
/// <param name="callback">The completion callback method.</param>
public static void UndeleteUser(int userID, EventHandler<DataPortalResult<User>> callback)
{
var obj = new User();
DataPortal.BeginFetch<User>(userID, (o, e) =>
{
if (e.Error != null)
throw e.Error;
else
obj = e.Object;
});
obj.IsActive = true;
obj.BeginSave(callback);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="User"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public User()
{
// Use factory methods and do not use direct creation.
}
#endregion
#region Object Authorization
/// <summary>
/// Adds the object authorization rules.
/// </summary>
protected static void AddObjectAuthorizationRules()
{
BusinessRules.AddRule(typeof (User), new IsInRole(AuthorizationActions.CreateObject, "Manager"));
BusinessRules.AddRule(typeof (User), new IsInRole(AuthorizationActions.GetObject, "User"));
BusinessRules.AddRule(typeof (User), new IsInRole(AuthorizationActions.EditObject, "Manager"));
BusinessRules.AddRule(typeof (User), new IsInRole(AuthorizationActions.DeleteObject, "Admin"));
AddObjectAuthorizationRulesExtend();
}
/// <summary>
/// Allows the set up of custom object authorization rules.
/// </summary>
static partial void AddObjectAuthorizationRulesExtend();
/// <summary>
/// Checks if the current user can create a new User object.
/// </summary>
/// <returns><c>true</c> if the user can create a new object; otherwise, <c>false</c>.</returns>
public static bool CanAddObject()
{
return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.CreateObject, typeof(User));
}
/// <summary>
/// Checks if the current user can retrieve User's properties.
/// </summary>
/// <returns><c>true</c> if the user can read the object; otherwise, <c>false</c>.</returns>
public static bool CanGetObject()
{
return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.GetObject, typeof(User));
}
/// <summary>
/// Checks if the current user can change User's properties.
/// </summary>
/// <returns><c>true</c> if the user can update the object; otherwise, <c>false</c>.</returns>
public static bool CanEditObject()
{
return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.EditObject, typeof(User));
}
/// <summary>
/// Checks if the current user can delete a User object.
/// </summary>
/// <returns><c>true</c> if the user can delete the object; otherwise, <c>false</c>.</returns>
public static bool CanDeleteObject()
{
return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.DeleteObject, typeof(User));
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="User"/> object properties.
/// </summary>
[RunLocal]
protected override void DataPortal_Create()
{
LoadProperty(UserIDProperty, System.Threading.Interlocked.Decrement(ref _lastId));
LoadProperty(PictureProperty, new byte[0]);
LoadProperty(CreateDateProperty, new SmartDate(DateTime.Now));
LoadProperty(CreateUserIDProperty, UserInformation.UserId);
LoadProperty(ChangeDateProperty, ReadProperty(CreateDateProperty));
LoadProperty(ChangeUserIDProperty, ReadProperty(CreateUserIDProperty));
var args = new DataPortalHookArgs();
OnCreate(args);
base.DataPortal_Create();
}
/// <summary>
/// Loads a <see cref="User"/> object from the database, based on given criteria.
/// </summary>
/// <param name="userID">The User ID.</param>
protected void DataPortal_Fetch(int userID)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("GetUser", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@UserID", userID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, userID);
OnFetchPre(args);
Fetch(cmd);
OnFetchPost(args);
}
}
// check all object rules and property rules
BusinessRules.CheckRules();
}
private void Fetch(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
if (dr.Read())
{
Fetch(dr);
}
}
}
/// <summary>
/// Loads a <see cref="User"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(UserIDProperty, dr.GetInt32("UserID"));
LoadProperty(NameProperty, dr.GetString("Name"));
LoadProperty(LoginProperty, dr.GetString("Login"));
LoadProperty(EmailProperty, dr.GetString("Email"));
LoadProperty(IsActiveProperty, dr.GetBoolean("IsActive"));
LoadProperty(CreateDateProperty, dr.GetSmartDate("CreateDate", true));
LoadProperty(CreateUserIDProperty, dr.GetInt32("CreateUserID"));
LoadProperty(ChangeDateProperty, dr.GetSmartDate("ChangeDate", true));
LoadProperty(ChangeUserIDProperty, dr.GetInt32("ChangeUserID"));
LoadProperty(RowVersionProperty, dr.GetValue("RowVersion") as byte[]);
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="User"/> object in the database.
/// </summary>
protected override void DataPortal_Insert()
{
SimpleAuditTrail();
using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("AddUser", ctx.Connection))
{
cmd.Transaction = ctx.Transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@UserID", ReadProperty(UserIDProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@Name", ReadProperty(NameProperty)).DbType = DbType.String;
cmd.Parameters.AddWithValue("@Login", ReadProperty(LoginProperty)).DbType = DbType.String;
cmd.Parameters.AddWithValue("@Email", ReadProperty(EmailProperty)).DbType = DbType.String;
cmd.Parameters.AddWithValue("@IsActive", ReadProperty(IsActiveProperty)).DbType = DbType.Boolean;
cmd.Parameters.AddWithValue("@CreateDate", ReadProperty(CreateDateProperty).DBValue).DbType = DbType.DateTime2;
cmd.Parameters.AddWithValue("@CreateUserID", ReadProperty(CreateUserIDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@ChangeDate", ReadProperty(ChangeDateProperty).DBValue).DbType = DbType.DateTime2;
cmd.Parameters.AddWithValue("@ChangeUserID", ReadProperty(ChangeUserIDProperty)).DbType = DbType.Int32;
cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(UserIDProperty, (int) cmd.Parameters["@UserID"].Value);
LoadProperty(RowVersionProperty, (byte[]) cmd.Parameters["@NewRowVersion"].Value);
}
ctx.Commit();
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="User"/> object.
/// </summary>
protected override void DataPortal_Update()
{
SimpleAuditTrail();
using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("UpdateUser", ctx.Connection))
{
cmd.Transaction = ctx.Transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@UserID", ReadProperty(UserIDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Name", ReadProperty(NameProperty)).DbType = DbType.String;
cmd.Parameters.AddWithValue("@Login", ReadProperty(LoginProperty)).DbType = DbType.String;
cmd.Parameters.AddWithValue("@Email", ReadProperty(EmailProperty)).DbType = DbType.String;
cmd.Parameters.AddWithValue("@IsActive", ReadProperty(IsActiveProperty)).DbType = DbType.Boolean;
cmd.Parameters.AddWithValue("@ChangeDate", ReadProperty(ChangeDateProperty).DBValue).DbType = DbType.DateTime2;
cmd.Parameters.AddWithValue("@ChangeUserID", ReadProperty(ChangeUserIDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@RowVersion", ReadProperty(RowVersionProperty)).DbType = DbType.Binary;
cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
LoadProperty(RowVersionProperty, (byte[]) cmd.Parameters["@NewRowVersion"].Value);
}
ctx.Commit();
}
}
private void SimpleAuditTrail()
{
LoadProperty(ChangeDateProperty, DateTime.Now);
LoadProperty(ChangeUserIDProperty, UserInformation.UserId);
OnPropertyChanged("ChangeUserName");
if (IsNew)
{
LoadProperty(CreateDateProperty, ReadProperty(ChangeDateProperty));
LoadProperty(CreateUserIDProperty, ReadProperty(ChangeUserIDProperty));
OnPropertyChanged("CreateUserName");
}
}
/// <summary>
/// Self deletes the <see cref="User"/> object.
/// </summary>
protected override void DataPortal_DeleteSelf()
{
DataPortal_Delete(UserID);
}
/// <summary>
/// Deletes the <see cref="User"/> object from database.
/// </summary>
/// <param name="userID">The delete criteria.</param>
protected void DataPortal_Delete(int userID)
{
// audit the object, just in case soft delete is used on this object
SimpleAuditTrail();
using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("DeleteUser", ctx.Connection))
{
cmd.Transaction = ctx.Transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@UserID", userID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, userID);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
ctx.Commit();
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BacklogWikiMockupModule.cs">
// bl4n - Backlog.jp API Client library
// this file is part of bl4n, license under MIT license. http://t-ashula.mit-license.org/2015
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using BL4N.Tests.Properties;
using Nancy;
namespace BL4N.Tests
{
/// <summary>
/// /api/v2/wikis routing module
/// </summary>
public class BacklogWikiMockupModule : NancyModule
{
/// <summary>
/// /api/v2/wikis routing
/// </summary>
public BacklogWikiMockupModule() :
base("/api/v2/wikis")
{
#region /api/v2/wikis
Get[string.Empty] = p => Response.AsJson(new[]
{
new
{
id = 112,
projectId = Request.Query["projectIdOrKey"], // TODO
name = "Home",
tags = new[] { new { id = 12, name = "proceedings" } },
createdUser = new { id = 1, userId = "admin", name = "admin", roleType = 1, lang = "ja", mailAddress = "eguchi@nulab.example" },
created = "2013-05-30T09:11:36Z",
updatedUser = new { id = 1, userId = "admin", name = "admin", roleType = 1, lang = "ja", mailAddress = "eguchi@nulab.example" },
updated = "2013-05-30T09:11:36Z"
}
});
#endregion
#region /api/v2/wikis/count
Get["/count"] = p => Response.AsJson(new { count = 5 });
#endregion
#region /api/v2/wikis/tags
Get["/tags"] = p => Response.AsJson(new[] { new { id = 1, name = "test" } });
#endregion
#region POST /api/v2/wikis
Post[string.Empty] = p =>
{
string projectId = Request.Form["projectId"];
string name = Request.Form["name"];
string content = Request.Form["content"];
//// bool notify = Request.Form["mailNotify"] != null;
return Response.AsJson(new
{
id = 1,
projectId = projectId,
name = name,
content = content,
tags = new[] { new { id = 12, name = "prpceedings" } },
//// attachments = [],
//// sharedFiles = [],
//// stars = [],
createdUser = new { id = 1, userId = "admin", name = "admin", roleTyoe = 1, lang = "ja", mailAddress = "eguchi@nulab.example" },
created = "2012-07-23T06:09:48Z",
updatedUser = new { id = 1, userId = "admin", name = "admin", roleTyoe = 1, lang = "ja", mailAddress = "eguchi@nulab.example" },
updated = "2012-07-23T06:09:48Z"
});
};
#endregion
#region GET /api/v2/wikis/:id
Get["/{id}"] = p => Response.AsJson(new
{
id = p.id,
projectId = 1,
name = "Home",
content = "Content",
tags = new[] { new { id = 12, name = "prpceedings" } },
//// attachments = [],
//// sharedFiles = [],
//// stars = [],
createdUser = new { id = 1, userId = "admin", name = "admin", roleTyoe = 1, lang = "ja", mailAddress = "eguchi@nulab.example" },
created = "2012-07-23T06:09:48Z",
updatedUser = new { id = 1, userId = "admin", name = "admin", roleTyoe = 1, lang = "ja", mailAddress = "eguchi@nulab.example" },
updated = "2012-07-23T06:09:48Z"
});
#endregion
#region PATCH /api/v2/wikis/:id
Patch["/{id}"] = p =>
{
string name = Request.Form["name"];
string content = Request.Form["content"];
//// bool notify = Request.Form["mailNotify"] != null;
return Response.AsJson(new
{
id = p.id,
projectId = 1,
name = name,
content = content,
tags = new[] { new { id = 12, name = "prpceedings" } },
//// attachments = [],
//// sharedFiles = [],
//// stars = [],
createdUser = new { id = 1, userId = "admin", name = "admin", roleTyoe = 1, lang = "ja", mailAddress = "eguchi@nulab.example" },
created = "2012-07-23T06:09:48Z",
updatedUser = new { id = 1, userId = "admin", name = "admin", roleTyoe = 1, lang = "ja", mailAddress = "eguchi@nulab.example" },
updated = "2012-07-23T06:09:48Z"
});
};
#endregion
#region DELETE /api/v2/wikis/:id
Delete["/{id}"] = p => Response.AsJson(new
{
id = p.id,
projectId = 1,
name = "Home",
content = "Content",
tags = new[] { new { id = 12, name = "prpceedings" } },
//// attachments = [],
//// sharedFiles = [],
//// stars = [],
createdUser = new { id = 1, userId = "admin", name = "admin", roleTyoe = 1, lang = "ja", mailAddress = "eguchi@nulab.example" },
created = "2012-07-23T06:09:48Z",
updatedUser = new { id = 1, userId = "admin", name = "admin", roleTyoe = 1, lang = "ja", mailAddress = "eguchi@nulab.example" },
updated = "2012-07-23T06:09:48Z"
});
#endregion
#region /api/v2/wikis/:id/attachments
Get["/{id}/attachments"] = p => Response.AsJson(new[]
{
new { id = 1, name = "IMGP0088.JPG", size = 85079 }
});
#endregion
#region POST /api/v2/wikis/:id/attachments
Post["/{id}/attachments"] = p =>
{
string reqFileIds = Request.Form["attachmentId[]"];
var ids = RequestUtils.ToIds(reqFileIds).ToList();
return Response.AsJson(new[]
{
new
{
id = ids[0],
name = "Duke.png",
size = 196186,
createdUser = new { id = 1, userId = "admin", name = "admin", roleType = 1, lang = "ja", mailAddress = "eguchi@nulab.example" },
created = "2014-07-11T06:26:05Z"
}
});
};
#endregion
#region GET /api/v2/wikis/:wikiId/attachments/:attachmentid
Get["/{wikiid}/attachments/{attachmentid}"] = p =>
{
var fileName = string.Format("{0}.{1}.dat", (long)p.wikiid, (long)p.attachmentid);
var response = new Response
{
ContentType = "application/octet-stream",
Contents = stream =>
{
var logo = Resources.projectIcon;
using (var ms = new MemoryStream())
{
logo.Save(ms, ImageFormat.Png);
ms.Position = 0;
using (var writer = new BinaryWriter(stream))
{
writer.Write(ms.GetBuffer());
}
}
}
};
response.Headers.Add("Content-Disposition", "attachment; filename*=UTF-8''" + fileName);
return response;
};
#endregion
#region DELETE /api/v2/wikis/:id/attachments/:attachmentid
Delete["/{wikiid}/attachments/{attachmentid}"] = p => Response.AsJson(new
{
id = p.attachmentid,
name = "Duke.png",
size = 196186,
createdUser = new { id = 1, userId = "admin", name = "admin", roleType = 1, lang = "ja", mailAddress = "eguchi@nulab.example" },
created = "2014-07-11T06:26:05Z"
});
#endregion
#region /api/v2/wikis/:wikiId/sharedFiles
Get["/{wikiid}/sharedFiles"] = p => Response.AsJson(new[]
{
new
{
id = 825952,
type = "file",
dir = "/PressRelease/20091130/",
name = "20091130.txt",
size = 4836,
createdUser = new { id = 1, userId = "admin", name = "admin", roleType = 1, lang = "ja", mailAddress = "eguchi@nulab.example" },
created = "2009-11-30T01:22:21Z",
//// updatedUser = null,
updated = "2009-11-30T01:22:21Z"
}
});
#endregion
#region POST /api/v2/wikis/:wikiid/sharedFiles
Post["/{wikiid}/sharedFiles"] = p =>
{
string reqFileIds = Request.Form["fileId[]"];
var ids = RequestUtils.ToIds(reqFileIds).ToList();
return Response.AsJson(new[]
{
new
{
id = ids[0],
type = "file",
dir = "/PressRelease/20091130/",
name = "20091130.txt",
size = 4836,
createdUser = new { id = 1, userId = "admin", name = "admin", roleType = 1, lang = "ja", mailAddress = "eguchi@nulab.example" },
created = "2009-11-30T01:22:21Z",
//// updatedUser = null,
updated = "2009-11-30T01:22:21Z"
}
});
};
#endregion
#region DELETE /api/v2/wikis/:wikiid/sharedFiles/:id
Delete["/{wikiid}/sharedFiles/{fileid}"] = p => Response.AsJson(new
{
id = p.fileid,
type = "file",
dir = "/PressRelease/20091130/",
name = "20091130.txt",
size = 4836,
createdUser = new { id = 1, userId = "admin", name = "admin", roleType = 1, lang = "ja", mailAddress = "eguchi@nulab.example" },
created = "2009-11-30T01:22:21Z",
//// updatedUser = null,
updated = "2009-11-30T01:22:21Z"
});
#endregion
#region /api/v2/wikis/:wikiid/history
Get["/{wikiid}/history"] = p => Response.AsJson(new[]
{
new
{
pageId = p.wikiid,
version = 1,
name = "test",
content = "hello world",
createdUser = new { id = 1, userId = "admin", name = "admin", roleType = 1, lang = "ja", mailAddress = "eguchi@nulab.example" },
created = "2009-11-30T01:22:21Z",
}
});
#endregion
#region /api/v2/wikis/:wikiid/stars
Get["/{wikiid}/stars"] = p => Response.AsJson(new[]
{
new
{
id = 75,
//// comment = null,
url = "https://xx.backlogtool.com/alias/wiki/1",
title = "[TEST1] Home | Wiki - Backlog",
presenter = new { id = 1, userId = "admin", name = "admin", roleType = 1, lang = "ja", mailAddress = "eguchi@nulab.example" },
created = "2009-11-30T01:22:21Z"
}
});
#endregion
}
}
}
| |
/*
The MIT License (MIT)
Copyright (c) 2016 Maksim Volkau
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 AddOrUpdateServiceFactory
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
namespace DryIoc
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Runtime.CompilerServices; // for aggressive inlining hints
/// <summary>Methods to work with immutable arrays, and general array sugar.</summary>
public static class ArrayTools
{
/// <summary>Returns true if array is null or have no items.</summary> <typeparam name="T">Type of array item.</typeparam>
/// <param name="source">Source array to check.</param> <returns>True if null or has no items, false otherwise.</returns>
public static bool IsNullOrEmpty<T>(this T[] source)
{
return source == null || source.Length == 0;
}
/// <summary>Returns empty array instead of null, or source array otherwise.</summary> <typeparam name="T">Type of array item.</typeparam>
/// <param name="source">Source array.</param> <returns>Empty array or source.</returns>
public static T[] EmptyIfNull<T>(this T[] source)
{
return source ?? Empty<T>();
}
/// <summary>Returns source enumerable if it is array, otherwise converts source to array.</summary>
/// <typeparam name="T">Array item type.</typeparam>
/// <param name="source">Source enumerable.</param>
/// <returns>Source enumerable or its array copy.</returns>
public static T[] ToArrayOrSelf<T>(this IEnumerable<T> source)
{
return source is T[] ? (T[])source : source.ToArray();
}
/// <summary>Returns new array consisting from all items from source array then all items from added array.
/// If source is null or empty, then added array will be returned.
/// If added is null or empty, then source will be returned.</summary>
/// <typeparam name="T">Array item type.</typeparam>
/// <param name="source">Array with leading items.</param>
/// <param name="added">Array with following items.</param>
/// <returns>New array with items of source and added arrays.</returns>
public static T[] Append<T>(this T[] source, params T[] added)
{
if (added == null || added.Length == 0)
return source;
if (source == null || source.Length == 0)
return added;
var result = new T[source.Length + added.Length];
Array.Copy(source, 0, result, 0, source.Length);
if (added.Length == 1)
result[source.Length] = added[0];
else
Array.Copy(added, 0, result, source.Length, added.Length);
return result;
}
/// <summary>Returns new array with <paramref name="value"/> appended,
/// or <paramref name="value"/> at <paramref name="index"/>, if specified.
/// If source array could be null or empty, then single value item array will be created despite any index.</summary>
/// <typeparam name="T">Array item type.</typeparam>
/// <param name="source">Array to append value to.</param>
/// <param name="value">Value to append.</param>
/// <param name="index">(optional) Index of value to update.</param>
/// <returns>New array with appended or updated value.</returns>
public static T[] AppendOrUpdate<T>(this T[] source, T value, int index = -1)
{
if (source == null || source.Length == 0)
return new[] { value };
var sourceLength = source.Length;
index = index < 0 ? sourceLength : index;
var result = new T[index < sourceLength ? sourceLength : sourceLength + 1];
Array.Copy(source, result, sourceLength);
result[index] = value;
return result;
}
/// <summary>Calls predicate on each item in <paramref name="source"/> array until predicate returns true,
/// then method will return this item index, or if predicate returns false for each item, method will return -1.</summary>
/// <typeparam name="T">Type of array items.</typeparam>
/// <param name="source">Source array: if null or empty, then method will return -1.</param>
/// <param name="predicate">Delegate to evaluate on each array item until delegate returns true.</param>
/// <returns>Index of item for which predicate returns true, or -1 otherwise.</returns>
public static int IndexOf<T>(this T[] source, Func<T, bool> predicate)
{
if (source != null && source.Length != 0)
for (var i = 0; i < source.Length; ++i)
if (predicate(source[i]))
return i;
return -1;
}
/// <summary>Looks up for item in source array equal to provided value, and returns its index, or -1 if not found.</summary>
/// <typeparam name="T">Type of array items.</typeparam>
/// <param name="source">Source array: if null or empty, then method will return -1.</param>
/// <param name="value">Value to look up.</param>
/// <returns>Index of item equal to value, or -1 item is not found.</returns>
public static int IndexOf<T>(this T[] source, T value)
{
if (source != null && source.Length != 0)
for (var i = 0; i < source.Length; ++i)
{
var item = source[i];
if (ReferenceEquals(item, value) || Equals(item, value))
return i;
}
return -1;
}
/// <summary>Produces new array without item at specified <paramref name="index"/>.
/// Will return <paramref name="source"/> array if index is out of bounds, or source is null/empty.</summary>
/// <typeparam name="T">Type of array item.</typeparam>
/// <param name="source">Input array.</param> <param name="index">Index if item to remove.</param>
/// <returns>New array with removed item at index, or input source array if index is not in array.</returns>
public static T[] RemoveAt<T>(this T[] source, int index)
{
if (source == null || source.Length == 0 || index < 0 || index >= source.Length)
return source;
if (index == 0 && source.Length == 1)
return new T[0];
var result = new T[source.Length - 1];
if (index != 0)
Array.Copy(source, 0, result, 0, index);
if (index != result.Length)
Array.Copy(source, index + 1, result, index, result.Length - index);
return result;
}
/// <summary>Looks for item in array using equality comparison, and returns new array with found item remove, or original array if not item found.</summary>
/// <typeparam name="T">Type of array item.</typeparam>
/// <param name="source">Input array.</param> <param name="value">Value to find and remove.</param>
/// <returns>New array with value removed or original array if value is not found.</returns>
public static T[] Remove<T>(this T[] source, T value)
{
return source.RemoveAt(source.IndexOf(value));
}
/// <summary>Returns singleton empty array of provided type.</summary>
/// <typeparam name="T">Array item type.</typeparam> <returns>Empty array.</returns>
public static T[] Empty<T>()
{
return EmptyArray<T>.Value;
}
private static class EmptyArray<T>
{
public static readonly T[] Value = new T[0];
}
}
/// <summary>Wrapper that provides optimistic-concurrency Swap operation implemented using <see cref="Ref.Swap{T}"/>.</summary>
/// <typeparam name="T">Type of object to wrap.</typeparam>
public sealed class Ref<T> where T : class
{
/// <summary>Gets the wrapped value.</summary>
public T Value { get { return _value; } }
/// <summary>Creates ref to object, optionally with initial value provided.</summary>
/// <param name="initialValue">(optional) Initial value.</param>
public Ref(T initialValue = default(T))
{
_value = initialValue;
}
/// <summary>Exchanges currently hold object with <paramref name="getNewValue"/> - see <see cref="Ref.Swap{T}"/> for details.</summary>
/// <param name="getNewValue">Delegate to produce new object value from current one passed as parameter.</param>
/// <returns>Returns old object value the same way as <see cref="Interlocked.Exchange(ref int,int)"/></returns>
/// <remarks>Important: <paramref name="getNewValue"/> May be called multiple times to retry update with value concurrently changed by other code.</remarks>
public T Swap(Func<T, T> getNewValue)
{
return Ref.Swap(ref _value, getNewValue);
}
/// <summary>Just sets new value ignoring any intermingled changes.</summary>
/// <param name="newValue"></param> <returns>old value</returns>
public T Swap(T newValue)
{
return Interlocked.Exchange(ref _value, newValue);
}
/// <summary>Compares current Referred value with <paramref name="currentValue"/> and if equal replaces current with <paramref name="newValue"/></summary>
/// <param name="currentValue"></param> <param name="newValue"></param>
/// <returns>True if current value was replaced with new value, and false if current value is outdated (already changed by other party).</returns>
/// <example><c>[!CDATA[
/// var value = SomeRef.Value;
/// if (!SomeRef.TrySwapIfStillCurrent(value, Update(value))
/// SomeRef.Swap(v => Update(v)); // fallback to normal Swap with delegate allocation
/// ]]</c></example>
public bool TrySwapIfStillCurrent(T currentValue, T newValue)
{
return Interlocked.CompareExchange(ref _value, newValue, currentValue) == currentValue;
}
private T _value;
}
/// <summary>Provides optimistic-concurrency consistent <see cref="Swap{T}"/> operation.</summary>
public static class Ref
{
/// <summary>Factory for <see cref="Ref{T}"/> with type of value inference.</summary>
/// <typeparam name="T">Type of value to wrap.</typeparam>
/// <param name="value">Initial value to wrap.</param>
/// <returns>New ref.</returns>
public static Ref<T> Of<T>(T value) where T : class
{
return new Ref<T>(value);
}
/// <summary>Creates new ref to the value of original ref.</summary> <typeparam name="T">Ref value type.</typeparam>
/// <param name="original">Original ref.</param> <returns>New ref to original value.</returns>
public static Ref<T> NewRef<T>(this Ref<T> original) where T : class
{
return Of(original.Value);
}
/// <summary>First, it evaluates new value using <paramref name="getNewValue"/> function.
/// Second, it checks that original value is not changed.
/// If it is changed it will retry first step, otherwise it assigns new value and returns original (the one used for <paramref name="getNewValue"/>).</summary>
/// <typeparam name="T">Type of value to swap.</typeparam>
/// <param name="value">Reference to change to new value</param>
/// <param name="getNewValue">Delegate to get value from old one.</param>
/// <returns>Old/original value. By analogy with <see cref="Interlocked.Exchange(ref int,int)"/>.</returns>
/// <remarks>Important: <paramref name="getNewValue"/> May be called multiple times to retry update with value concurrently changed by other code.</remarks>
public static T Swap<T>(ref T value, Func<T, T> getNewValue) where T : class
{
var retryCount = 0;
while (true)
{
var oldValue = value;
var newValue = getNewValue(oldValue);
if (Interlocked.CompareExchange(ref value, newValue, oldValue) == oldValue)
return oldValue;
if (++retryCount > RETRY_COUNT_UNTIL_THROW)
throw new InvalidOperationException(_errorRetryCountExceeded);
}
}
private const int RETRY_COUNT_UNTIL_THROW = 50;
private static readonly string _errorRetryCountExceeded =
"Ref retried to Update for " + RETRY_COUNT_UNTIL_THROW + " times But there is always someone else intervened.";
}
/// <summary>Immutable Key-Value pair. It is reference type (could be check for null),
/// which is different from System value type <see cref="KeyValuePair{TKey,TValue}"/>.
/// In addition provides <see cref="Equals"/> and <see cref="GetHashCode"/> implementations.</summary>
/// <typeparam name="K">Type of Key.</typeparam><typeparam name="V">Type of Value.</typeparam>
public class KV<K, V>
{
/// <summary>Key.</summary>
public readonly K Key;
/// <summary>Value.</summary>
public readonly V Value;
/// <summary>Creates Key-Value object by providing key and value. Does Not check either one for null.</summary>
/// <param name="key">key.</param><param name="value">value.</param>
public KV(K key, V value)
{
Key = key;
Value = value;
}
/// <summary>Creates nice string view.</summary><returns>String representation.</returns>
public override string ToString()
{
var s = new StringBuilder('{');
if (Key != null)
s.Append(Key);
s.Append(',');
if (Value != null)
s.Append(Value);
s.Append('}');
return s.ToString();
}
/// <summary>Returns true if both key and value are equal to corresponding key-value of other object.</summary>
/// <param name="obj">Object to check equality with.</param> <returns>True if equal.</returns>
public override bool Equals(object obj)
{
var other = obj as KV<K, V>;
return other != null
&& (ReferenceEquals(other.Key, Key) || Equals(other.Key, Key))
&& (ReferenceEquals(other.Value, Value) || Equals(other.Value, Value));
}
/// <summary>Combines key and value hash code. R# generated default implementation.</summary>
/// <returns>Combined hash code for key-value.</returns>
public override int GetHashCode()
{
unchecked
{
return ((object)Key == null ? 0 : Key.GetHashCode() * 397)
^ ((object)Value == null ? 0 : Value.GetHashCode());
}
}
}
/// <summary>Helpers for <see cref="KV{K,V}"/>.</summary>
public static class KV
{
/// <summary>Creates the key value pair.</summary>
/// <typeparam name="K">Key type</typeparam> <typeparam name="V">Value type</typeparam>
/// <param name="key">Key</param> <param name="value">Value</param> <returns>New pair.</returns>
[MethodImpl((MethodImplOptions)256)] // AggressiveInlining
public static KV<K, V> Of<K, V>(K key, V value)
{
return new KV<K, V>(key, value);
}
/// <summary>Creates the new pair with new key and old value.</summary>
/// <typeparam name="K">Key type</typeparam> <typeparam name="V">Value type</typeparam>
/// <param name="source">Source value</param> <param name="key">New key</param> <returns>New pair</returns>
[MethodImpl((MethodImplOptions)256)] // AggressiveInlining
public static KV<K, V> WithKey<K, V>(this KV<K, V> source, K key)
{
return new KV<K, V>(key, source.Value);
}
/// <summary>Creates the new pair with old key and new value.</summary>
/// <typeparam name="K">Key type</typeparam> <typeparam name="V">Value type</typeparam>
/// <param name="source">Source value</param> <param name="value">New value.</param> <returns>New pair</returns>
[MethodImpl((MethodImplOptions)256)] // AggressiveInlining
public static KV<K, V> WithValue<K, V>(this KV<K, V> source, V value)
{
return new KV<K, V>(source.Key, value);
}
}
/// <summary>Delegate for changing value from old one to some new based on provided new value.</summary>
/// <typeparam name="V">Type of values.</typeparam>
/// <param name="oldValue">Existing value.</param>
/// <param name="newValue">New value passed to Update.. method.</param>
/// <returns>Changed value.</returns>
public delegate V Update<V>(V oldValue, V newValue);
// todo: V3: Rename to ImTree
/// <summary>Simple immutable AVL tree with integer keys and object values.</summary>
public sealed class ImTreeMapIntToObj
{
/// <summary>Empty tree to start with.</summary>
public static readonly ImTreeMapIntToObj Empty = new ImTreeMapIntToObj();
/// <summary>Key.</summary>
public readonly int Key;
/// <summary>Value.</summary>
public readonly object Value;
/// <summary>Left sub-tree/branch, or empty.</summary>
public readonly ImTreeMapIntToObj Left;
/// <summary>Right sub-tree/branch, or empty.</summary>
public readonly ImTreeMapIntToObj Right;
/// <summary>Height of longest sub-tree/branch plus 1. It is 0 for empty tree, and 1 for single node tree.</summary>
public readonly int Height;
/// <summary>Returns true is tree is empty.</summary>
public bool IsEmpty { get { return Height == 0; } }
/// <summary>Returns new tree with added or updated value for specified key.</summary>
/// <param name="key"></param> <param name="value"></param>
/// <returns>New tree.</returns>
public ImTreeMapIntToObj AddOrUpdate(int key, object value)
{
return AddOrUpdate(key, value, false, null);
}
/// <summary>Delegate to calculate new value from and old and a new value.</summary>
/// <param name="oldValue">Old</param> <param name="newValue">New</param> <returns>Calculated result.</returns>
public delegate object UpdateValue(object oldValue, object newValue);
/// <summary>Returns new tree with added or updated value for specified key.</summary>
/// <param name="key">Key</param> <param name="value">Value</param>
/// <param name="updateValue">(optional) Delegate to calculate new value from and old and a new value.</param>
/// <returns>New tree.</returns>
public ImTreeMapIntToObj AddOrUpdate(int key, object value, UpdateValue updateValue)
{
return AddOrUpdate(key, value, false, updateValue);
}
/// <summary>Returns new tree with updated value for the key, Or the same tree if key was not found.</summary>
/// <param name="key"></param> <param name="value"></param>
/// <returns>New tree if key is found, or the same tree otherwise.</returns>
public ImTreeMapIntToObj Update(int key, object value)
{
return AddOrUpdate(key, value, true, null);
}
/// <summary>Get value for found key or null otherwise.</summary>
/// <param name="key"></param> <returns>Found value or null.</returns>
public object GetValueOrDefault(int key)
{
var tree = this;
while (tree.Height != 0 && tree.Key != key)
tree = key < tree.Key ? tree.Left : tree.Right;
return tree.Height != 0 ? tree.Value : null;
}
/// <summary>Returns all sub-trees enumerated from left to right.</summary>
/// <returns>Enumerated sub-trees or empty if tree is empty.</returns>
public IEnumerable<ImTreeMapIntToObj> Enumerate()
{
if (Height == 0)
yield break;
var parents = new ImTreeMapIntToObj[Height];
var tree = this;
var parentCount = -1;
while (tree.Height != 0 || parentCount != -1)
{
if (tree.Height != 0)
{
parents[++parentCount] = tree;
tree = tree.Left;
}
else
{
tree = parents[parentCount--];
yield return tree;
tree = tree.Right;
}
}
}
#region Implementation
private ImTreeMapIntToObj() { }
private ImTreeMapIntToObj(int key, object value, ImTreeMapIntToObj left, ImTreeMapIntToObj right)
{
Key = key;
Value = value;
Left = left;
Right = right;
Height = 1 + (left.Height > right.Height ? left.Height : right.Height);
}
private ImTreeMapIntToObj AddOrUpdate(int key, object value, bool updateOnly, UpdateValue update)
{
return Height == 0 ? // tree is empty
(updateOnly ? this : new ImTreeMapIntToObj(key, value, Empty, Empty))
: (key == Key ? // actual update
new ImTreeMapIntToObj(key, update == null ? value : update(Value, value), Left, Right)
: (key < Key // try update on left or right sub-tree
? With(Left.AddOrUpdate(key, value, updateOnly, update), Right)
: With(Left, Right.AddOrUpdate(key, value, updateOnly, update))).KeepBalanced());
}
private ImTreeMapIntToObj KeepBalanced()
{
var delta = Left.Height - Right.Height;
return delta >= 2 ? With(Left.Right.Height - Left.Left.Height == 1 ? Left.RotateLeft() : Left, Right).RotateRight()
: (delta <= -2 ? With(Left, Right.Left.Height - Right.Right.Height == 1 ? Right.RotateRight() : Right).RotateLeft()
: this);
}
private ImTreeMapIntToObj RotateRight()
{
return Left.With(Left.Left, With(Left.Right, Right));
}
private ImTreeMapIntToObj RotateLeft()
{
return Right.With(With(Left, Right.Left), Right.Right);
}
private ImTreeMapIntToObj With(ImTreeMapIntToObj left, ImTreeMapIntToObj right)
{
return left == Left && right == Right ? this : new ImTreeMapIntToObj(Key, Value, left, right);
}
#endregion
}
// todo: V3: Rename to ImHashTree
/// <summary>Immutable http://en.wikipedia.org/wiki/AVL_tree where actual node key is hash code of <typeparamref name="K"/>.</summary>
public sealed class ImTreeMap<K, V>
{
/// <summary>Empty tree to start with.</summary>
public static readonly ImTreeMap<K, V> Empty = new ImTreeMap<K, V>();
/// <summary>Key of type K that should support <see cref="object.Equals(object)"/> and <see cref="object.GetHashCode"/>.</summary>
public readonly K Key;
/// <summary>Value of any type V.</summary>
public readonly V Value;
/// <summary>Calculated key hash.</summary>
public readonly int Hash;
/// <summary>In case of <see cref="Hash"/> conflicts for different keys contains conflicted keys with their values.</summary>
public readonly KV<K, V>[] Conflicts;
/// <summary>Left sub-tree/branch, or empty.</summary>
public readonly ImTreeMap<K, V> Left;
/// <summary>Right sub-tree/branch, or empty.</summary>
public readonly ImTreeMap<K, V> Right;
/// <summary>Height of longest sub-tree/branch plus 1. It is 0 for empty tree, and 1 for single node tree.</summary>
public readonly int Height;
/// <summary>Returns true if tree is empty.</summary>
public bool IsEmpty { get { return Height == 0; } }
/// <summary>Returns new tree with added key-value. If value with the same key is exist, then
/// if <paramref name="update"/> is not specified: then existing value will be replaced by <paramref name="value"/>;
/// if <paramref name="update"/> is specified: then update delegate will decide what value to keep.</summary>
/// <param name="key">Key to add.</param><param name="value">Value to add.</param>
/// <param name="update">(optional) Delegate to decide what value to keep: old or new one.</param>
/// <returns>New tree with added or updated key-value.</returns>
public ImTreeMap<K, V> AddOrUpdate(K key, V value, Update<V> update = null)
{
return AddOrUpdate(key.GetHashCode(), key, value, update, updateOnly: false);
}
/// <summary>Looks for <paramref name="key"/> and replaces its value with new <paramref name="value"/>, or
/// runs custom update handler (<paramref name="update"/>) with old and new value to get the updated result.</summary>
/// <param name="key">Key to look for.</param>
/// <param name="value">New value to replace key value with.</param>
/// <param name="update">(optional) Delegate for custom update logic, it gets old and new <paramref name="value"/>
/// as inputs and should return updated value as output.</param>
/// <returns>New tree with updated value or the SAME tree if no key found.</returns>
public ImTreeMap<K, V> Update(K key, V value, Update<V> update = null)
{
return AddOrUpdate(key.GetHashCode(), key, value, update, updateOnly: true);
}
/// <summary>Looks for key in a tree and returns the key value if found, or <paramref name="defaultValue"/> otherwise.</summary>
/// <param name="key">Key to look for.</param> <param name="defaultValue">(optional) Value to return if key is not found.</param>
/// <returns>Found value or <paramref name="defaultValue"/>.</returns>
public V GetValueOrDefault(K key, V defaultValue = default(V))
{
var t = this;
var hash = key.GetHashCode();
while (t.Height != 0 && t.Hash != hash)
t = hash < t.Hash ? t.Left : t.Right;
return t.Height != 0 && (ReferenceEquals(key, t.Key) || key.Equals(t.Key))
? t.Value : t.GetConflictedValueOrDefault(key, defaultValue);
}
/// <summary>Depth-first in-order traversal as described in http://en.wikipedia.org/wiki/Tree_traversal
/// The only difference is using fixed size array instead of stack for speed-up (~20% faster than stack).</summary>
/// <returns>Sequence of enumerated key value pairs.</returns>
public IEnumerable<KV<K, V>> Enumerate()
{
if (Height == 0)
yield break;
var parents = new ImTreeMap<K, V>[Height];
var tree = this;
var parentCount = -1;
while (tree.Height != 0 || parentCount != -1)
{
if (tree.Height != 0)
{
parents[++parentCount] = tree;
tree = tree.Left;
}
else
{
tree = parents[parentCount--];
yield return new KV<K, V>(tree.Key, tree.Value);
if (tree.Conflicts != null)
for (var i = 0; i < tree.Conflicts.Length; i++)
yield return tree.Conflicts[i];
tree = tree.Right;
}
}
}
#region Implementation
private ImTreeMap() { }
private ImTreeMap(int hash, K key, V value, KV<K, V>[] conficts, ImTreeMap<K, V> left, ImTreeMap<K, V> right)
{
Hash = hash;
Key = key;
Value = value;
Conflicts = conficts;
Left = left;
Right = right;
Height = 1 + (left.Height > right.Height ? left.Height : right.Height);
}
private ImTreeMap<K, V> AddOrUpdate(int hash, K key, V value, Update<V> update, bool updateOnly)
{
return Height == 0 ? (updateOnly ? this : new ImTreeMap<K, V>(hash, key, value, null, Empty, Empty))
: (hash == Hash ? UpdateValueAndResolveConflicts(key, value, update, updateOnly)
: (hash < Hash
? With(Left.AddOrUpdate(hash, key, value, update, updateOnly), Right)
: With(Left, Right.AddOrUpdate(hash, key, value, update, updateOnly))).KeepBalanced());
}
private ImTreeMap<K, V> UpdateValueAndResolveConflicts(K key, V value, Update<V> update, bool updateOnly)
{
if (ReferenceEquals(Key, key) || Key.Equals(key))
return new ImTreeMap<K, V>(Hash, key, update == null ? value : update(Value, value), Conflicts, Left, Right);
if (Conflicts == null) // add only if updateOnly is false.
return updateOnly ? this
: new ImTreeMap<K, V>(Hash, Key, Value, new[] { new KV<K, V>(key, value) }, Left, Right);
var found = Conflicts.Length - 1;
while (found >= 0 && !Equals(Conflicts[found].Key, Key)) --found;
if (found == -1)
{
if (updateOnly) return this;
var newConflicts = new KV<K, V>[Conflicts.Length + 1];
Array.Copy(Conflicts, 0, newConflicts, 0, Conflicts.Length);
newConflicts[Conflicts.Length] = new KV<K, V>(key, value);
return new ImTreeMap<K, V>(Hash, Key, Value, newConflicts, Left, Right);
}
var conflicts = new KV<K, V>[Conflicts.Length];
Array.Copy(Conflicts, 0, conflicts, 0, Conflicts.Length);
conflicts[found] = new KV<K, V>(key, update == null ? value : update(Conflicts[found].Value, value));
return new ImTreeMap<K, V>(Hash, Key, Value, conflicts, Left, Right);
}
private V GetConflictedValueOrDefault(K key, V defaultValue)
{
if (Conflicts != null)
for (var i = 0; i < Conflicts.Length; i++)
if (Equals(Conflicts[i].Key, key))
return Conflicts[i].Value;
return defaultValue;
}
private ImTreeMap<K, V> KeepBalanced()
{
var delta = Left.Height - Right.Height;
return delta >= 2 ? With(Left.Right.Height - Left.Left.Height == 1 ? Left.RotateLeft() : Left, Right).RotateRight()
: (delta <= -2 ? With(Left, Right.Left.Height - Right.Right.Height == 1 ? Right.RotateRight() : Right).RotateLeft()
: this);
}
private ImTreeMap<K, V> RotateRight()
{
return Left.With(Left.Left, With(Left.Right, Right));
}
private ImTreeMap<K, V> RotateLeft()
{
return Right.With(With(Left, Right.Left), Right.Right);
}
private ImTreeMap<K, V> With(ImTreeMap<K, V> left, ImTreeMap<K, V> right)
{
return left == Left && right == Right ? this : new ImTreeMap<K, V>(Hash, Key, Value, Conflicts, left, right);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*
** Copyright (c) Microsoft. All rights reserved.
** Licensed under the MIT license.
** See LICENSE file in the project root for full license information.
**
** This program was translated to C# and adapted for xunit-performance.
** New variants of several tests were added to compare class versus
** struct and to compare jagged arrays vs multi-dimensional arrays.
*/
// Captures contents of NNET.DAT as a string
// to simplfy testing in CoreCLR.
internal class NeuralData
{
public static string Input =
"5 7 8 \n"
+ "26 \n"
+ "0 0 1 0 0 \n"
+ "0 1 0 1 0 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 1 1 1 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "0 1 0 0 0 0 0 1 \n"
+ "1 1 1 1 0 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 1 1 1 0 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 1 1 1 0 \n"
+ "0 1 0 0 0 0 1 0 \n"
+ "0 1 1 1 0 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 1 \n"
+ "0 1 1 1 0 \n"
+ "0 1 0 0 0 0 1 1 \n"
+ "1 1 1 1 0 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 1 1 1 0 \n"
+ "0 1 0 0 0 1 0 0 \n"
+ "1 1 1 1 1 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "1 1 1 0 0 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "1 1 1 1 1 \n"
+ "0 1 0 0 0 1 0 1 \n"
+ "1 1 1 1 1 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "1 1 1 0 0 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "0 1 0 0 0 1 1 0 \n"
+ "0 1 1 1 0 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 1 1 \n"
+ "1 0 0 0 1 \n"
+ "0 1 1 1 0 \n"
+ "0 1 0 0 0 1 1 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 1 1 1 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "0 1 0 0 1 0 0 0 \n"
+ "0 1 1 1 0 \n"
+ "0 0 1 0 0 \n"
+ "0 0 1 0 0 \n"
+ "0 0 1 0 0 \n"
+ "0 0 1 0 0 \n"
+ "0 0 1 0 0 \n"
+ "0 1 1 1 0 \n"
+ "0 1 0 0 1 0 0 1 \n"
+ "0 0 0 0 1 \n"
+ "0 0 0 0 1 \n"
+ "0 0 0 0 1 \n"
+ "0 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "0 1 1 1 0 \n"
+ "0 1 0 0 1 0 1 0 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 1 0 \n"
+ "1 0 1 0 0 \n"
+ "1 1 0 0 0 \n"
+ "1 0 1 0 0 \n"
+ "1 0 0 1 0 \n"
+ "1 0 0 0 1 \n"
+ "0 1 0 0 1 0 1 1 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "1 1 1 1 1 \n"
+ "0 1 0 0 1 1 0 0 \n"
+ "1 0 0 0 1 \n"
+ "1 1 0 1 1 \n"
+ "1 0 1 0 1 \n"
+ "1 0 1 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "0 1 0 0 1 1 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 1 0 0 1 \n"
+ "1 0 1 0 1 \n"
+ "1 0 1 0 1 \n"
+ "1 0 1 0 1 \n"
+ "1 0 0 1 1 \n"
+ "1 0 0 0 1 \n"
+ "0 1 0 0 1 1 1 0 \n"
+ "0 1 1 1 0 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "0 1 1 1 0 \n"
+ "0 1 0 0 1 1 1 1 \n"
+ "1 1 1 1 0 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 1 1 1 0 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "0 1 0 1 0 0 0 0 \n"
+ "0 1 1 1 0 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 1 0 1 \n"
+ "1 0 0 1 1 \n"
+ "0 1 1 1 1 \n"
+ "0 1 0 1 0 0 0 1 \n"
+ "1 1 1 1 0 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 1 1 1 0 \n"
+ "1 0 1 0 0 \n"
+ "1 0 0 1 0 \n"
+ "1 0 0 0 1 \n"
+ "0 1 0 1 0 0 1 0 \n"
+ "0 1 1 1 1 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "0 1 1 1 0 \n"
+ "0 0 0 0 1 \n"
+ "0 0 0 0 1 \n"
+ "1 1 1 1 0 \n"
+ "0 1 0 1 0 0 1 1 \n"
+ "1 1 1 1 1 \n"
+ "0 0 1 0 0 \n"
+ "0 0 1 0 0 \n"
+ "0 0 1 0 0 \n"
+ "0 0 1 0 0 \n"
+ "0 0 1 0 0 \n"
+ "0 0 1 0 0 \n"
+ "0 1 0 1 0 1 0 0 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "0 1 1 1 0 \n"
+ "0 1 0 1 0 1 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "0 1 0 1 0 \n"
+ "0 1 0 1 0 \n"
+ "0 1 0 1 0 \n"
+ "0 1 0 1 0 \n"
+ "0 0 1 0 0 \n"
+ "0 1 0 1 0 1 1 0 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 1 0 1 \n"
+ "1 0 1 0 1 \n"
+ "1 0 1 0 1 \n"
+ "0 1 0 1 0 \n"
+ "0 1 0 1 0 1 1 1 \n"
+ "1 0 0 0 1 \n"
+ "0 1 0 1 0 \n"
+ "0 1 0 1 0 \n"
+ "0 0 1 0 0 \n"
+ "0 1 0 1 0 \n"
+ "0 1 0 1 0 \n"
+ "1 0 0 0 1 \n"
+ "0 1 0 1 1 0 0 0 \n"
+ "1 0 0 0 1 \n"
+ "0 1 0 1 0 \n"
+ "0 1 0 1 0 \n"
+ "0 0 1 0 0 \n"
+ "0 0 1 0 0 \n"
+ "0 0 1 0 0 \n"
+ "0 0 1 0 0 \n"
+ "0 1 0 1 1 0 0 1 \n"
+ "1 1 1 1 1 \n"
+ "0 0 0 1 0 \n"
+ "0 0 0 1 0 \n"
+ "0 0 1 0 0 \n"
+ "0 1 0 0 0 \n"
+ "0 1 0 0 0 \n"
+ "1 1 1 1 1 \n"
+ "0 1 0 1 1 0 1 0 \n"
+ " \n";
}
| |
using System;
using MonoBrick;
namespace MonoBrick.NXT
{
/// <summary>
/// Motor ports
/// </summary>
public enum MotorPort {
#pragma warning disable
OutA = 0, OutB = 1, OutC = 2
#pragma warning restore
};
/// <summary>
/// Motor mode
/// </summary>
[Flags] public enum MotorMode {
#pragma warning disable
On = 0x01, Break = 0x02, Regulated = 0x04
#pragma warning restore
};
/// <summary>
/// Motor regulation
/// </summary>
public enum MotorRegulation {
#pragma warning disable
Idle = 0x00, Speed = 0x01, Sync = 0x02
#pragma warning restore
};
/// <summary>
/// Motor run state
/// </summary>
public enum MotorRunState {
#pragma warning disable
Idle = 0x00, RampUp = 0x10, Running = 0x20, RampDown = 0x40
#pragma warning restore
};
/// <summary>
/// Output state of the motor
/// </summary>
public struct OutputState{
/// <summary>
/// Gets or sets the speed.
/// </summary>
/// <value>
/// The speed.
/// </value>
public sbyte Speed{get;set;}
/// <summary>
/// Gets or sets the mode.
/// </summary>
/// <value>
/// The mode.
/// </value>
public MotorMode Mode{get;set;}
/// <summary>
/// Gets or sets the regulation.
/// </summary>
/// <value>
/// The regulation.
/// </value>
public MotorRegulation Regulation{get;set;}
/// <summary>
/// Gets or sets the turn ratio.
/// </summary>
/// <value>
/// The turn ratio.
/// </value>
public sbyte TurnRatio{get;set;}
/// <summary>
/// Gets or sets the state of the run.
/// </summary>
/// <value>
/// The state of the run.
/// </value>
public MotorRunState RunState{get;set;}
/// <summary>
/// Gets or sets the tacho limit.
/// </summary>
/// <value>
/// The tacho limit.
/// </value>
public UInt32 TachoLimit{get;set;}//Current limit on a movement in progres, if any
/// <summary>
/// Gets or sets the tacho count.
/// </summary>
/// <value>
/// The tacho count.
/// </value>
public Int32 TachoCount{get;internal set;}//Internal count. Number of counts since last reset of motor
/// <summary>
/// Gets or sets the block tacho count.
/// </summary>
/// <value>
/// The block tacho count.
/// </value>
public Int32 BlockTachoCount{get;internal set;} //Current position relative to last programmed movement
/// <summary>
/// Gets or sets the rotation count.
/// </summary>
/// <value>
/// The rotation count.
/// </value>
public Int32 RotationCount{get;internal set;} //Current position relative to last reset of the rotation sensor for this
}
/// <summary>
/// Motor class
/// </summary>
public class Motor : IMotor
{
private MotorPort port = MotorPort.OutA;
private Connection<Command,Reply> connection = null;
private bool reverse;
internal MotorPort Port{
get{ return port;}
set{ port = value;}
}
internal Connection<Command,Reply> Connection{
get{ return connection;}
set{ connection = value;}
}
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.NXT.Motor"/> class.
/// </summary>
public Motor() { Reverse = false; Sync = false;}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="MonoBrick.NXT.Motor"/> run in reverse direction
/// </summary>
/// <value>
/// <c>true</c> if reverse; otherwise, <c>false</c>.
/// </value>
public bool Reverse {get{return reverse;} set{reverse = value;}}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="MonoBrick.NXT.Motor"/> is synchronised with another motor.
/// Two motors needs to have this to true in order to work
/// </summary>
/// <value>
/// <c>true</c> if sync; otherwise, <c>false</c>.
/// </value>
public bool Sync{get;set;}
/// <summary>
/// Sets the output state of the motor
/// </summary>
/// <param name='state'>
/// Outputstate
/// </param>
public void SetOutputState(OutputState state){
SetOutputState(state,false);
}
/// <summary>
/// Sets the output state of the motor
/// </summary>
/// <param name='state'>
/// Outputstate
/// </param>
/// <param name='reply'>
/// If set to <c>true</c> the brick will send a reply
/// </param>
public void SetOutputState(OutputState state, bool reply){
if(state.Speed > 100){
state.Speed = 100;
}
if(state.Speed < -100){
state.Speed = -100;
}
if(state.TurnRatio > 100){
state.TurnRatio = 100;
}
if(state.TurnRatio < -100){
state.TurnRatio = 100;
}
if (Reverse)
state.Speed = (sbyte)-state.Speed;
var command = new Command(CommandType.DirecCommand,CommandByte.SetOutputState, reply);
command.Append((byte)port);
command.Append(state.Speed);
command.Append((byte)state.Mode);
command.Append((byte)state.Regulation);
command.Append(state.TurnRatio);
command.Append((byte)state.RunState);
command.Append(state.TachoLimit);
command.Append((byte) 0x00);//why a 5th byte?
connection.Send(command);
if(reply){
var brickReply = connection.Receive();
Error.CheckForError(brickReply,3);
}
}
/// <summary>
/// Move the motor
/// </summary>
/// <param name='speed'>
/// Speed of the motor -100 to 100
/// </param>
public void On(sbyte speed){
On (speed,false);
}
/// <summary>
/// Move the motor
/// </summary>
/// <param name='speed'>
/// Speed of the motor -100 to 100
/// </param>
/// <param name='reply'>
/// If set to <c>true</c> brick will send a reply
/// </param>
public void On(sbyte speed, bool reply){
On(speed, 0, reply);
}
/// <summary>
/// Move the motor to a relative position
/// </summary>
/// <param name='speed'>
/// Speed of the motor -100 to 100
/// </param>
/// <param name='degrees'>
/// The relative position of the motor
/// </param>
public void On(sbyte speed, UInt32 degrees){
On (speed,degrees,false);
}
/// <summary>
/// Move the motor to a relative position
/// </summary>
/// <param name='speed'>
/// Speed of the motor -100 to 100
/// </param>
/// <param name='degrees'>
/// The relative position of the motor
/// </param>
/// <param name='reply'>
/// If set to <c>true</c> the brick will send a reply
/// </param>
public void On(sbyte speed, UInt32 degrees,bool reply){
OutputState state = new OutputState();
state.Speed = speed;
state.Mode = MotorMode.Break | MotorMode.On | MotorMode.Regulated;
state.Regulation = MotorRegulation.Speed;
state.TurnRatio = 100;
state.RunState = MotorRunState.Running;
state.TachoLimit = degrees;
SetOutputState(state, reply);
}
/*public void RampUp(sbyte speed, UInt32 degrees) {
RampUp(speed,degrees,false);
}
public void RampUp(sbyte speed, UInt32 degrees, bool reply) {
SetOutputState(speed, degrees, MotorMode.Break | MotorMode.On | MotorMode.Regulated, MotorRegulation.Speed, MotorRunState.RampUp, 100, reply);
}
public void RampDown(sbyte speed, UInt32 degrees){
RampDown(speed,degrees,false);
}
public void RampDown(sbyte speed, UInt32 degrees, bool reply)
{
SetOutputState(speed, degrees, MotorMode.Break | MotorMode.On | MotorMode.Regulated, MotorRegulation.Speed, MotorRunState.RampDown, 100, reply);
}*/
/// <summary>
/// Brake the motor (is still on but does not move)
/// </summary>
public void Brake(){
Brake(false);
}
/// <summary>
/// Brake the motor (is still on but does not move)
/// </summary>
/// <param name='reply'>
/// If set to <c>true</c> the brick will send a reply
/// </param>
public void Brake(bool reply){
OutputState state = new OutputState();
state.Speed = 0;
state.Mode = MotorMode.Break | MotorMode.On | MotorMode.Regulated;
state.Regulation = MotorRegulation.Speed;
state.TurnRatio = 100;
state.RunState = MotorRunState.Running;
state.TachoLimit = 0;
SetOutputState(state, reply);
}
/// <summary>
/// Turn the motor off
/// </summary>
public void Off(){
Off (false);
}
/// <summary>
/// Turn the motor off
/// </summary>
/// <param name='reply'>
/// If set to <c>true</c> the brick will send a reply
/// </param>
public void Off(bool reply)
{
OutputState state = new OutputState();
state.Speed = 0;
state.Mode = MotorMode.Break | MotorMode.Regulated;
state.Regulation = MotorRegulation.Speed;
state.TurnRatio = 100;
state.RunState = MotorRunState.Running;
state.TachoLimit = 0;
SetOutputState(state, reply);
}
/// <summary>
/// Gets the output state of the motor
/// </summary>
/// <returns>
/// The output state
/// </returns>
public OutputState GetOutputState() {
OutputState motorOutput = new OutputState();
var command = new Command(CommandType.DirecCommand, CommandByte.GetOutputState,true);
command.Append((byte)port);
connection.Send(command);
var reply = connection.Receive();
Error.CheckForError(reply,25);
motorOutput.Speed = reply.GetSbyte(4);
motorOutput.Mode = (MotorMode)reply[5];
motorOutput.Regulation = (MotorRegulation)reply[6];
motorOutput.TurnRatio = reply.GetSbyte(7);
motorOutput.RunState = (MotorRunState)reply[8];
motorOutput.TachoLimit = reply.GetUInt32(9);
motorOutput.TachoCount = reply.GetInt32(13);
motorOutput.BlockTachoCount = reply.GetInt32(17);
motorOutput.RotationCount = reply.GetInt32(21);
return motorOutput;
}
private void ResetMotorPosition(bool relative) {
ResetMotorPosition(relative,false);
}
private void ResetMotorPosition(bool relative, bool reply) {
var command = new Command(CommandType.DirecCommand, CommandByte.ResetMotorPosition, reply);
command.Append((byte)Port);
command.Append(relative);
connection.Send(command);
if (reply)
{
var brickReply = connection.Receive();
Error.CheckForError(brickReply, 3);
}
}
/// <summary>
/// Moves the motor to an absolute position
/// </summary>
/// <param name='speed'>
/// Speed of the motor 0 to 100
/// </param>
/// <param name='position'>
/// Absolute position
/// </param>
/// <param name='reply'>
/// If set to <c>true</c> the brick will send a reply
/// </param>
public void MoveTo(byte speed, Int32 position, bool reply){
bool savedReverse = reverse;
Int32 move = position-GetTachoCount();
if(move == 0)
return;
if(move < 0){
Reverse = true;
}
else{
Reverse = false;
}
try{
On((sbyte)speed, (uint) Math.Abs(move), reply);
}
catch(Exception e){
Reverse = savedReverse;
throw(e);
}
Reverse = savedReverse;
}
/// <summary>
/// Moves the motor to an absolute position
/// </summary>
/// <param name='speed'>
/// Speed of the motor -100 to 100
/// </param>
/// <param name='position'>
/// Absolute position
/// </param>
public void MoveTo(byte speed, Int32 position){
MoveTo(speed,position, false);
}
/// <summary>
/// Resets the tacho
/// </summary>
public void ResetTacho() {
ResetTacho(false);
}
/// <summary>
/// Resets the tacho
/// </summary>
/// <param name='reply'>
/// If set to <c>true</c> the brick will send a reply
/// </param>
public void ResetTacho(bool reply) {
ResetMotorPosition(false, reply);
ResetMotorPosition(true, reply);
}
/// <summary>
/// Gets the tacho count.
/// </summary>
/// <returns>
/// The tacho count
/// </returns>
public Int32 GetTachoCount() {
return GetOutputState().RotationCount;
}
/// <summary>
/// Determines whether this motor is running.
/// </summary>
/// <returns>
/// <c>true</c> if this motor is running; otherwise, <c>false</c>.
/// </returns>
public bool IsRunning() {
if (GetOutputState().RunState == MotorRunState.Idle)
return false;
return true;
}
}
/// <summary>
/// Vehicle class
/// </summary>
public class Vehicle: IVehicle{
private Motor left = new Motor();
private Motor right = new Motor();
private Connection<Command,Reply> connection = null;
internal Connection<Command,Reply> Connection{
get{ return connection;}
set{
connection = value;
left.Connection = value;
right.Connection = value;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.NXT.Vehicle"/> class.
/// </summary>
/// <param name='left'>
/// The left motor of the vehicle
/// </param>
/// <param name='right'>
/// The right motor of the vehicle
/// </param>
public Vehicle(MotorPort left, MotorPort right){
this.left.Port = left;
this.right.Port = right;
Sync = false;
}
/// <summary>
/// Gets or sets the left motor
/// </summary>
/// <value>
/// The left motor
/// </value>
public MotorPort LeftPort{
get{
return left.Port;
}
set{
left.Port = value;
}
}
/// <summary>
/// Gets or sets the right motor
/// </summary>
/// <value>
/// The right motor
/// </value>
public MotorPort RightPort{
get{
return right.Port;
}
set{
right.Port = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether the left motor is running in reverse direction
/// </summary>
/// <value>
/// <c>true</c> if left motor is reverse; otherwise, <c>false</c>.
/// </value>
public bool ReverseLeft{
get{
return left.Reverse;
}
set{
left.Reverse = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether the right motor is running in reverse direction
/// </summary>
/// <value>
/// <c>true</c> if right motor is reverse; otherwise, <c>false</c>.
/// </value>
public bool ReverseRight{
get{
return right.Reverse;
}
set{
right.Reverse = value;
}
}
private bool Sync{get;set;}
/// <summary>
/// Run backwards
/// </summary>
/// <param name='speed'>
/// Speed of the vehicle -100 to 100
/// </param>
public void Backward(sbyte speed){
Move((sbyte)-speed,0,false);
}
/// <summary>
/// Run backwards
/// </summary>
/// <param name='speed'>
/// Speed of the vehicle -100 to 100
/// </param>
/// <param name='reply'>
/// If set to <c>true</c> the brick will send a reply
/// </param>
public void Backward(sbyte speed, bool reply){
Move((sbyte)-speed,0,reply);
}
/*public void Backward(sbyte speed, UInt32 degrees){
Move((sbyte)-speed,degrees,false);
}
public void Backward(sbyte speed, UInt32 degrees, bool reply){
Move((sbyte)-speed,degrees, reply);
}*/
/// <summary>
/// Run forward
/// </summary>
/// <param name='speed'>
/// Speed of the vehicle -100 to 100
/// </param>
public void Forward(sbyte speed){
Move(speed,0,false);
}
/// <summary>
/// Run forward
/// </summary>
/// <param name='speed'>
/// Speed of the vehicle -100 to 100
/// </param>
/// <param name='reply'>
/// If set to <c>true</c> the brick will send a reply
/// </param>
public void Forward(sbyte speed, bool reply){
Move(speed,0,reply);
}
/*public void Forward(sbyte speed, UInt32 degrees){
Forward(speed,degrees,false);
}
public void Forward(sbyte speed, UInt32 degrees, bool reply){
Move(speed, degrees, reply);
}*/
private void Move(sbyte speed, UInt32 degrees, bool reply){
OutputState state = new OutputState();
state.Speed = speed;
state.Mode = MotorMode.Break | MotorMode.On | MotorMode.Regulated;
if(Sync)
state.Regulation = MotorRegulation.Sync;
else{
state.Regulation = MotorRegulation.Speed;
}
state.TurnRatio = 100;
state.RunState = MotorRunState.Running;
state.TachoLimit = degrees;
left.SetOutputState(state,reply);
right.SetOutputState(state,reply);
}
/// <summary>
/// Spins the vehicle left.
/// </summary>
/// <param name='speed'>
/// Speed of the vehicle -100 to 100
/// </param>
public void SpinLeft(sbyte speed){
SpinLeft(speed,false);
}
/// <summary>
/// Spins the vehicle left.
/// </summary>
/// <param name='speed'>
/// Speed of the vehicle -100 to 100
/// </param>
/// <param name='reply'>
/// If set to <c>true</c> the brick will send a reply
/// </param>
public void SpinLeft(sbyte speed, bool reply){
right.On(speed,reply);
left.On((sbyte)-speed,reply);
}
/// <summary>
/// Spins the vehicle right
/// </summary>
/// <param name='speed'>
/// Speed of the vehicle -100 to 100
/// </param>
public void SpinRight(sbyte speed){
SpinRight(speed,false);
}
/// <summary>
/// Spins the vehicle right
/// </summary>
/// <param name='speed'>
/// Speed -100 to 100
/// </param>
/// <param name='reply'>
/// If set to <c>true</c> the brick will send a reply
/// </param>
public void SpinRight(sbyte speed, bool reply){
right.On((sbyte)-speed,reply);
left.On(speed,reply);
}
/// <summary>
/// Stop moving the vehicle
/// </summary>
/// <param name='reply'>
/// If set to <c>true</c> the brick will send a reply
/// </param>
public void Off(bool reply){
left.Off(reply);
right.Off(reply);
}
/// <summary>
/// Stop moving the vehicle
/// </summary>
public void Off(){
Off(false);
}
/// <summary>
/// Brake the vehicle (the motor is still on but it does not move)
/// </summary>
public void Brake(){
Brake(false);
}
/// <summary>
/// Brake the vehicle (the motor is still on but it does not move)
/// </summary>
/// <param name='reply'>
/// If set to <c>true</c> the brick will send a reply
/// </param>
public void Brake(bool reply){
OutputState state = new OutputState();
state.Speed = 0;
state.Mode = MotorMode.Break | MotorMode.On | MotorMode.Regulated;
if(Sync)
state.Regulation = MotorRegulation.Sync;
else{
state.Regulation = MotorRegulation.Speed;
}
state.TurnRatio = 100;
state.RunState = MotorRunState.Running;
state.TachoLimit = 0;
left.SetOutputState(state,reply);
right.SetOutputState(state,reply);
}
/// <summary>
/// Turns the vehicle right
/// </summary>
/// <param name='speed'>
/// Speed of the vehicle -100 to 100
/// </param>
/// <param name='turnPercent'>
/// Turn percent
/// </param>
public void TurnRightForward(sbyte speed, sbyte turnPercent){
TurnRightForward(speed, turnPercent, false);
}
/// <summary>
/// Turns the vehicle right
/// </summary>
/// <param name='speed'>
/// Speed of the vehicle -100 to 100
/// </param>
/// <param name='turnPercent'>
/// Turn percent
/// </param>
/// <param name='reply'>
/// If set to <c>true</c> the brick will send a reply
/// </param>
public void TurnRightForward(sbyte speed, sbyte turnPercent, bool reply){
left.On(speed,reply);
right.On((sbyte)((double)speed * ((double)turnPercent/100.0)),reply);
}
/// <summary>
/// Turns the vehicle right will moving backwards
/// </summary>
/// <param name='speed'>
/// Speed of the vehicle -100 to 100
/// </param>
/// <param name='turnPercent'>
/// Turn percent.
/// </param>
public void TurnRightReverse(sbyte speed, sbyte turnPercent){
TurnRightReverse(speed, turnPercent, false);
}
/// <summary>
/// Turns the vehicle right will moving backwards
/// </summary>
/// <param name='speed'>
/// Speed of the vehicle -100 to 100
/// </param>
/// <param name='turnPercent'>
/// Turn percent.
/// </param>
/// <param name='reply'>
/// If set to <c>true</c> the brick will send a reply
/// </param>
public void TurnRightReverse(sbyte speed, sbyte turnPercent, bool reply){
left.On((sbyte)-speed,reply);
right.On( (sbyte)((double)-speed * ((double)turnPercent/100.0)),reply);
}
/// <summary>
/// Turns the vehicle left
/// </summary>
/// <param name='speed'>
/// Speed of the vehicle -100 to 100
/// </param>
/// <param name='turnPercent'>
/// Turn percent.
/// </param>
public void TurnLeftForward(sbyte speed, sbyte turnPercent){
TurnLeftForward(speed, turnPercent, false);
}
/// <summary>
/// Turns the vehicle left
/// </summary>
/// <param name='speed'>
/// Speed of the vehicle -100 to 100
/// </param>
/// <param name='turnPercent'>
/// Turn percent.
/// </param>
/// <param name='reply'>
/// If set to <c>true</c> the brick will send a reply
/// </param>
public void TurnLeftForward(sbyte speed, sbyte turnPercent, bool reply){
right.On(speed,reply);
left.On( (sbyte)((double)speed * ((double)turnPercent/100.0)),reply);
}
/// <summary>
/// Turns the vehicle left will moving backwards
/// </summary>
/// <param name='speed'>
/// Speed of the vehicle -100 to 100
/// </param>
/// <param name='turnPercent'>
/// Turn percent.
/// </param>
public void TurnLeftReverse(sbyte speed, sbyte turnPercent){
TurnLeftReverse(speed, turnPercent, false);
}
/// <summary>
/// Turns the vehicle left will moving backwards
/// </summary>
/// <param name='speed'>
/// Speed of the vehicle -100 to 100
/// </param>
/// <param name='turnPercent'>
/// Turn percent.
/// </param>
/// <param name='reply'>
/// If set to <c>true</c> the brick will send a reply
/// </param>
public void TurnLeftReverse(sbyte speed, sbyte turnPercent, bool reply){
right.On((sbyte)-speed,reply);
left.On( (sbyte)((double)-speed * ((double)turnPercent/100.0)),reply);
}
/*public void ResetTacho() {
motor1.ResetTacho();
motor2.ResetTacho();
}*/
/*public void ResetTacho(bool reply) {
motor1.ResetTacho(reply);
motor2.ResetTacho(reply);
}*/
}
}
| |
#region Copyright notice and license
// Copyright 2015-2016 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using Grpc.Core.Interceptors;
using Grpc.Core.Internal;
using Grpc.Core.Utils;
namespace Grpc.Core
{
/// <summary>
/// Generic base class for client-side stubs.
/// </summary>
public abstract class ClientBase<T> : ClientBase
where T : ClientBase<T>
{
/// <summary>
/// Initializes a new instance of <c>ClientBase</c> class that
/// throws <c>NotImplementedException</c> upon invocation of any RPC.
/// This constructor is only provided to allow creation of test doubles
/// for client classes (e.g. mocking requires a parameterless constructor).
/// </summary>
protected ClientBase() : base()
{
}
/// <summary>
/// Initializes a new instance of <c>ClientBase</c> class.
/// </summary>
/// <param name="configuration">The configuration.</param>
protected ClientBase(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Initializes a new instance of <c>ClientBase</c> class.
/// </summary>
/// <param name="channel">The channel to use for remote call invocation.</param>
public ClientBase(ChannelBase channel) : base(channel)
{
}
/// <summary>
/// Initializes a new instance of <c>ClientBase</c> class.
/// </summary>
/// <param name="callInvoker">The <c>CallInvoker</c> for remote call invocation.</param>
public ClientBase(CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>
/// Creates a new client that sets host field for calls explicitly.
/// gRPC supports multiple "hosts" being served by a single server.
/// By default (if a client was not created by calling this method),
/// host <c>null</c> with the meaning "use default host" is used.
/// </summary>
public T WithHost(string host)
{
var newConfiguration = this.Configuration.WithHost(host);
return NewInstance(newConfiguration);
}
/// <summary>
/// Creates a new instance of client from given <c>ClientBaseConfiguration</c>.
/// </summary>
protected abstract T NewInstance(ClientBaseConfiguration configuration);
}
/// <summary>
/// Base class for client-side stubs.
/// </summary>
public abstract class ClientBase
{
readonly ClientBaseConfiguration configuration;
readonly CallInvoker callInvoker;
/// <summary>
/// Initializes a new instance of <c>ClientBase</c> class that
/// throws <c>NotImplementedException</c> upon invocation of any RPC.
/// This constructor is only provided to allow creation of test doubles
/// for client classes (e.g. mocking requires a parameterless constructor).
/// </summary>
protected ClientBase() : this(new UnimplementedCallInvoker())
{
}
/// <summary>
/// Initializes a new instance of <c>ClientBase</c> class.
/// </summary>
/// <param name="configuration">The configuration.</param>
protected ClientBase(ClientBaseConfiguration configuration)
{
this.configuration = GrpcPreconditions.CheckNotNull(configuration, "configuration");
this.callInvoker = configuration.CreateDecoratedCallInvoker();
}
/// <summary>
/// Initializes a new instance of <c>ClientBase</c> class.
/// </summary>
/// <param name="channel">The channel to use for remote call invocation.</param>
public ClientBase(ChannelBase channel) : this(channel.CreateCallInvoker())
{
}
/// <summary>
/// Initializes a new instance of <c>ClientBase</c> class.
/// </summary>
/// <param name="callInvoker">The <c>CallInvoker</c> for remote call invocation.</param>
public ClientBase(CallInvoker callInvoker) : this(new ClientBaseConfiguration(callInvoker, null))
{
}
/// <summary>
/// Gets the call invoker.
/// </summary>
protected CallInvoker CallInvoker
{
get { return this.callInvoker; }
}
/// <summary>
/// Gets the configuration.
/// </summary>
internal ClientBaseConfiguration Configuration
{
get { return this.configuration; }
}
/// <summary>
/// Represents configuration of ClientBase. The class itself is visible to
/// subclasses, but contents are marked as internal to make the instances opaque.
/// The verbose name of this class was chosen to make name clash in generated code
/// less likely.
/// </summary>
protected internal class ClientBaseConfiguration
{
private class ClientBaseConfigurationInterceptor : Interceptor
{
readonly Func<IMethod, string, CallOptions, ClientBaseConfigurationInfo> interceptor;
/// <summary>
/// Creates a new instance of ClientBaseConfigurationInterceptor given the specified header and host interceptor function.
/// </summary>
public ClientBaseConfigurationInterceptor(Func<IMethod, string, CallOptions, ClientBaseConfigurationInfo> interceptor)
{
this.interceptor = GrpcPreconditions.CheckNotNull(interceptor, nameof(interceptor));
}
private ClientInterceptorContext<TRequest, TResponse> GetNewContext<TRequest, TResponse>(ClientInterceptorContext<TRequest, TResponse> context)
where TRequest : class
where TResponse : class
{
var newHostAndCallOptions = interceptor(context.Method, context.Host, context.Options);
return new ClientInterceptorContext<TRequest, TResponse>(context.Method, newHostAndCallOptions.Host, newHostAndCallOptions.CallOptions);
}
public override TResponse BlockingUnaryCall<TRequest, TResponse>(TRequest request, ClientInterceptorContext<TRequest, TResponse> context, BlockingUnaryCallContinuation<TRequest, TResponse> continuation)
{
return continuation(request, GetNewContext(context));
}
public override AsyncUnaryCall<TResponse> AsyncUnaryCall<TRequest, TResponse>(TRequest request, ClientInterceptorContext<TRequest, TResponse> context, AsyncUnaryCallContinuation<TRequest, TResponse> continuation)
{
return continuation(request, GetNewContext(context));
}
public override AsyncServerStreamingCall<TResponse> AsyncServerStreamingCall<TRequest, TResponse>(TRequest request, ClientInterceptorContext<TRequest, TResponse> context, AsyncServerStreamingCallContinuation<TRequest, TResponse> continuation)
{
return continuation(request, GetNewContext(context));
}
public override AsyncClientStreamingCall<TRequest, TResponse> AsyncClientStreamingCall<TRequest, TResponse>(ClientInterceptorContext<TRequest, TResponse> context, AsyncClientStreamingCallContinuation<TRequest, TResponse> continuation)
{
return continuation(GetNewContext(context));
}
public override AsyncDuplexStreamingCall<TRequest, TResponse> AsyncDuplexStreamingCall<TRequest, TResponse>(ClientInterceptorContext<TRequest, TResponse> context, AsyncDuplexStreamingCallContinuation<TRequest, TResponse> continuation)
{
return continuation(GetNewContext(context));
}
}
internal struct ClientBaseConfigurationInfo
{
internal readonly string Host;
internal readonly CallOptions CallOptions;
internal ClientBaseConfigurationInfo(string host, CallOptions callOptions)
{
Host = host;
CallOptions = callOptions;
}
}
readonly CallInvoker undecoratedCallInvoker;
readonly string host;
internal ClientBaseConfiguration(CallInvoker undecoratedCallInvoker, string host)
{
this.undecoratedCallInvoker = GrpcPreconditions.CheckNotNull(undecoratedCallInvoker);
this.host = host;
}
internal CallInvoker CreateDecoratedCallInvoker()
{
return undecoratedCallInvoker.Intercept(new ClientBaseConfigurationInterceptor((method, host, options) => new ClientBaseConfigurationInfo(this.host, options)));
}
internal ClientBaseConfiguration WithHost(string host)
{
GrpcPreconditions.CheckNotNull(host, nameof(host));
return new ClientBaseConfiguration(this.undecoratedCallInvoker, host);
}
}
}
}
| |
// 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.
/*============================================================
**
**
**
** Provides a way for an app to not start an operation unless
** there's a reasonable chance there's enough memory
** available for the operation to succeed.
**
**
===========================================================*/
using System;
using System.IO;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.Diagnostics;
using System.Diagnostics.Contracts;
/*
This class allows an application to fail before starting certain
activities. The idea is to fail early instead of failing in the middle
of some long-running operation to increase the survivability of the
application and ensure you don't have to write tricky code to handle an
OOM anywhere in your app's code (which implies state corruption, meaning you
should unload the appdomain, if you have a transacted environment to ensure
rollback of individual transactions). This is an incomplete tool to attempt
hoisting all your OOM failures from anywhere in your worker methods to one
particular point where it is easier to handle an OOM failure, and you can
optionally choose to not start a workitem if it will likely fail. This does
not help the performance of your code directly (other than helping to avoid
AD unloads). The point is to avoid starting work if it is likely to fail.
The Enterprise Services team has used these memory gates effectively in the
unmanaged world for a decade.
In Whidbey, we will simply check to see if there is enough memory available
in the OS's page file & attempt to ensure there might be enough space free
within the process's address space (checking for address space fragmentation
as well). We will not commit or reserve any memory. To avoid race conditions with
other threads using MemoryFailPoints, we'll also keep track of a
process-wide amount of memory "reserved" via all currently-active
MemoryFailPoints. This has two problems:
1) This can account for memory twice. If a thread creates a
MemoryFailPoint for 100 MB then allocates 99 MB, we'll see 99 MB
less free memory and 100 MB less reserved memory. Yet, subtracting
off the 100 MB is necessary because the thread may not have started
allocating memory yet. Disposing of this class immediately after
front-loaded allocations have completed is a great idea.
2) This is still vulnerable to race conditions with other threads that don't use
MemoryFailPoints.
So this class is far from perfect. But it may be good enough to
meaningfully reduce the frequency of OutOfMemoryExceptions in managed apps.
In Orcas or later, we might allocate some memory from the OS and add it
to a allocation context for this thread. Obviously, at that point we need
some way of conveying when we release this block of memory. So, we
implemented IDisposable on this type in Whidbey and expect all users to call
this from within a using block to provide lexical scope for their memory
usage. The call to Dispose (implicit with the using block) will give us an
opportunity to release this memory, perhaps. We anticipate this will give
us the possibility of a more effective design in a future version.
In Orcas, we may also need to differentiate between allocations that would
go into the normal managed heap vs. the large object heap, or we should
consider checking for enough free space in both locations (with any
appropriate adjustments to ensure the memory is contiguous).
*/
namespace System.Runtime
{
public sealed class MemoryFailPoint : CriticalFinalizerObject, IDisposable
{
// Find the top section of user mode memory. Avoid the last 64K.
// Windows reserves that block for the kernel, apparently, and doesn't
// let us ask about that memory. But since we ask for memory in 1 MB
// chunks, we don't have to special case this. Also, we need to
// deal with 32 bit machines in 3 GB mode.
// Using Win32's GetSystemInfo should handle all this for us.
private static readonly ulong TopOfMemory;
// Walking the address space is somewhat expensive, taking around half
// a millisecond. Doing that per transaction limits us to a max of
// ~2000 transactions/second. Instead, let's do this address space
// walk once every 10 seconds, or when we will likely fail. This
// amortization scheme can reduce the cost of a memory gate by about
// a factor of 100.
private static long hiddenLastKnownFreeAddressSpace = 0;
private static long hiddenLastTimeCheckingAddressSpace = 0;
private const int CheckThreshold = 10 * 1000; // 10 seconds
private static long LastKnownFreeAddressSpace
{
get { return Volatile.Read(ref hiddenLastKnownFreeAddressSpace); }
set { Volatile.Write(ref hiddenLastKnownFreeAddressSpace, value); }
}
private static long AddToLastKnownFreeAddressSpace(long addend)
{
return Interlocked.Add(ref hiddenLastKnownFreeAddressSpace, addend);
}
private static long LastTimeCheckingAddressSpace
{
get { return Volatile.Read(ref hiddenLastTimeCheckingAddressSpace); }
set { Volatile.Write(ref hiddenLastTimeCheckingAddressSpace, value); }
}
// When allocating memory segment by segment, we've hit some cases
// where there are only 22 MB of memory available on the machine,
// we need 1 16 MB segment, and the OS does not succeed in giving us
// that memory. Reasons for this could include:
// 1) The GC does allocate memory when doing a collection.
// 2) Another process on the machine could grab that memory.
// 3) Some other part of the runtime might grab this memory.
// If we build in a little padding, we can help protect
// ourselves against some of these cases, and we want to err on the
// conservative side with this class.
private const int LowMemoryFudgeFactor = 16 << 20;
// Round requested size to a 16MB multiple to have a better granularity
// when checking for available memory.
private const int MemoryCheckGranularity = 16;
// Note: This may become dynamically tunable in the future.
// Also note that we can have different segment sizes for the normal vs.
// large object heap. We currently use the max of the two.
private static readonly ulong GCSegmentSize;
// For multi-threaded workers, we want to ensure that if two workers
// use a MemoryFailPoint at the same time, and they both succeed, that
// they don't trample over each other's memory. Keep a process-wide
// count of "reserved" memory, and decrement this in Dispose and
// in the critical finalizer. See
// SharedStatics.MemoryFailPointReservedMemory
private ulong _reservedMemory; // The size of this request (from user)
private bool _mustSubtractReservation; // Did we add data to SharedStatics?
static MemoryFailPoint()
{
GetMemorySettings(out GCSegmentSize, out TopOfMemory);
}
// We can remove this link demand in a future version - we will
// have scenarios for this in partial trust in the future, but
// we're doing this just to restrict this in case the code below
// is somehow incorrect.
public MemoryFailPoint(int sizeInMegabytes)
{
if (sizeInMegabytes <= 0)
throw new ArgumentOutOfRangeException(nameof(sizeInMegabytes), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
#if !FEATURE_PAL // Remove this when CheckForAvailableMemory is able to provide legitimate estimates
ulong size = ((ulong)sizeInMegabytes) << 20;
_reservedMemory = size;
// Check to see that we both have enough memory on the system
// and that we have enough room within the user section of the
// process's address space. Also, we need to use the GC segment
// size, not the amount of memory the user wants to allocate.
// Consider correcting this to reflect free memory within the GC
// heap, and to check both the normal & large object heaps.
ulong segmentSize = (ulong)(Math.Ceiling((double)size / GCSegmentSize) * GCSegmentSize);
if (segmentSize >= TopOfMemory)
throw new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint_TooBig);
ulong requestedSizeRounded = (ulong)(Math.Ceiling((double)sizeInMegabytes / MemoryCheckGranularity) * MemoryCheckGranularity);
//re-convert into bytes
requestedSizeRounded <<= 20;
ulong availPageFile = 0; // available VM (physical + page file)
ulong totalAddressSpaceFree = 0; // non-contiguous free address space
// Check for available memory, with 2 attempts at getting more
// memory.
// Stage 0: If we don't have enough, trigger a GC.
// Stage 1: If we don't have enough, try growing the swap file.
// Stage 2: Update memory state, then fail or leave loop.
//
// (In the future, we could consider adding another stage after
// Stage 0 to run finalizers. However, before doing that make sure
// that we could abort this constructor when we call
// GC.WaitForPendingFinalizers, noting that this method uses a CER
// so it can't be aborted, and we have a critical finalizer. It
// would probably work, but do some thinking first.)
for (int stage = 0; stage < 3; stage++)
{
CheckForAvailableMemory(out availPageFile, out totalAddressSpaceFree);
// If we have enough room, then skip some stages.
// Note that multiple threads can still lead to a race condition for our free chunk
// of address space, which can't be easily solved.
ulong reserved = SharedStatics.MemoryFailPointReservedMemory;
ulong segPlusReserved = segmentSize + reserved;
bool overflow = segPlusReserved < segmentSize || segPlusReserved < reserved;
bool needPageFile = availPageFile < (requestedSizeRounded + reserved + LowMemoryFudgeFactor) || overflow;
bool needAddressSpace = totalAddressSpaceFree < segPlusReserved || overflow;
// Ensure our cached amount of free address space is not stale.
long now = Environment.TickCount; // Handle wraparound.
if ((now > LastTimeCheckingAddressSpace + CheckThreshold || now < LastTimeCheckingAddressSpace) ||
LastKnownFreeAddressSpace < (long)segmentSize)
{
CheckForFreeAddressSpace(segmentSize, false);
}
bool needContiguousVASpace = (ulong)LastKnownFreeAddressSpace < segmentSize;
BCLDebug.Trace("MEMORYFAILPOINT", "MemoryFailPoint: Checking for {0} MB, for allocation size of {1} MB, stage {9}. Need page file? {2} Need Address Space? {3} Need Contiguous address space? {4} Avail page file: {5} MB Total free VA space: {6} MB Contiguous free address space (found): {7} MB Space reserved via process's MemoryFailPoints: {8} MB",
segmentSize >> 20, sizeInMegabytes, needPageFile,
needAddressSpace, needContiguousVASpace,
availPageFile >> 20, totalAddressSpaceFree >> 20,
LastKnownFreeAddressSpace >> 20, reserved, stage);
if (!needPageFile && !needAddressSpace && !needContiguousVASpace)
break;
switch (stage)
{
case 0:
// The GC will release empty segments to the OS. This will
// relieve us from having to guess whether there's
// enough memory in either GC heap, and whether
// internal fragmentation will prevent those
// allocations from succeeding.
GC.Collect();
continue;
case 1:
// Do this step if and only if the page file is too small.
if (!needPageFile)
continue;
// Attempt to grow the OS's page file. Note that we ignore
// any allocation routines from the host intentionally.
RuntimeHelpers.PrepareConstrainedRegions();
// This shouldn't overflow due to the if clauses above.
UIntPtr numBytes = new UIntPtr(segmentSize);
unsafe
{
void* pMemory = Win32Native.VirtualAlloc(null, numBytes, Win32Native.MEM_COMMIT, Win32Native.PAGE_READWRITE);
if (pMemory != null)
{
bool r = Win32Native.VirtualFree(pMemory, UIntPtr.Zero, Win32Native.MEM_RELEASE);
if (!r)
throw Win32Marshal.GetExceptionForLastWin32Error();
}
}
continue;
case 2:
// The call to CheckForAvailableMemory above updated our
// state.
if (needPageFile || needAddressSpace)
{
InsufficientMemoryException e = new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint);
#if _DEBUG
e.Data["MemFailPointState"] = new MemoryFailPointState(sizeInMegabytes, segmentSize,
needPageFile, needAddressSpace, needContiguousVASpace,
availPageFile >> 20, totalAddressSpaceFree >> 20,
LastKnownFreeAddressSpace >> 20, reserved);
#endif
throw e;
}
if (needContiguousVASpace)
{
InsufficientMemoryException e = new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint_VAFrag);
#if _DEBUG
e.Data["MemFailPointState"] = new MemoryFailPointState(sizeInMegabytes, segmentSize,
needPageFile, needAddressSpace, needContiguousVASpace,
availPageFile >> 20, totalAddressSpaceFree >> 20,
LastKnownFreeAddressSpace >> 20, reserved);
#endif
throw e;
}
break;
default:
Debug.Assert(false, "Fell through switch statement!");
break;
}
}
// Success - we have enough room the last time we checked.
// Now update our shared state in a somewhat atomic fashion
// and handle a simple race condition with other MemoryFailPoint instances.
AddToLastKnownFreeAddressSpace(-((long)size));
if (LastKnownFreeAddressSpace < 0)
CheckForFreeAddressSpace(segmentSize, true);
RuntimeHelpers.PrepareConstrainedRegions();
SharedStatics.AddMemoryFailPointReservation((long)size);
_mustSubtractReservation = true;
#endif
}
private static void CheckForAvailableMemory(out ulong availPageFile, out ulong totalAddressSpaceFree)
{
bool r;
Win32Native.MEMORYSTATUSEX memory = new Win32Native.MEMORYSTATUSEX();
r = Win32Native.GlobalMemoryStatusEx(ref memory);
if (!r)
throw Win32Marshal.GetExceptionForLastWin32Error();
availPageFile = memory.availPageFile;
totalAddressSpaceFree = memory.availVirtual;
//Console.WriteLine("Memory gate: Mem load: {0}% Available memory (physical + page file): {1} MB Total free address space: {2} MB GC Heap: {3} MB", memory.memoryLoad, memory.availPageFile >> 20, memory.availVirtual >> 20, GC.GetTotalMemory(true) >> 20);
}
// Based on the shouldThrow parameter, this will throw an exception, or
// returns whether there is enough space. In all cases, we update
// our last known free address space, hopefully avoiding needing to
// probe again.
private static unsafe bool CheckForFreeAddressSpace(ulong size, bool shouldThrow)
{
// Start walking the address space at 0. VirtualAlloc may wrap
// around the address space. We don't need to find the exact
// pages that VirtualAlloc would return - we just need to
// know whether VirtualAlloc could succeed.
ulong freeSpaceAfterGCHeap = MemFreeAfterAddress(null, size);
BCLDebug.Trace("MEMORYFAILPOINT", "MemoryFailPoint: Checked for free VA space. Found enough? {0} Asked for: {1} Found: {2}", (freeSpaceAfterGCHeap >= size), size, freeSpaceAfterGCHeap);
// We may set these without taking a lock - I don't believe
// this will hurt, as long as we never increment this number in
// the Dispose method. If we do an extra bit of checking every
// once in a while, but we avoid taking a lock, we may win.
LastKnownFreeAddressSpace = (long)freeSpaceAfterGCHeap;
LastTimeCheckingAddressSpace = Environment.TickCount;
if (freeSpaceAfterGCHeap < size && shouldThrow)
throw new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint_VAFrag);
return freeSpaceAfterGCHeap >= size;
}
// Returns the amount of consecutive free memory available in a block
// of pages. If we didn't have enough address space, we still return
// a positive value < size, to help potentially avoid the overhead of
// this check if we use a MemoryFailPoint with a smaller size next.
private static unsafe ulong MemFreeAfterAddress(void* address, ulong size)
{
if (size >= TopOfMemory)
return 0;
ulong largestFreeRegion = 0;
Win32Native.MEMORY_BASIC_INFORMATION memInfo = new Win32Native.MEMORY_BASIC_INFORMATION();
UIntPtr sizeOfMemInfo = (UIntPtr)Marshal.SizeOf(memInfo);
while (((ulong)address) + size < TopOfMemory)
{
UIntPtr r = Win32Native.VirtualQuery(address, ref memInfo, sizeOfMemInfo);
if (r == UIntPtr.Zero)
throw Win32Marshal.GetExceptionForLastWin32Error();
ulong regionSize = memInfo.RegionSize.ToUInt64();
if (memInfo.State == Win32Native.MEM_FREE)
{
if (regionSize >= size)
return regionSize;
else
largestFreeRegion = Math.Max(largestFreeRegion, regionSize);
}
address = (void*)((ulong)address + regionSize);
}
return largestFreeRegion;
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void GetMemorySettings(out ulong maxGCSegmentSize, out ulong topOfMemory);
~MemoryFailPoint()
{
Dispose(false);
}
// Applications must call Dispose, which conceptually "releases" the
// memory that was "reserved" by the MemoryFailPoint. This affects a
// global count of reserved memory in this version (helping to throttle
// future MemoryFailPoints) in this version. We may in the
// future create an allocation context and release it in the Dispose
// method. While the finalizer will eventually free this block of
// memory, apps will help their performance greatly by calling Dispose.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
// This is just bookkeeping to ensure multiple threads can really
// get enough memory, and this does not actually reserve memory
// within the GC heap.
if (_mustSubtractReservation)
{
RuntimeHelpers.PrepareConstrainedRegions();
SharedStatics.AddMemoryFailPointReservation(-((long)_reservedMemory));
_mustSubtractReservation = false;
}
/*
// Prototype performance
// Let's pretend that we returned at least some free memory to
// the GC heap. We don't know this is true - the objects could
// have a longer lifetime, and the memory could be elsewhere in the
// GC heap. Additionally, we subtracted off the segment size, not
// this size. That's ok - we don't mind if this slowly degrades
// and requires us to refresh the value a little bit sooner.
// But releasing the memory here should help us avoid probing for
// free address space excessively with large workItem sizes.
Interlocked.Add(ref LastKnownFreeAddressSpace, _reservedMemory);
*/
}
#if _DEBUG
[Serializable]
internal sealed class MemoryFailPointState
{
private ulong _segmentSize;
private int _allocationSizeInMB;
private bool _needPageFile;
private bool _needAddressSpace;
private bool _needContiguousVASpace;
private ulong _availPageFile;
private ulong _totalFreeAddressSpace;
private long _lastKnownFreeAddressSpace;
private ulong _reservedMem;
private String _stackTrace; // Where did we fail, for additional debugging.
internal MemoryFailPointState(int allocationSizeInMB, ulong segmentSize, bool needPageFile, bool needAddressSpace, bool needContiguousVASpace, ulong availPageFile, ulong totalFreeAddressSpace, long lastKnownFreeAddressSpace, ulong reservedMem)
{
_allocationSizeInMB = allocationSizeInMB;
_segmentSize = segmentSize;
_needPageFile = needPageFile;
_needAddressSpace = needAddressSpace;
_needContiguousVASpace = needContiguousVASpace;
_availPageFile = availPageFile;
_totalFreeAddressSpace = totalFreeAddressSpace;
_lastKnownFreeAddressSpace = lastKnownFreeAddressSpace;
_reservedMem = reservedMem;
try
{
_stackTrace = Environment.StackTrace;
}
catch (System.Security.SecurityException)
{
_stackTrace = "no permission";
}
catch (OutOfMemoryException)
{
_stackTrace = "out of memory";
}
}
public override String ToString()
{
return String.Format(System.Globalization.CultureInfo.InvariantCulture, "MemoryFailPoint detected insufficient memory to guarantee an operation could complete. Checked for {0} MB, for allocation size of {1} MB. Need page file? {2} Need Address Space? {3} Need Contiguous address space? {4} Avail page file: {5} MB Total free VA space: {6} MB Contiguous free address space (found): {7} MB Space reserved by process's MemoryFailPoints: {8} MB",
_segmentSize >> 20, _allocationSizeInMB, _needPageFile,
_needAddressSpace, _needContiguousVASpace,
_availPageFile >> 20, _totalFreeAddressSpace >> 20,
_lastKnownFreeAddressSpace >> 20, _reservedMem);
}
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
#if !uapaot
namespace System.Xml.Serialization
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Xml;
using System.Xml.Serialization.Configuration;
using System.Reflection;
using System.Reflection.Emit;
using System.IO;
using System.Security;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Xml.Extensions;
internal class CodeGenerator
{
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Method does validation only without any user input")]
internal static bool IsValidLanguageIndependentIdentifier(string ident) { return CSharpHelpers.IsValidLanguageIndependentIdentifier(ident); }
internal static BindingFlags InstancePublicBindingFlags = BindingFlags.Instance | BindingFlags.Public;
internal static BindingFlags InstanceBindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
internal static BindingFlags StaticBindingFlags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
internal static MethodAttributes PublicMethodAttributes = MethodAttributes.Public | MethodAttributes.HideBySig;
internal static MethodAttributes PublicOverrideMethodAttributes = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig;
internal static MethodAttributes ProtectedOverrideMethodAttributes = MethodAttributes.Family | MethodAttributes.Virtual | MethodAttributes.HideBySig;
internal static MethodAttributes PrivateMethodAttributes = MethodAttributes.Private | MethodAttributes.HideBySig;
internal static Type[] EmptyTypeArray = new Type[] { };
private TypeBuilder _typeBuilder;
private MethodBuilder _methodBuilder;
private ILGenerator _ilGen;
private Dictionary<string, ArgBuilder> _argList;
private LocalScope _currentScope;
// Stores a queue of free locals available in the context of the method, keyed by
// type and name of the local
private Dictionary<Tuple<Type, string>, Queue<LocalBuilder>> _freeLocals;
private Stack _blockStack;
private Label _methodEndLabel;
internal CodeGenerator(TypeBuilder typeBuilder)
{
System.Diagnostics.Debug.Assert(typeBuilder != null);
_typeBuilder = typeBuilder;
}
internal static bool IsNullableGenericType(Type type)
{
return type.Name == "Nullable`1";
}
internal static void AssertHasInterface(Type type, Type iType)
{
#if DEBUG
Debug.Assert(iType.IsInterface);
foreach (Type iFace in type.GetInterfaces())
{
if (iFace == iType)
return;
}
Debug.Assert(false);
#endif
}
internal void BeginMethod(Type returnType, string methodName, Type[] argTypes, string[] argNames, MethodAttributes methodAttributes)
{
_methodBuilder = _typeBuilder.DefineMethod(methodName, methodAttributes, returnType, argTypes);
_ilGen = _methodBuilder.GetILGenerator();
InitILGeneration(argTypes, argNames, (_methodBuilder.Attributes & MethodAttributes.Static) == MethodAttributes.Static);
}
internal void BeginMethod(Type returnType, MethodBuilderInfo methodBuilderInfo, Type[] argTypes, string[] argNames, MethodAttributes methodAttributes)
{
#if DEBUG
methodBuilderInfo.Validate(returnType, argTypes, methodAttributes);
#endif
_methodBuilder = methodBuilderInfo.MethodBuilder;
_ilGen = _methodBuilder.GetILGenerator();
InitILGeneration(argTypes, argNames, (_methodBuilder.Attributes & MethodAttributes.Static) == MethodAttributes.Static);
}
private void InitILGeneration(Type[] argTypes, string[] argNames, bool isStatic)
{
_methodEndLabel = _ilGen.DefineLabel();
this.retLabel = _ilGen.DefineLabel();
_blockStack = new Stack();
_whileStack = new Stack();
_currentScope = new LocalScope();
_freeLocals = new Dictionary<Tuple<Type, string>, Queue<LocalBuilder>>();
_argList = new Dictionary<string, ArgBuilder>();
// this ptr is arg 0 for non static, assuming ref type (not value type)
if (!isStatic)
_argList.Add("this", new ArgBuilder("this", 0, _typeBuilder.BaseType));
for (int i = 0; i < argTypes.Length; i++)
{
ArgBuilder arg = new ArgBuilder(argNames[i], _argList.Count, argTypes[i]);
_argList.Add(arg.Name, arg);
_methodBuilder.DefineParameter(arg.Index, ParameterAttributes.None, arg.Name);
}
}
internal MethodBuilder EndMethod()
{
MarkLabel(_methodEndLabel);
Ret();
MethodBuilder retVal = null;
retVal = _methodBuilder;
_methodBuilder = null;
_ilGen = null;
_freeLocals = null;
_blockStack = null;
_whileStack = null;
_argList = null;
_currentScope = null;
retLocal = null;
return retVal;
}
internal MethodBuilder MethodBuilder
{
get { return _methodBuilder; }
}
internal ArgBuilder GetArg(string name)
{
System.Diagnostics.Debug.Assert(_argList != null && _argList.ContainsKey(name));
return (ArgBuilder)_argList[name];
}
internal LocalBuilder GetLocal(string name)
{
System.Diagnostics.Debug.Assert(_currentScope != null && _currentScope.ContainsKey(name));
return _currentScope[name];
}
internal LocalBuilder retLocal;
internal Label retLabel;
internal LocalBuilder ReturnLocal
{
get
{
if (retLocal == null)
retLocal = DeclareLocal(_methodBuilder.ReturnType, "_ret");
return retLocal;
}
}
internal Label ReturnLabel
{
get { return retLabel; }
}
private Dictionary<Type, LocalBuilder> _tmpLocals = new Dictionary<Type, LocalBuilder>();
internal LocalBuilder GetTempLocal(Type type)
{
LocalBuilder localTmp;
if (!_tmpLocals.TryGetValue(type, out localTmp))
{
localTmp = DeclareLocal(type, "_tmp" + _tmpLocals.Count);
_tmpLocals.Add(type, localTmp);
}
return localTmp;
}
internal Type GetVariableType(object var)
{
if (var is ArgBuilder)
return ((ArgBuilder)var).ArgType;
else if (var is LocalBuilder)
return ((LocalBuilder)var).LocalType;
else
return var.GetType();
}
internal object GetVariable(string name)
{
object var;
if (TryGetVariable(name, out var))
return var;
System.Diagnostics.Debug.Assert(false);
return null;
}
internal bool TryGetVariable(string name, out object variable)
{
LocalBuilder loc;
if (_currentScope != null && _currentScope.TryGetValue(name, out loc))
{
variable = loc;
return true;
}
ArgBuilder arg;
if (_argList != null && _argList.TryGetValue(name, out arg))
{
variable = arg;
return true;
}
int val;
if (Int32.TryParse(name, out val))
{
variable = val;
return true;
}
variable = null;
return false;
}
internal void EnterScope()
{
LocalScope newScope = new LocalScope(_currentScope);
_currentScope = newScope;
}
internal void ExitScope()
{
Debug.Assert(_currentScope.parent != null);
_currentScope.AddToFreeLocals(_freeLocals);
_currentScope = _currentScope.parent;
}
private bool TryDequeueLocal(Type type, string name, out LocalBuilder local)
{
// This method can only be called between BeginMethod and EndMethod (i.e.
// while we are emitting code for a method
Debug.Assert(_freeLocals != null);
Queue<LocalBuilder> freeLocalQueue;
Tuple<Type, string> key = new Tuple<Type, string>(type, name);
if (_freeLocals.TryGetValue(key, out freeLocalQueue))
{
local = freeLocalQueue.Dequeue();
// If the queue is empty, remove this key from the dictionary
// of free locals
if (freeLocalQueue.Count == 0)
{
_freeLocals.Remove(key);
}
return true;
}
local = null;
return false;
}
internal LocalBuilder DeclareLocal(Type type, string name)
{
Debug.Assert(!_currentScope.ContainsKey(name));
LocalBuilder local;
if (!TryDequeueLocal(type, name, out local))
{
local = _ilGen.DeclareLocal(type, false);
}
_currentScope[name] = local;
return local;
}
internal LocalBuilder DeclareOrGetLocal(Type type, string name)
{
LocalBuilder local;
if (!_currentScope.TryGetValue(name, out local))
local = DeclareLocal(type, name);
else
Debug.Assert(local.LocalType == type);
return local;
}
internal object For(LocalBuilder local, object start, object end)
{
ForState forState = new ForState(local, DefineLabel(), DefineLabel(), end);
if (forState.Index != null)
{
Load(start);
Stloc(forState.Index);
Br(forState.TestLabel);
}
MarkLabel(forState.BeginLabel);
_blockStack.Push(forState);
return forState;
}
internal void EndFor()
{
object stackTop = _blockStack.Pop();
ForState forState = stackTop as ForState;
Debug.Assert(forState != null);
if (forState.Index != null)
{
Ldloc(forState.Index);
Ldc(1);
Add();
Stloc(forState.Index);
MarkLabel(forState.TestLabel);
Ldloc(forState.Index);
Load(forState.End);
Type varType = GetVariableType(forState.End);
if (varType.IsArray)
{
Ldlen();
}
else
{
#if DEBUG
CodeGenerator.AssertHasInterface(varType, typeof(ICollection));
#endif
MethodInfo ICollection_get_Count = typeof(ICollection).GetMethod(
"get_Count",
CodeGenerator.InstanceBindingFlags,
CodeGenerator.EmptyTypeArray
);
Call(ICollection_get_Count);
}
Blt(forState.BeginLabel);
}
else
Br(forState.BeginLabel);
}
internal void If()
{
InternalIf(false);
}
internal void IfNot()
{
InternalIf(true);
}
private static OpCode[] s_branchCodes = new OpCode[] {
OpCodes.Bge,
OpCodes.Bne_Un,
OpCodes.Bgt,
OpCodes.Ble,
OpCodes.Beq,
OpCodes.Blt,
};
private OpCode GetBranchCode(Cmp cmp)
{
return s_branchCodes[(int)cmp];
}
internal void If(Cmp cmpOp)
{
IfState ifState = new IfState();
ifState.EndIf = DefineLabel();
ifState.ElseBegin = DefineLabel();
_ilGen.Emit(GetBranchCode(cmpOp), ifState.ElseBegin);
_blockStack.Push(ifState);
}
internal void If(object value1, Cmp cmpOp, object value2)
{
Load(value1);
Load(value2);
If(cmpOp);
}
internal void Else()
{
IfState ifState = PopIfState();
Br(ifState.EndIf);
MarkLabel(ifState.ElseBegin);
ifState.ElseBegin = ifState.EndIf;
_blockStack.Push(ifState);
}
internal void EndIf()
{
IfState ifState = PopIfState();
if (!ifState.ElseBegin.Equals(ifState.EndIf))
MarkLabel(ifState.ElseBegin);
MarkLabel(ifState.EndIf);
}
private Stack _leaveLabels = new Stack();
internal void BeginExceptionBlock()
{
_leaveLabels.Push(DefineLabel());
_ilGen.BeginExceptionBlock();
}
internal void BeginCatchBlock(Type exception)
{
_ilGen.BeginCatchBlock(exception);
}
internal void EndExceptionBlock()
{
_ilGen.EndExceptionBlock();
_ilGen.MarkLabel((Label)_leaveLabels.Pop());
}
internal void Leave()
{
_ilGen.Emit(OpCodes.Leave, (Label)_leaveLabels.Peek());
}
internal void Call(MethodInfo methodInfo)
{
Debug.Assert(methodInfo != null);
if (methodInfo.IsVirtual && !methodInfo.DeclaringType.IsValueType)
_ilGen.Emit(OpCodes.Callvirt, methodInfo);
else
_ilGen.Emit(OpCodes.Call, methodInfo);
}
internal void Call(ConstructorInfo ctor)
{
Debug.Assert(ctor != null);
_ilGen.Emit(OpCodes.Call, ctor);
}
internal void New(ConstructorInfo constructorInfo)
{
Debug.Assert(constructorInfo != null);
_ilGen.Emit(OpCodes.Newobj, constructorInfo);
}
internal void InitObj(Type valueType)
{
_ilGen.Emit(OpCodes.Initobj, valueType);
}
internal void NewArray(Type elementType, object len)
{
Load(len);
_ilGen.Emit(OpCodes.Newarr, elementType);
}
internal void LoadArrayElement(object obj, object arrayIndex)
{
Type objType = GetVariableType(obj).GetElementType();
Load(obj);
Load(arrayIndex);
if (IsStruct(objType))
{
Ldelema(objType);
Ldobj(objType);
}
else
Ldelem(objType);
}
internal void StoreArrayElement(object obj, object arrayIndex, object value)
{
Type arrayType = GetVariableType(obj);
if (arrayType == typeof(Array))
{
Load(obj);
Call(typeof(Array).GetMethod("SetValue", new Type[] { typeof(object), typeof(int) }));
}
else
{
Type objType = arrayType.GetElementType();
Load(obj);
Load(arrayIndex);
if (IsStruct(objType))
Ldelema(objType);
Load(value);
ConvertValue(GetVariableType(value), objType);
if (IsStruct(objType))
Stobj(objType);
else
Stelem(objType);
}
}
private static bool IsStruct(Type objType)
{
return objType.IsValueType && !objType.IsPrimitive;
}
internal Type LoadMember(object obj, MemberInfo memberInfo)
{
if (GetVariableType(obj).IsValueType)
LoadAddress(obj);
else
Load(obj);
return LoadMember(memberInfo);
}
private static MethodInfo GetPropertyMethodFromBaseType(PropertyInfo propertyInfo, bool isGetter)
{
// we only invoke this when the propertyInfo does not have a GET or SET method on it
Type currentType = propertyInfo.DeclaringType.BaseType;
PropertyInfo currentProperty;
string propertyName = propertyInfo.Name;
MethodInfo result = null;
while (currentType != null)
{
currentProperty = currentType.GetProperty(propertyName);
if (currentProperty != null)
{
if (isGetter)
{
result = currentProperty.GetMethod;
}
else
{
result = currentProperty.SetMethod;
}
if (result != null)
{
// we found the GetMethod/SetMethod on the type closest to the current declaring type
break;
}
}
// keep looking at the base type like compiler does
currentType = currentType.BaseType;
}
return result;
}
internal Type LoadMember(MemberInfo memberInfo)
{
Type memberType = null;
if (memberInfo is FieldInfo)
{
FieldInfo fieldInfo = (FieldInfo)memberInfo;
memberType = fieldInfo.FieldType;
if (fieldInfo.IsStatic)
{
_ilGen.Emit(OpCodes.Ldsfld, fieldInfo);
}
else
{
_ilGen.Emit(OpCodes.Ldfld, fieldInfo);
}
}
else
{
System.Diagnostics.Debug.Assert(memberInfo is PropertyInfo);
PropertyInfo property = (PropertyInfo)memberInfo;
memberType = property.PropertyType;
if (property != null)
{
MethodInfo getMethod = property.GetMethod;
if (getMethod == null)
{
getMethod = GetPropertyMethodFromBaseType(property, true);
}
System.Diagnostics.Debug.Assert(getMethod != null);
Call(getMethod);
}
}
return memberType;
}
internal Type LoadMemberAddress(MemberInfo memberInfo)
{
Type memberType = null;
if (memberInfo is FieldInfo)
{
FieldInfo fieldInfo = (FieldInfo)memberInfo;
memberType = fieldInfo.FieldType;
if (fieldInfo.IsStatic)
{
_ilGen.Emit(OpCodes.Ldsflda, fieldInfo);
}
else
{
_ilGen.Emit(OpCodes.Ldflda, fieldInfo);
}
}
else
{
System.Diagnostics.Debug.Assert(memberInfo is PropertyInfo);
PropertyInfo property = (PropertyInfo)memberInfo;
memberType = property.PropertyType;
if (property != null)
{
MethodInfo getMethod = property.GetMethod;
if (getMethod == null)
{
getMethod = GetPropertyMethodFromBaseType(property, true);
}
System.Diagnostics.Debug.Assert(getMethod != null);
Call(getMethod);
LocalBuilder tmpLoc = GetTempLocal(memberType);
Stloc(tmpLoc);
Ldloca(tmpLoc);
}
}
return memberType;
}
internal void StoreMember(MemberInfo memberInfo)
{
if (memberInfo is FieldInfo)
{
FieldInfo fieldInfo = (FieldInfo)memberInfo;
if (fieldInfo.IsStatic)
{
_ilGen.Emit(OpCodes.Stsfld, fieldInfo);
}
else
{
_ilGen.Emit(OpCodes.Stfld, fieldInfo);
}
}
else
{
System.Diagnostics.Debug.Assert(memberInfo is PropertyInfo);
PropertyInfo property = (PropertyInfo)memberInfo;
if (property != null)
{
MethodInfo setMethod = property.SetMethod;
if (setMethod == null)
{
setMethod = GetPropertyMethodFromBaseType(property, false);
}
System.Diagnostics.Debug.Assert(setMethod != null);
Call(setMethod);
}
}
}
internal void Load(object obj)
{
if (obj == null)
_ilGen.Emit(OpCodes.Ldnull);
else if (obj is ArgBuilder)
Ldarg((ArgBuilder)obj);
else if (obj is LocalBuilder)
Ldloc((LocalBuilder)obj);
else
Ldc(obj);
}
internal void LoadAddress(object obj)
{
if (obj is ArgBuilder)
LdargAddress((ArgBuilder)obj);
else if (obj is LocalBuilder)
LdlocAddress((LocalBuilder)obj);
else
Load(obj);
}
internal void ConvertAddress(Type source, Type target)
{
InternalConvert(source, target, true);
}
internal void ConvertValue(Type source, Type target)
{
InternalConvert(source, target, false);
}
internal void Castclass(Type target)
{
_ilGen.Emit(OpCodes.Castclass, target);
}
internal void Box(Type type)
{
_ilGen.Emit(OpCodes.Box, type);
}
internal void Unbox(Type type)
{
_ilGen.Emit(OpCodes.Unbox, type);
}
private static OpCode[] s_ldindOpCodes = new OpCode[] {
OpCodes.Nop,//Empty = 0,
OpCodes.Nop,//Object = 1,
OpCodes.Nop,//DBNull = 2,
OpCodes.Ldind_I1,//Boolean = 3,
OpCodes.Ldind_I2,//Char = 4,
OpCodes.Ldind_I1,//SByte = 5,
OpCodes.Ldind_U1,//Byte = 6,
OpCodes.Ldind_I2,//Int16 = 7,
OpCodes.Ldind_U2,//UInt16 = 8,
OpCodes.Ldind_I4,//Int32 = 9,
OpCodes.Ldind_U4,//UInt32 = 10,
OpCodes.Ldind_I8,//Int64 = 11,
OpCodes.Ldind_I8,//UInt64 = 12,
OpCodes.Ldind_R4,//Single = 13,
OpCodes.Ldind_R8,//Double = 14,
OpCodes.Nop,//Decimal = 15,
OpCodes.Nop,//DateTime = 16,
OpCodes.Nop,//17
OpCodes.Ldind_Ref,//String = 18,
};
private OpCode GetLdindOpCode(TypeCode typeCode)
{
return s_ldindOpCodes[(int)typeCode];
}
internal void Ldobj(Type type)
{
OpCode opCode = GetLdindOpCode(type.GetTypeCode());
if (!opCode.Equals(OpCodes.Nop))
{
_ilGen.Emit(opCode);
}
else
{
_ilGen.Emit(OpCodes.Ldobj, type);
}
}
internal void Stobj(Type type)
{
_ilGen.Emit(OpCodes.Stobj, type);
}
internal void Ceq()
{
_ilGen.Emit(OpCodes.Ceq);
}
internal void Clt()
{
_ilGen.Emit(OpCodes.Clt);
}
internal void Cne()
{
Ceq();
Ldc(0);
Ceq();
}
internal void Ble(Label label)
{
_ilGen.Emit(OpCodes.Ble, label);
}
internal void Throw()
{
_ilGen.Emit(OpCodes.Throw);
}
internal void Ldtoken(Type t)
{
_ilGen.Emit(OpCodes.Ldtoken, t);
}
internal void Ldc(object o)
{
Type valueType = o.GetType();
if (o is Type)
{
Ldtoken((Type)o);
Call(typeof(Type).GetMethod("GetTypeFromHandle", BindingFlags.Static | BindingFlags.Public, new Type[] { typeof(RuntimeTypeHandle) }));
}
else if (valueType.IsEnum)
{
Ldc(Convert.ChangeType(o, Enum.GetUnderlyingType(valueType), null));
}
else
{
switch (valueType.GetTypeCode())
{
case TypeCode.Boolean:
Ldc((bool)o);
break;
case TypeCode.Char:
Debug.Assert(false, "Char is not a valid schema primitive and should be treated as int in DataContract");
throw new NotSupportedException(SR.XmlInvalidCharSchemaPrimitive);
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
Ldc(Convert.ToInt32(o, CultureInfo.InvariantCulture));
break;
case TypeCode.Int32:
Ldc((int)o);
break;
case TypeCode.UInt32:
Ldc((int)(uint)o);
break;
case TypeCode.UInt64:
Ldc((long)(ulong)o);
break;
case TypeCode.Int64:
Ldc((long)o);
break;
case TypeCode.Single:
Ldc((float)o);
break;
case TypeCode.Double:
Ldc((double)o);
break;
case TypeCode.String:
Ldstr((string)o);
break;
case TypeCode.Decimal:
ConstructorInfo Decimal_ctor = typeof(Decimal).GetConstructor(
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(Int32), typeof(Int32), typeof(Int32), typeof(Boolean), typeof(Byte) }
);
int[] bits = Decimal.GetBits((decimal)o);
Ldc(bits[0]); // digit
Ldc(bits[1]); // digit
Ldc(bits[2]); // digit
Ldc((bits[3] & 0x80000000) == 0x80000000); // sign
Ldc((Byte)((bits[3] >> 16) & 0xFF)); // decimal location
New(Decimal_ctor);
break;
case TypeCode.DateTime:
ConstructorInfo DateTime_ctor = typeof(DateTime).GetConstructor(
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(Int64) }
);
Ldc(((DateTime)o).Ticks); // ticks
New(DateTime_ctor);
break;
case TypeCode.Object:
case TypeCode.Empty:
case TypeCode.DBNull:
default:
Debug.Assert(false, "UnknownConstantType");
throw new NotSupportedException(SR.Format(SR.UnknownConstantType, valueType.AssemblyQualifiedName));
}
}
}
internal void Ldc(bool boolVar)
{
if (boolVar)
{
_ilGen.Emit(OpCodes.Ldc_I4_1);
}
else
{
_ilGen.Emit(OpCodes.Ldc_I4_0);
}
}
internal void Ldc(int intVar)
{
switch (intVar)
{
case -1:
_ilGen.Emit(OpCodes.Ldc_I4_M1);
break;
case 0:
_ilGen.Emit(OpCodes.Ldc_I4_0);
break;
case 1:
_ilGen.Emit(OpCodes.Ldc_I4_1);
break;
case 2:
_ilGen.Emit(OpCodes.Ldc_I4_2);
break;
case 3:
_ilGen.Emit(OpCodes.Ldc_I4_3);
break;
case 4:
_ilGen.Emit(OpCodes.Ldc_I4_4);
break;
case 5:
_ilGen.Emit(OpCodes.Ldc_I4_5);
break;
case 6:
_ilGen.Emit(OpCodes.Ldc_I4_6);
break;
case 7:
_ilGen.Emit(OpCodes.Ldc_I4_7);
break;
case 8:
_ilGen.Emit(OpCodes.Ldc_I4_8);
break;
default:
_ilGen.Emit(OpCodes.Ldc_I4, intVar);
break;
}
}
internal void Ldc(long l)
{
_ilGen.Emit(OpCodes.Ldc_I8, l);
}
internal void Ldc(float f)
{
_ilGen.Emit(OpCodes.Ldc_R4, f);
}
internal void Ldc(double d)
{
_ilGen.Emit(OpCodes.Ldc_R8, d);
}
internal void Ldstr(string strVar)
{
if (strVar == null)
_ilGen.Emit(OpCodes.Ldnull);
else
_ilGen.Emit(OpCodes.Ldstr, strVar);
}
internal void LdlocAddress(LocalBuilder localBuilder)
{
if (localBuilder.LocalType.IsValueType)
Ldloca(localBuilder);
else
Ldloc(localBuilder);
}
internal void Ldloc(LocalBuilder localBuilder)
{
_ilGen.Emit(OpCodes.Ldloc, localBuilder);
}
internal void Ldloc(string name)
{
Debug.Assert(_currentScope.ContainsKey(name));
LocalBuilder local = _currentScope[name];
Ldloc(local);
}
internal void Stloc(Type type, string name)
{
LocalBuilder local = null;
if (!_currentScope.TryGetValue(name, out local))
{
local = DeclareLocal(type, name);
}
Debug.Assert(local.LocalType == type);
Stloc(local);
}
internal void Stloc(LocalBuilder local)
{
_ilGen.Emit(OpCodes.Stloc, local);
}
internal void Ldloc(Type type, string name)
{
Debug.Assert(_currentScope.ContainsKey(name));
LocalBuilder local = _currentScope[name];
Debug.Assert(local.LocalType == type);
Ldloc(local);
}
internal void Ldloca(LocalBuilder localBuilder)
{
_ilGen.Emit(OpCodes.Ldloca, localBuilder);
}
internal void LdargAddress(ArgBuilder argBuilder)
{
if (argBuilder.ArgType.IsValueType)
Ldarga(argBuilder);
else
Ldarg(argBuilder);
}
internal void Ldarg(string arg)
{
Ldarg(GetArg(arg));
}
internal void Ldarg(ArgBuilder arg)
{
Ldarg(arg.Index);
}
internal void Ldarg(int slot)
{
switch (slot)
{
case 0:
_ilGen.Emit(OpCodes.Ldarg_0);
break;
case 1:
_ilGen.Emit(OpCodes.Ldarg_1);
break;
case 2:
_ilGen.Emit(OpCodes.Ldarg_2);
break;
case 3:
_ilGen.Emit(OpCodes.Ldarg_3);
break;
default:
if (slot <= 255)
_ilGen.Emit(OpCodes.Ldarg_S, slot);
else
_ilGen.Emit(OpCodes.Ldarg, slot);
break;
}
}
internal void Ldarga(ArgBuilder argBuilder)
{
Ldarga(argBuilder.Index);
}
internal void Ldarga(int slot)
{
if (slot <= 255)
_ilGen.Emit(OpCodes.Ldarga_S, slot);
else
_ilGen.Emit(OpCodes.Ldarga, slot);
}
internal void Ldlen()
{
_ilGen.Emit(OpCodes.Ldlen);
_ilGen.Emit(OpCodes.Conv_I4);
}
private static OpCode[] s_ldelemOpCodes = new OpCode[] {
OpCodes.Nop,//Empty = 0,
OpCodes.Ldelem_Ref,//Object = 1,
OpCodes.Ldelem_Ref,//DBNull = 2,
OpCodes.Ldelem_I1,//Boolean = 3,
OpCodes.Ldelem_I2,//Char = 4,
OpCodes.Ldelem_I1,//SByte = 5,
OpCodes.Ldelem_U1,//Byte = 6,
OpCodes.Ldelem_I2,//Int16 = 7,
OpCodes.Ldelem_U2,//UInt16 = 8,
OpCodes.Ldelem_I4,//Int32 = 9,
OpCodes.Ldelem_U4,//UInt32 = 10,
OpCodes.Ldelem_I8,//Int64 = 11,
OpCodes.Ldelem_I8,//UInt64 = 12,
OpCodes.Ldelem_R4,//Single = 13,
OpCodes.Ldelem_R8,//Double = 14,
OpCodes.Nop,//Decimal = 15,
OpCodes.Nop,//DateTime = 16,
OpCodes.Nop,//17
OpCodes.Ldelem_Ref,//String = 18,
};
private OpCode GetLdelemOpCode(TypeCode typeCode)
{
return s_ldelemOpCodes[(int)typeCode];
}
internal void Ldelem(Type arrayElementType)
{
if (arrayElementType.IsEnum)
{
Ldelem(Enum.GetUnderlyingType(arrayElementType));
}
else
{
OpCode opCode = GetLdelemOpCode(arrayElementType.GetTypeCode());
Debug.Assert(!opCode.Equals(OpCodes.Nop));
if (opCode.Equals(OpCodes.Nop))
throw new InvalidOperationException(SR.Format(SR.ArrayTypeIsNotSupported, arrayElementType.AssemblyQualifiedName));
_ilGen.Emit(opCode);
}
}
internal void Ldelema(Type arrayElementType)
{
OpCode opCode = OpCodes.Ldelema;
_ilGen.Emit(opCode, arrayElementType);
}
private static OpCode[] s_stelemOpCodes = new OpCode[] {
OpCodes.Nop,//Empty = 0,
OpCodes.Stelem_Ref,//Object = 1,
OpCodes.Stelem_Ref,//DBNull = 2,
OpCodes.Stelem_I1,//Boolean = 3,
OpCodes.Stelem_I2,//Char = 4,
OpCodes.Stelem_I1,//SByte = 5,
OpCodes.Stelem_I1,//Byte = 6,
OpCodes.Stelem_I2,//Int16 = 7,
OpCodes.Stelem_I2,//UInt16 = 8,
OpCodes.Stelem_I4,//Int32 = 9,
OpCodes.Stelem_I4,//UInt32 = 10,
OpCodes.Stelem_I8,//Int64 = 11,
OpCodes.Stelem_I8,//UInt64 = 12,
OpCodes.Stelem_R4,//Single = 13,
OpCodes.Stelem_R8,//Double = 14,
OpCodes.Nop,//Decimal = 15,
OpCodes.Nop,//DateTime = 16,
OpCodes.Nop,//17
OpCodes.Stelem_Ref,//String = 18,
};
private OpCode GetStelemOpCode(TypeCode typeCode)
{
return s_stelemOpCodes[(int)typeCode];
}
internal void Stelem(Type arrayElementType)
{
if (arrayElementType.IsEnum)
Stelem(Enum.GetUnderlyingType(arrayElementType));
else
{
OpCode opCode = GetStelemOpCode(arrayElementType.GetTypeCode());
if (opCode.Equals(OpCodes.Nop))
throw new InvalidOperationException(SR.Format(SR.ArrayTypeIsNotSupported, arrayElementType.AssemblyQualifiedName));
_ilGen.Emit(opCode);
}
}
internal Label DefineLabel()
{
return _ilGen.DefineLabel();
}
internal void MarkLabel(Label label)
{
_ilGen.MarkLabel(label);
}
internal void Nop()
{
_ilGen.Emit(OpCodes.Nop);
}
internal void Add()
{
_ilGen.Emit(OpCodes.Add);
}
internal void Ret()
{
_ilGen.Emit(OpCodes.Ret);
}
internal void Br(Label label)
{
_ilGen.Emit(OpCodes.Br, label);
}
internal void Br_S(Label label)
{
_ilGen.Emit(OpCodes.Br_S, label);
}
internal void Blt(Label label)
{
_ilGen.Emit(OpCodes.Blt, label);
}
internal void Brfalse(Label label)
{
_ilGen.Emit(OpCodes.Brfalse, label);
}
internal void Brtrue(Label label)
{
_ilGen.Emit(OpCodes.Brtrue, label);
}
internal void Pop()
{
_ilGen.Emit(OpCodes.Pop);
}
internal void Dup()
{
_ilGen.Emit(OpCodes.Dup);
}
private void InternalIf(bool negate)
{
IfState ifState = new IfState();
ifState.EndIf = DefineLabel();
ifState.ElseBegin = DefineLabel();
if (negate)
Brtrue(ifState.ElseBegin);
else
Brfalse(ifState.ElseBegin);
_blockStack.Push(ifState);
}
private static OpCode[] s_convOpCodes = new OpCode[] {
OpCodes.Nop,//Empty = 0,
OpCodes.Nop,//Object = 1,
OpCodes.Nop,//DBNull = 2,
OpCodes.Conv_I1,//Boolean = 3,
OpCodes.Conv_I2,//Char = 4,
OpCodes.Conv_I1,//SByte = 5,
OpCodes.Conv_U1,//Byte = 6,
OpCodes.Conv_I2,//Int16 = 7,
OpCodes.Conv_U2,//UInt16 = 8,
OpCodes.Conv_I4,//Int32 = 9,
OpCodes.Conv_U4,//UInt32 = 10,
OpCodes.Conv_I8,//Int64 = 11,
OpCodes.Conv_U8,//UInt64 = 12,
OpCodes.Conv_R4,//Single = 13,
OpCodes.Conv_R8,//Double = 14,
OpCodes.Nop,//Decimal = 15,
OpCodes.Nop,//DateTime = 16,
OpCodes.Nop,//17
OpCodes.Nop,//String = 18,
};
private OpCode GetConvOpCode(TypeCode typeCode)
{
return s_convOpCodes[(int)typeCode];
}
private void InternalConvert(Type source, Type target, bool isAddress)
{
if (target == source)
return;
if (target.IsValueType)
{
if (source.IsValueType)
{
OpCode opCode = GetConvOpCode(target.GetTypeCode());
if (opCode.Equals(OpCodes.Nop))
{
throw new CodeGeneratorConversionException(source, target, isAddress, "NoConversionPossibleTo");
}
else
{
_ilGen.Emit(opCode);
}
}
else if (source.IsAssignableFrom(target))
{
Unbox(target);
if (!isAddress)
Ldobj(target);
}
else
{
throw new CodeGeneratorConversionException(source, target, isAddress, "IsNotAssignableFrom");
}
}
else if (target.IsAssignableFrom(source))
{
if (source.IsValueType)
{
if (isAddress)
Ldobj(source);
Box(source);
}
}
else if (source.IsAssignableFrom(target))
{
Castclass(target);
}
else if (target.IsInterface || source.IsInterface)
{
Castclass(target);
}
else
{
throw new CodeGeneratorConversionException(source, target, isAddress, "IsNotAssignableFrom");
}
}
private IfState PopIfState()
{
object stackTop = _blockStack.Pop();
IfState ifState = stackTop as IfState;
Debug.Assert(ifState != null);
return ifState;
}
internal static AssemblyBuilder CreateAssemblyBuilder(string name)
{
AssemblyName assemblyName = new AssemblyName();
assemblyName.Name = name;
assemblyName.Version = new Version(1, 0, 0, 0);
return AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
}
internal static ModuleBuilder CreateModuleBuilder(AssemblyBuilder assemblyBuilder, string name)
{
return assemblyBuilder.DefineDynamicModule(name);
}
internal static TypeBuilder CreateTypeBuilder(ModuleBuilder moduleBuilder, string name, TypeAttributes attributes, Type parent, Type[] interfaces)
{
// parent is nullable if no base class
return moduleBuilder.DefineType(TempAssembly.GeneratedAssemblyNamespace + "." + name,
attributes, parent, interfaces);
}
private int _initElseIfStack = -1;
private IfState _elseIfState;
internal void InitElseIf()
{
Debug.Assert(_initElseIfStack == -1);
_elseIfState = (IfState)_blockStack.Pop();
_initElseIfStack = _blockStack.Count;
Br(_elseIfState.EndIf);
MarkLabel(_elseIfState.ElseBegin);
}
private int _initIfStack = -1;
internal void InitIf()
{
Debug.Assert(_initIfStack == -1);
_initIfStack = _blockStack.Count;
}
internal void AndIf(Cmp cmpOp)
{
if (_initIfStack == _blockStack.Count)
{
_initIfStack = -1;
If(cmpOp);
return;
}
if (_initElseIfStack == _blockStack.Count)
{
_initElseIfStack = -1;
_elseIfState.ElseBegin = DefineLabel();
_ilGen.Emit(GetBranchCode(cmpOp), _elseIfState.ElseBegin);
_blockStack.Push(_elseIfState);
return;
}
Debug.Assert(_initIfStack == -1 && _initElseIfStack == -1);
IfState ifState = (IfState)_blockStack.Peek();
_ilGen.Emit(GetBranchCode(cmpOp), ifState.ElseBegin);
}
internal void AndIf()
{
if (_initIfStack == _blockStack.Count)
{
_initIfStack = -1;
If();
return;
}
if (_initElseIfStack == _blockStack.Count)
{
_initElseIfStack = -1;
_elseIfState.ElseBegin = DefineLabel();
Brfalse(_elseIfState.ElseBegin);
_blockStack.Push(_elseIfState);
return;
}
Debug.Assert(_initIfStack == -1 && _initElseIfStack == -1);
IfState ifState = (IfState)_blockStack.Peek();
Brfalse(ifState.ElseBegin);
}
internal void IsInst(Type type)
{
_ilGen.Emit(OpCodes.Isinst, type);
}
internal void Beq(Label label)
{
_ilGen.Emit(OpCodes.Beq, label);
}
internal void Bne(Label label)
{
_ilGen.Emit(OpCodes.Bne_Un, label);
}
internal void GotoMethodEnd()
{
//limit to only short forward (127 CIL instruction)
//Br_S(this.methodEndLabel);
Br(_methodEndLabel);
}
internal class WhileState
{
public Label StartLabel;
public Label CondLabel;
public Label EndLabel;
public WhileState(CodeGenerator ilg)
{
StartLabel = ilg.DefineLabel();
CondLabel = ilg.DefineLabel();
EndLabel = ilg.DefineLabel();
}
}
// Usage:
// WhileBegin()
// WhileBreak()
// WhileContinue()
// WhileBeginCondition()
// (bool on stack)
// WhileEndCondition()
// WhileEnd()
private Stack _whileStack;
internal void WhileBegin()
{
WhileState whileState = new WhileState(this);
Br(whileState.CondLabel);
MarkLabel(whileState.StartLabel);
_whileStack.Push(whileState);
}
internal void WhileEnd()
{
WhileState whileState = (WhileState)_whileStack.Pop();
MarkLabel(whileState.EndLabel);
}
internal void WhileBreak()
{
WhileState whileState = (WhileState)_whileStack.Peek();
Br(whileState.EndLabel);
}
internal void WhileContinue()
{
WhileState whileState = (WhileState)_whileStack.Peek();
Br(whileState.CondLabel);
}
internal void WhileBeginCondition()
{
WhileState whileState = (WhileState)_whileStack.Peek();
// If there are two MarkLabel ILs consecutively, Labels will converge to one label.
// This could cause the code to look different. We insert Nop here specifically
// that the While label stands out.
Nop();
MarkLabel(whileState.CondLabel);
}
internal void WhileEndCondition()
{
WhileState whileState = (WhileState)_whileStack.Peek();
Brtrue(whileState.StartLabel);
}
}
internal class ArgBuilder
{
internal string Name;
internal int Index;
internal Type ArgType;
internal ArgBuilder(string name, int index, Type argType)
{
this.Name = name;
this.Index = index;
this.ArgType = argType;
}
}
internal class ForState
{
private LocalBuilder _indexVar;
private Label _beginLabel;
private Label _testLabel;
private object _end;
internal ForState(LocalBuilder indexVar, Label beginLabel, Label testLabel, object end)
{
_indexVar = indexVar;
_beginLabel = beginLabel;
_testLabel = testLabel;
_end = end;
}
internal LocalBuilder Index
{
get
{
return _indexVar;
}
}
internal Label BeginLabel
{
get
{
return _beginLabel;
}
}
internal Label TestLabel
{
get
{
return _testLabel;
}
}
internal object End
{
get
{
return _end;
}
}
}
internal enum Cmp : int
{
LessThan = 0,
EqualTo,
LessThanOrEqualTo,
GreaterThan,
NotEqualTo,
GreaterThanOrEqualTo
}
internal class IfState
{
private Label _elseBegin;
private Label _endIf;
internal Label EndIf
{
get
{
return _endIf;
}
set
{
_endIf = value;
}
}
internal Label ElseBegin
{
get
{
return _elseBegin;
}
set
{
_elseBegin = value;
}
}
}
internal class LocalScope
{
public readonly LocalScope parent;
private readonly Dictionary<string, LocalBuilder> _locals;
// Root scope
public LocalScope()
{
_locals = new Dictionary<string, LocalBuilder>();
}
public LocalScope(LocalScope parent) : this()
{
this.parent = parent;
}
public void Add(string key, LocalBuilder value)
{
_locals.Add(key, value);
}
public bool ContainsKey(string key)
{
return _locals.ContainsKey(key) || (parent != null && parent.ContainsKey(key));
}
public bool TryGetValue(string key, out LocalBuilder value)
{
if (_locals.TryGetValue(key, out value))
{
return true;
}
else if (parent != null)
{
return parent.TryGetValue(key, out value);
}
else
{
value = null;
return false;
}
}
public LocalBuilder this[string key]
{
get
{
LocalBuilder value;
TryGetValue(key, out value);
return value;
}
set
{
_locals[key] = value;
}
}
public void AddToFreeLocals(Dictionary<Tuple<Type, string>, Queue<LocalBuilder>> freeLocals)
{
foreach (var item in _locals)
{
Tuple<Type, string> key = new Tuple<Type, string>(item.Value.LocalType, item.Key);
Queue<LocalBuilder> freeLocalQueue;
if (freeLocals.TryGetValue(key, out freeLocalQueue))
{
// Add to end of the queue so that it will be re-used in
// FIFO manner
freeLocalQueue.Enqueue(item.Value);
}
else
{
freeLocalQueue = new Queue<LocalBuilder>();
freeLocalQueue.Enqueue(item.Value);
freeLocals.Add(key, freeLocalQueue);
}
}
}
}
internal class MethodBuilderInfo
{
public readonly MethodBuilder MethodBuilder;
public readonly Type[] ParameterTypes;
public MethodBuilderInfo(MethodBuilder methodBuilder, Type[] parameterTypes)
{
this.MethodBuilder = methodBuilder;
this.ParameterTypes = parameterTypes;
}
public void Validate(Type returnType, Type[] parameterTypes, MethodAttributes attributes)
{
#if DEBUG
Debug.Assert(this.MethodBuilder.ReturnType == returnType);
Debug.Assert(this.MethodBuilder.Attributes == attributes);
Debug.Assert(this.ParameterTypes.Length == parameterTypes.Length);
for (int i = 0; i < parameterTypes.Length; ++i) {
Debug.Assert(this.ParameterTypes[i] == parameterTypes[i]);
}
#endif
}
}
internal class CodeGeneratorConversionException : Exception
{
private Type _sourceType;
private Type _targetType;
private bool _isAddress;
private string _reason;
public CodeGeneratorConversionException(Type sourceType, Type targetType, bool isAddress, string reason)
: base()
{
_sourceType = sourceType;
_targetType = targetType;
_isAddress = isAddress;
_reason = reason;
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: This class will encapsulate a long and provide an
** Object representation of it.
**
**
===========================================================*/
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
namespace System
{
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
public struct Int64 : IComparable, IFormattable, IComparable<Int64>, IEquatable<Int64>, IConvertible
{
internal long m_value;
public const long MaxValue = 0x7fffffffffffffffL;
public const long MinValue = unchecked((long)0x8000000000000000L);
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type Int64, this method throws an ArgumentException.
//
public int CompareTo(Object value)
{
if (value == null)
{
return 1;
}
if (value is Int64)
{
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
long i = (long)value;
if (m_value < i) return -1;
if (m_value > i) return 1;
return 0;
}
throw new ArgumentException(SR.Arg_MustBeInt64);
}
public int CompareTo(Int64 value)
{
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
if (m_value < value) return -1;
if (m_value > value) return 1;
return 0;
}
public override bool Equals(Object obj)
{
if (!(obj is Int64))
{
return false;
}
return m_value == ((Int64)obj).m_value;
}
[NonVersionable]
public bool Equals(Int64 obj)
{
return m_value == obj;
}
// The value of the lower 32 bits XORed with the uppper 32 bits.
public override int GetHashCode()
{
return (unchecked((int)((long)m_value)) ^ (int)(m_value >> 32));
}
public override String ToString()
{
Contract.Ensures(Contract.Result<String>() != null);
return FormatProvider.FormatInt64(m_value, null, null);
}
public String ToString(IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return FormatProvider.FormatInt64(m_value, null, provider);
}
public String ToString(String format)
{
Contract.Ensures(Contract.Result<String>() != null);
return FormatProvider.FormatInt64(m_value, format, null);
}
public String ToString(String format, IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return FormatProvider.FormatInt64(m_value, format, provider);
}
public static long Parse(String s)
{
return FormatProvider.ParseInt64(s, NumberStyles.Integer, null);
}
public static long Parse(String s, NumberStyles style)
{
UInt32.ValidateParseStyleInteger(style);
return FormatProvider.ParseInt64(s, style, null);
}
public static long Parse(String s, IFormatProvider provider)
{
return FormatProvider.ParseInt64(s, NumberStyles.Integer, provider);
}
// Parses a long from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
//
public static long Parse(String s, NumberStyles style, IFormatProvider provider)
{
UInt32.ValidateParseStyleInteger(style);
return FormatProvider.ParseInt64(s, style, provider);
}
public static Boolean TryParse(String s, out Int64 result)
{
return FormatProvider.TryParseInt64(s, NumberStyles.Integer, null, out result);
}
public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out Int64 result)
{
UInt32.ValidateParseStyleInteger(style);
return FormatProvider.TryParseInt64(s, style, provider, out result);
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.Int64;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(m_value);
}
char IConvertible.ToChar(IFormatProvider provider)
{
return Convert.ToChar(m_value);
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(m_value);
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(m_value);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(m_value);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(m_value);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(m_value);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(m_value);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return m_value;
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(m_value);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(m_value);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(m_value);
}
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(m_value);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Int64", "DateTime"));
}
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Localization;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.DataAnnotations
{
public class CompareAttributeAdapterTest
{
[Fact]
[ReplaceCulture]
public void ClientRulesWithCompareAttribute_ErrorMessageUsesDisplayName_WithoutLocalizer()
{
// Arrange
var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
var metadata = metadataProvider.GetMetadataForProperty(typeof(PropertyDisplayNameModel), "MyProperty");
var attribute = new CompareAttribute("OtherProperty");
var adapter = new CompareAttributeAdapter(attribute, stringLocalizer: null);
var expectedMessage = "'MyPropertyDisplayName' and 'OtherPropertyDisplayName' do not match.";
var actionContext = new ActionContext();
var context = new ClientModelValidationContext(
actionContext,
metadata,
metadataProvider,
new Dictionary<string, string>());
// Act
adapter.AddValidation(context);
// Assert
Assert.Collection(
context.Attributes,
kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("true", kvp.Value); },
kvp => { Assert.Equal("data-val-equalto", kvp.Key); Assert.Equal(expectedMessage, kvp.Value); },
kvp =>
{
Assert.Equal("data-val-equalto-other", kvp.Key);
Assert.Equal("*.OtherProperty", kvp.Value);
});
}
[Fact]
[ReplaceCulture]
public void ClientRulesWithCompareAttribute_ErrorMessageUsesDisplayName()
{
// Arrange
var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
var metadata = metadataProvider.GetMetadataForProperty(typeof(PropertyDisplayNameModel), "MyProperty");
var attribute = new CompareAttribute("OtherProperty");
attribute.ErrorMessage = "CompareAttributeErrorMessage";
var stringLocalizer = new Mock<IStringLocalizer>();
var expectedProperties = new object[] { "MyPropertyDisplayName", "OtherPropertyDisplayName" };
var expectedMessage = "'MyPropertyDisplayName' and 'OtherPropertyDisplayName' do not match.";
stringLocalizer.Setup(s => s[attribute.ErrorMessage, expectedProperties])
.Returns(new LocalizedString(attribute.ErrorMessage, expectedMessage));
var adapter = new CompareAttributeAdapter(attribute, stringLocalizer: stringLocalizer.Object);
var actionContext = new ActionContext();
var context = new ClientModelValidationContext(
actionContext,
metadata,
metadataProvider,
new Dictionary<string, string>());
// Act
adapter.AddValidation(context);
// Assert
Assert.Collection(
context.Attributes,
kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("true", kvp.Value); },
kvp => { Assert.Equal("data-val-equalto", kvp.Key); Assert.Equal(expectedMessage, kvp.Value); },
kvp =>
{
Assert.Equal("data-val-equalto-other", kvp.Key);
Assert.Equal("*.OtherProperty", kvp.Value);
});
}
[Fact]
[ReplaceCulture]
public void ClientRulesWithCompareAttribute_ErrorMessageUsesPropertyName()
{
// Arrange
var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
var metadata = metadataProvider.GetMetadataForProperty(typeof(PropertyNameModel), "MyProperty");
var attribute = new CompareAttribute("OtherProperty");
var adapter = new CompareAttributeAdapter(attribute, stringLocalizer: null);
var expectedMessage = "'MyProperty' and 'OtherProperty' do not match.";
var actionContext = new ActionContext();
var context = new ClientModelValidationContext(
actionContext,
metadata,
metadataProvider,
new Dictionary<string, string>());
// Act
adapter.AddValidation(context);
// Assert
Assert.Collection(
context.Attributes,
kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("true", kvp.Value); },
kvp => { Assert.Equal("data-val-equalto", kvp.Key); Assert.Equal(expectedMessage, kvp.Value); },
kvp =>
{
Assert.Equal("data-val-equalto-other", kvp.Key);
Assert.Equal("*.OtherProperty", kvp.Value);
});
}
[Fact]
public void ClientRulesWithCompareAttribute_ErrorMessageUsesOverride()
{
// Arrange
var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
var metadata = metadataProvider.GetMetadataForProperty(typeof(PropertyNameModel), "MyProperty");
var attribute = new CompareAttribute("OtherProperty")
{
ErrorMessage = "Hello '{0}', goodbye '{1}'."
};
var adapter = new CompareAttributeAdapter(attribute, stringLocalizer: null);
var expectedMessage = "Hello 'MyProperty', goodbye 'OtherProperty'.";
var actionContext = new ActionContext();
var context = new ClientModelValidationContext(
actionContext,
metadata,
metadataProvider,
new Dictionary<string, string>());
// Act
adapter.AddValidation(context);
// Assert
Assert.Collection(
context.Attributes,
kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("true", kvp.Value); },
kvp => { Assert.Equal("data-val-equalto", kvp.Key); Assert.Equal(expectedMessage, kvp.Value); },
kvp =>
{
Assert.Equal("data-val-equalto-other", kvp.Key);
Assert.Equal("*.OtherProperty", kvp.Value);
});
}
[ConditionalFact]
// ValidationAttribute in Mono does not read non-public resx properties.
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public void ClientRulesWithCompareAttribute_ErrorMessageUsesResourceOverride()
{
// Arrange
var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
var metadata = metadataProvider.GetMetadataForProperty(typeof(PropertyNameModel), "MyProperty");
var attribute = new CompareAttribute("OtherProperty")
{
ErrorMessageResourceName = "CompareAttributeTestResource",
ErrorMessageResourceType = typeof(DataAnnotations.Test.Resources),
};
var adapter = new CompareAttributeAdapter(attribute, stringLocalizer: null);
var expectedMessage = "Comparing MyProperty to OtherProperty.";
var actionContext = new ActionContext();
var context = new ClientModelValidationContext(
actionContext,
metadata,
metadataProvider,
new Dictionary<string, string>());
// Act
adapter.AddValidation(context);
// Assert
Assert.Collection(
context.Attributes,
kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("true", kvp.Value); },
kvp => { Assert.Equal("data-val-equalto", kvp.Key); Assert.Equal(expectedMessage, kvp.Value); },
kvp =>
{
Assert.Equal("data-val-equalto-other", kvp.Key);
Assert.Equal("*.OtherProperty", kvp.Value);
});
}
[Fact]
[ReplaceCulture]
public void AddValidation_DoesNotTrounceExistingAttributes()
{
// Arrange
var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
var metadata = metadataProvider.GetMetadataForProperty(typeof(PropertyNameModel), "MyProperty");
var attribute = new CompareAttribute("OtherProperty");
var adapter = new CompareAttributeAdapter(attribute, stringLocalizer: null);
var actionContext = new ActionContext();
var context = new ClientModelValidationContext(
actionContext,
metadata,
metadataProvider,
new Dictionary<string, string>());
context.Attributes.Add("data-val", "original");
context.Attributes.Add("data-val-equalto", "original");
context.Attributes.Add("data-val-equalto-other", "original");
// Act
adapter.AddValidation(context);
// Assert
Assert.Collection(
context.Attributes,
kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("original", kvp.Value); },
kvp => { Assert.Equal("data-val-equalto", kvp.Key); Assert.Equal("original", kvp.Value); },
kvp => { Assert.Equal("data-val-equalto-other", kvp.Key); Assert.Equal("original", kvp.Value); });
}
private class PropertyDisplayNameModel
{
[Display(Name = "MyPropertyDisplayName")]
public string MyProperty { get; set; }
[Display(Name = "OtherPropertyDisplayName")]
public string OtherProperty { get; set; }
}
private class PropertyNameModel
{
public string MyProperty { get; set; }
public string OtherProperty { get; set; }
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="MetadataUtilsCommon.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
namespace Microsoft.OData.Core.Metadata
{
#region Namespaces
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.OData.Edm;
using Microsoft.OData.Edm.Library;
using Microsoft.OData.Edm.Validation;
using Microsoft.OData.Core.UriParser.Semantic;
#endregion Namespaces
/// <summary>
/// Class with utility methods for dealing with OData metadata that are shared with the OData.Query project.
/// </summary>
internal static class MetadataUtilsCommon
{
/// <summary>
/// Checks whether a type reference refers to an OData primitive type (i.e., a primitive, non-stream type).
/// </summary>
/// <param name="typeReference">The (non-null) <see cref="IEdmTypeReference"/> to check.</param>
/// <returns>true if the <paramref name="typeReference"/> is an OData primitive type reference; otherwise false.</returns>
internal static bool IsODataPrimitiveTypeKind(this IEdmTypeReference typeReference)
{
ExceptionUtils.CheckArgumentNotNull(typeReference, "typeReference");
ExceptionUtils.CheckArgumentNotNull(typeReference.Definition, "typeReference.Definition");
return typeReference.Definition.IsODataPrimitiveTypeKind();
}
/// <summary>
/// Checks whether a type refers to an OData primitive type (i.e., a primitive, non-stream type).
/// </summary>
/// <param name="type">The (non-null) <see cref="IEdmType"/> to check.</param>
/// <returns>true if the <paramref name="type"/> is an OData primitive type; otherwise false.</returns>
internal static bool IsODataPrimitiveTypeKind(this IEdmType type)
{
ExceptionUtils.CheckArgumentNotNull(type, "type");
EdmTypeKind typeKind = type.TypeKind;
if (typeKind != EdmTypeKind.Primitive)
{
return false;
}
// also make sure it is not a stream
return !type.IsStream();
}
/// <summary>
/// Checks whether a type reference refers to an OData complex type.
/// </summary>
/// <param name="typeReference">The (non-null) <see cref="IEdmTypeReference"/> to check.</param>
/// <returns>true if the <paramref name="typeReference"/> is an OData complex type reference; otherwise false.</returns>
internal static bool IsODataComplexTypeKind(this IEdmTypeReference typeReference)
{
ExceptionUtils.CheckArgumentNotNull(typeReference, "typeReference");
ExceptionUtils.CheckArgumentNotNull(typeReference.Definition, "typeReference.Definition");
return typeReference.Definition.IsODataComplexTypeKind();
}
/// <summary>
/// Checks whether a type refers to an OData complex type.
/// </summary>
/// <param name="type">The (non-null) <see cref="IEdmType"/> to check.</param>
/// <returns>true if the <paramref name="type"/> is an OData complex type; otherwise false.</returns>
internal static bool IsODataComplexTypeKind(this IEdmType type)
{
ExceptionUtils.CheckArgumentNotNull(type, "type");
return type.TypeKind == EdmTypeKind.Complex;
}
/// <summary>
/// Checks whether a type reference refers to an OData enumeration type.
/// </summary>
/// <param name="typeReference">The (non-null) <see cref="IEdmTypeReference"/> to check.</param>
/// <returns>true if the <paramref name="typeReference"/> is an OData enumeration type reference; otherwise false.</returns>
internal static bool IsODataEnumTypeKind(this IEdmTypeReference typeReference)
{
ExceptionUtils.CheckArgumentNotNull(typeReference, "typeReference");
ExceptionUtils.CheckArgumentNotNull(typeReference.Definition, "typeReference.Definition");
return typeReference.Definition.IsODataEnumTypeKind();
}
/// <summary>
/// Checks whether a type refers to an OData Enumeration type
/// </summary>
/// <param name="type">The (non-null) <see cref="IEdmType"/> to check.</param>
/// <returns>true if the <paramref name="type"/> is an OData enumeration type; otherwise false.</returns>
internal static bool IsODataEnumTypeKind(this IEdmType type)
{
ExceptionUtils.CheckArgumentNotNull(type, "type");
EdmTypeKind typeKind = type.TypeKind;
return typeKind == EdmTypeKind.Enum;
}
/// <summary>
/// Checks whether a type reference refers to an OData type definition.
/// </summary>
/// <param name="typeReference">The (non-null) <see cref="IEdmTypeReference"/> to check.</param>
/// <returns>true if the <paramref name="typeReference"/> is an OData type definition reference; otherwise false.</returns>
internal static bool IsODataTypeDefinitionTypeKind(this IEdmTypeReference typeReference)
{
ExceptionUtils.CheckArgumentNotNull(typeReference, "typeReference");
ExceptionUtils.CheckArgumentNotNull(typeReference.Definition, "typeReference.Definition");
return typeReference.Definition.IsODataTypeDefinitionTypeKind();
}
/// <summary>
/// Checks whether a type refers to an OData type definition.
/// </summary>
/// <param name="type">The (non-null) <see cref="IEdmType"/> to check.</param>
/// <returns>true if the <paramref name="type"/> is an OData type definition; otherwise false.</returns>
internal static bool IsODataTypeDefinitionTypeKind(this IEdmType type)
{
ExceptionUtils.CheckArgumentNotNull(type, "type");
return type.TypeKind == EdmTypeKind.TypeDefinition;
}
/// <summary>
/// Checks whether a type reference refers to an OData entity type.
/// </summary>
/// <param name="typeReference">The (non-null) <see cref="IEdmTypeReference"/> to check.</param>
/// <returns>true if the <paramref name="typeReference"/> is an OData entity type reference; otherwise false.</returns>
internal static bool IsODataEntityTypeKind(this IEdmTypeReference typeReference)
{
ExceptionUtils.CheckArgumentNotNull(typeReference, "typeReference");
ExceptionUtils.CheckArgumentNotNull(typeReference.Definition, "typeReference.Definition");
return typeReference.Definition.IsODataEntityTypeKind();
}
/// <summary>
/// Checks whether a type refers to an OData entity type.
/// </summary>
/// <param name="type">The (non-null) <see cref="IEdmType"/> to check.</param>
/// <returns>true if the <paramref name="type"/> is an OData entity type; otherwise false.</returns>
internal static bool IsODataEntityTypeKind(this IEdmType type)
{
ExceptionUtils.CheckArgumentNotNull(type, "type");
return type.TypeKind == EdmTypeKind.Entity;
}
/// <summary>
/// Checks whether a type reference is considered a value type in OData.
/// </summary>
/// <param name="typeReference">The <see cref="IEdmTypeReference"/> to check.</param>
/// <returns>true if the <paramref name="typeReference"/> is considered a value type; otherwise false.</returns>
/// <remarks>
/// The notion of value type in the OData space is driven by the IDSMP requirements where
/// Clr types denote the primitive types.
/// </remarks>
internal static bool IsODataValueType(this IEdmTypeReference typeReference)
{
IEdmPrimitiveTypeReference primitiveTypeReference = typeReference.AsPrimitiveOrNull();
if (primitiveTypeReference == null)
{
return false;
}
switch (primitiveTypeReference.PrimitiveKind())
{
case EdmPrimitiveTypeKind.Boolean:
case EdmPrimitiveTypeKind.Byte:
case EdmPrimitiveTypeKind.DateTimeOffset:
case EdmPrimitiveTypeKind.Decimal:
case EdmPrimitiveTypeKind.Double:
case EdmPrimitiveTypeKind.Guid:
case EdmPrimitiveTypeKind.Int16:
case EdmPrimitiveTypeKind.Int32:
case EdmPrimitiveTypeKind.Int64:
case EdmPrimitiveTypeKind.SByte:
case EdmPrimitiveTypeKind.Single:
case EdmPrimitiveTypeKind.Duration:
return true;
default:
return false;
}
}
/// <summary>
/// Checks whether a type reference refers to a OData collection value type of non-entity elements.
/// </summary>
/// <param name="typeReference">The (non-null) <see cref="IEdmType"/> to check.</param>
/// <returns>true if the <paramref name="typeReference"/> is a non-entity OData collection value type; otherwise false.</returns>
internal static bool IsNonEntityCollectionType(this IEdmTypeReference typeReference)
{
ExceptionUtils.CheckArgumentNotNull(typeReference, "typeReference");
ExceptionUtils.CheckArgumentNotNull(typeReference.Definition, "typeReference.Definition");
return typeReference.Definition.IsNonEntityCollectionType();
}
/// <summary>
/// Checks whether a type reference refers to a OData collection value type of entity elements.
/// </summary>
/// <param name="typeReference">The (non-null) <see cref="IEdmType"/> to check.</param>
/// <returns>true if the <paramref name="typeReference"/> is an entity OData collection value type; otherwise false.</returns>
internal static bool IsEntityCollectionType(this IEdmTypeReference typeReference)
{
ExceptionUtils.CheckArgumentNotNull(typeReference, "typeReference");
ExceptionUtils.CheckArgumentNotNull(typeReference.Definition, "typeReference.Definition");
return typeReference.Definition.IsEntityCollectionType();
}
/// <summary>
/// Checks whether a type refers to a OData collection value type of non-entity elements.
/// </summary>
/// <param name="type">The (non-null) <see cref="IEdmType"/> to check.</param>
/// <returns>true if the <paramref name="type"/> is a non-entity OData collection value type; otherwise false.</returns>
internal static bool IsNonEntityCollectionType(this IEdmType type)
{
Debug.Assert(type != null, "type != null");
IEdmCollectionType collectionType = type as IEdmCollectionType;
// Return false if this is not a collection type, or if it's a collection of entity types (i.e., a navigation property)
if (collectionType == null || (collectionType.ElementType != null && collectionType.ElementType.TypeKind() == EdmTypeKind.Entity))
{
return false;
}
Debug.Assert(collectionType.TypeKind == EdmTypeKind.Collection, "Expected collection type kind.");
return true;
}
/// <summary>
/// Checks whether a type refers to a OData collection value type of entity elements.
/// </summary>
/// <param name="type">The (non-null) <see cref="IEdmType"/> to check.</param>
/// <returns>true if the <paramref name="type"/> is an entity OData collection value type; otherwise false.</returns>
internal static bool IsEntityCollectionType(this IEdmType type)
{
Debug.Assert(type != null, "type != null");
IEdmCollectionType collectionType = type as IEdmCollectionType;
// Return false if this is not a collection type, or if it's a collection of entity types (i.e., a navigation property)
if (collectionType == null || (collectionType.ElementType != null && collectionType.ElementType.TypeKind() != EdmTypeKind.Entity))
{
return false;
}
Debug.Assert(collectionType.TypeKind == EdmTypeKind.Collection, "Expected collection type kind.");
return true;
}
/// <summary>
/// Casts an <see cref="IEdmTypeReference"/> to a <see cref="IEdmPrimitiveTypeReference"/> or returns null if this is not supported.
/// </summary>
/// <param name="typeReference">The type reference to convert.</param>
/// <returns>An <see cref="IEdmPrimitiveTypeReference"/> instance or null if the <paramref name="typeReference"/> cannot be converted.</returns>
internal static IEdmPrimitiveTypeReference AsPrimitiveOrNull(this IEdmTypeReference typeReference)
{
if (typeReference == null)
{
return null;
}
return typeReference.TypeKind() == EdmTypeKind.Primitive || typeReference.TypeKind() == EdmTypeKind.TypeDefinition ? typeReference.AsPrimitive() : null;
}
/// <summary>
/// Casts an <see cref="IEdmTypeReference"/> to a <see cref="IEdmEntityTypeReference"/> or returns null if this is not supported.
/// </summary>
/// <param name="typeReference">The type reference to convert.</param>
/// <returns>An <see cref="IEdmComplexTypeReference"/> instance or null if the <paramref name="typeReference"/> cannot be converted.</returns>
internal static IEdmEntityTypeReference AsEntityOrNull(this IEdmTypeReference typeReference)
{
if (typeReference == null)
{
return null;
}
return typeReference.TypeKind() == EdmTypeKind.Entity ? typeReference.AsEntity() : null;
}
/// <summary>
/// Casts an <see cref="IEdmTypeReference"/> to a <see cref="IEdmStructuredTypeReference"/> or returns null if this is not supported.
/// </summary>
/// <param name="typeReference">The type reference to convert.</param>
/// <returns>An <see cref="IEdmStructuredTypeReference"/> instance or null if the <paramref name="typeReference"/> cannot be converted.</returns>
internal static IEdmStructuredTypeReference AsStructuredOrNull(this IEdmTypeReference typeReference)
{
if (typeReference == null)
{
return null;
}
return typeReference.IsStructured() ? typeReference.AsStructured() : null;
}
/// <summary>
/// Determines if a <paramref name="sourcePrimitiveType"/> is convertibale according to OData rules to the
/// <paramref name="targetPrimitiveType"/>.
/// </summary>
/// <param name="sourceNodeOrNull">The node which is to be converted.</param>
/// <param name="sourcePrimitiveType">The type which is to be converted.</param>
/// <param name="targetPrimitiveType">The type to which we want to convert.</param>
/// <returns>true if the source type is convertible to the target type; otherwise false.</returns>
internal static bool CanConvertPrimitiveTypeTo(
SingleValueNode sourceNodeOrNull,
IEdmPrimitiveType sourcePrimitiveType,
IEdmPrimitiveType targetPrimitiveType)
{
Debug.Assert(sourcePrimitiveType != null, "sourcePrimitiveType != null");
Debug.Assert(targetPrimitiveType != null, "targetPrimitiveType != null");
EdmPrimitiveTypeKind sourcePrimitiveKind = sourcePrimitiveType.PrimitiveKind;
EdmPrimitiveTypeKind targetPrimitiveKind = targetPrimitiveType.PrimitiveKind;
switch (sourcePrimitiveKind)
{
case EdmPrimitiveTypeKind.SByte:
switch (targetPrimitiveKind)
{
case EdmPrimitiveTypeKind.SByte:
case EdmPrimitiveTypeKind.Int16:
case EdmPrimitiveTypeKind.Int32:
case EdmPrimitiveTypeKind.Int64:
case EdmPrimitiveTypeKind.Single:
case EdmPrimitiveTypeKind.Double:
case EdmPrimitiveTypeKind.Decimal:
return true;
}
break;
case EdmPrimitiveTypeKind.Byte:
switch (targetPrimitiveKind)
{
case EdmPrimitiveTypeKind.Byte:
case EdmPrimitiveTypeKind.Int16:
case EdmPrimitiveTypeKind.Int32:
case EdmPrimitiveTypeKind.Int64:
case EdmPrimitiveTypeKind.Single:
case EdmPrimitiveTypeKind.Double:
case EdmPrimitiveTypeKind.Decimal:
return true;
}
break;
case EdmPrimitiveTypeKind.Int16:
switch (targetPrimitiveKind)
{
case EdmPrimitiveTypeKind.Int16:
case EdmPrimitiveTypeKind.Int32:
case EdmPrimitiveTypeKind.Int64:
case EdmPrimitiveTypeKind.Single:
case EdmPrimitiveTypeKind.Double:
case EdmPrimitiveTypeKind.Decimal:
return true;
}
break;
case EdmPrimitiveTypeKind.Int32:
switch (targetPrimitiveKind)
{
case EdmPrimitiveTypeKind.Int32:
case EdmPrimitiveTypeKind.Int64:
case EdmPrimitiveTypeKind.Single:
case EdmPrimitiveTypeKind.Double:
case EdmPrimitiveTypeKind.Decimal:
return true;
}
break;
case EdmPrimitiveTypeKind.Int64:
switch (targetPrimitiveKind)
{
case EdmPrimitiveTypeKind.Int64:
case EdmPrimitiveTypeKind.Single:
case EdmPrimitiveTypeKind.Double:
case EdmPrimitiveTypeKind.Decimal:
return true;
}
break;
case EdmPrimitiveTypeKind.Single:
switch (targetPrimitiveKind)
{
case EdmPrimitiveTypeKind.Single:
case EdmPrimitiveTypeKind.Double:
return true;
// allow single constant->decimal in order to made L,M,D,F optional
case EdmPrimitiveTypeKind.Decimal:
object tmp;
return TryGetConstantNodePrimitiveLDMF(sourceNodeOrNull, out tmp);
}
break;
case EdmPrimitiveTypeKind.Double:
switch (targetPrimitiveKind)
{
case EdmPrimitiveTypeKind.Double:
return true;
// allow double constant->decimal in order to made L,M,D,F optional
// (if the double value actually has overflowed decimal.MaxValue, exception will occur later. more details in ExpressionLexer.cs)
case EdmPrimitiveTypeKind.Decimal:
object tmp;
return TryGetConstantNodePrimitiveLDMF(sourceNodeOrNull, out tmp);
}
break;
case EdmPrimitiveTypeKind.DateTimeOffset:
switch (targetPrimitiveKind)
{
case EdmPrimitiveTypeKind.DateTimeOffset:
return true;
case EdmPrimitiveTypeKind.Date:
object tmp;
return TryGetConstantNodePrimitiveDate(sourceNodeOrNull, out tmp);
}
break;
default:
return sourcePrimitiveKind == targetPrimitiveKind || targetPrimitiveType.IsAssignableFrom(sourcePrimitiveType);
}
return false;
}
/// <summary>
/// Try getting the constant DateTimeOffset node value
/// </summary>
/// <param name="sourceNodeOrNull">The Node</param>
/// <param name="primitiveValue">The out parameter if succeeds</param>
/// <returns>true if the constant node is for date type</returns>
internal static bool TryGetConstantNodePrimitiveDate(SingleValueNode sourceNodeOrNull, out object primitiveValue)
{
primitiveValue = null;
ConstantNode constantNode = sourceNodeOrNull as ConstantNode;
if (constantNode != null)
{
IEdmPrimitiveType primitiveType = constantNode.TypeReference.AsPrimitiveOrNull().Definition as IEdmPrimitiveType;
if (primitiveType != null)
{
switch (primitiveType.PrimitiveKind)
{
case EdmPrimitiveTypeKind.DateTimeOffset:
Date result;
if (UriParser.UriUtils.TryUriStringToDate(constantNode.LiteralText, out result))
{
primitiveValue = constantNode.LiteralText;
return true;
}
break;
default:
return false;
}
}
}
return false;
}
/// <summary>
/// Tries getting the constant node's primitive L M D F value (which can be converted to other primitive type while primitive AccessPropertyNode can't).
/// </summary>
/// <param name="sourceNodeOrNull">The Node</param>
/// <param name="primitiveValue">THe out parameter if succeeds</param>
/// <returns>true if the constant node is for long, float, double or decimal type</returns>
internal static bool TryGetConstantNodePrimitiveLDMF(SingleValueNode sourceNodeOrNull, out object primitiveValue)
{
primitiveValue = null;
ConstantNode tmp = sourceNodeOrNull as ConstantNode;
if (tmp != null)
{
IEdmPrimitiveType primitiveType = tmp.TypeReference.AsPrimitiveOrNull().Definition as IEdmPrimitiveType;
if (primitiveType != null)
{
switch (primitiveType.PrimitiveKind)
{
case EdmPrimitiveTypeKind.Int32:
case EdmPrimitiveTypeKind.Int64:
case EdmPrimitiveTypeKind.Single:
case EdmPrimitiveTypeKind.Double:
case EdmPrimitiveTypeKind.Decimal:
primitiveValue = tmp.Value;
return true;
default:
return false;
}
}
}
return false;
}
}
}
| |
/*
* 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.Data;
using System.Reflection;
using log4net;
using MySql.Data.MySqlClient;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Data.MySQL
{
public class MySQLGenericTableHandler<T> : MySqlFramework where T: class, new()
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected Dictionary<string, FieldInfo> m_Fields =
new Dictionary<string, FieldInfo>();
protected List<string> m_ColumnNames = null;
protected string m_Realm;
protected FieldInfo m_DataField = null;
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
public MySQLGenericTableHandler(MySqlTransaction trans,
string realm, string storeName) : base(trans)
{
m_Realm = realm;
CommonConstruct(storeName);
}
public MySQLGenericTableHandler(string connectionString,
string realm, string storeName) : base(connectionString)
{
m_Realm = realm;
CommonConstruct(storeName);
}
protected void CommonConstruct(string storeName)
{
if (storeName != String.Empty)
{
// We always use a new connection for any Migrations
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
Migration m = new Migration(dbcon, Assembly, storeName);
m.Update();
}
}
Type t = typeof(T);
FieldInfo[] fields = t.GetFields(BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
if (fields.Length == 0)
return;
foreach (FieldInfo f in fields)
{
if (f.Name != "Data")
m_Fields[f.Name] = f;
else
m_DataField = f;
}
}
private void CheckColumnNames(IDataReader reader)
{
if (m_ColumnNames != null)
return;
List<string> columnNames = new List<string>();
DataTable schemaTable = reader.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
{
if (row["ColumnName"] != null &&
(!m_Fields.ContainsKey(row["ColumnName"].ToString())))
columnNames.Add(row["ColumnName"].ToString());
}
m_ColumnNames = columnNames;
}
public virtual T[] Get(string field, string key)
{
return Get(new string[] { field }, new string[] { key });
}
public virtual T[] Get(string[] fields, string[] keys)
{
return Get(fields, keys, String.Empty);
}
public virtual T[] Get(string[] fields, string[] keys, string options)
{
if (fields.Length != keys.Length)
return new T[0];
List<string> terms = new List<string>();
using (MySqlCommand cmd = new MySqlCommand())
{
for (int i = 0 ; i < fields.Length ; i++)
{
cmd.Parameters.AddWithValue(fields[i], keys[i]);
terms.Add("`" + fields[i] + "` = ?" + fields[i]);
}
string where = String.Join(" and ", terms.ToArray());
string query = String.Format("select * from {0} where {1} {2}",
m_Realm, where, options);
cmd.CommandText = query;
return DoQuery(cmd);
}
}
protected T[] DoQuery(MySqlCommand cmd)
{
if (m_trans == null)
{
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
T[] ret = DoQueryWithConnection(cmd, dbcon);
dbcon.Close();
return ret;
}
}
else
{
return DoQueryWithTransaction(cmd, m_trans);
}
}
protected T[] DoQueryWithTransaction(MySqlCommand cmd, MySqlTransaction trans)
{
cmd.Transaction = trans;
return DoQueryWithConnection(cmd, trans.Connection);
}
protected T[] DoQueryWithConnection(MySqlCommand cmd, MySqlConnection dbcon)
{
List<T> result = new List<T>();
cmd.Connection = dbcon;
using (IDataReader reader = cmd.ExecuteReader())
{
if (reader == null)
return new T[0];
CheckColumnNames(reader);
while (reader.Read())
{
T row = new T();
foreach (string name in m_Fields.Keys)
{
if (reader[name] is DBNull)
{
continue;
}
if (m_Fields[name].FieldType == typeof(bool))
{
int v = Convert.ToInt32(reader[name]);
m_Fields[name].SetValue(row, v != 0 ? true : false);
}
else if (m_Fields[name].FieldType == typeof(UUID))
{
m_Fields[name].SetValue(row, DBGuid.FromDB(reader[name]));
}
else if (m_Fields[name].FieldType == typeof(int))
{
int v = Convert.ToInt32(reader[name]);
m_Fields[name].SetValue(row, v);
}
else if (m_Fields[name].FieldType == typeof(uint))
{
uint v = Convert.ToUInt32(reader[name]);
m_Fields[name].SetValue(row, v);
}
else
{
m_Fields[name].SetValue(row, reader[name]);
}
}
if (m_DataField != null)
{
Dictionary<string, string> data =
new Dictionary<string, string>();
foreach (string col in m_ColumnNames)
{
data[col] = reader[col].ToString();
if (data[col] == null)
data[col] = String.Empty;
}
m_DataField.SetValue(row, data);
}
result.Add(row);
}
}
cmd.Connection = null;
return result.ToArray();
}
public virtual T[] Get(string where)
{
using (MySqlCommand cmd = new MySqlCommand())
{
string query = String.Format("select * from {0} where {1}",
m_Realm, where);
cmd.CommandText = query;
return DoQuery(cmd);
}
}
public virtual bool Store(T row)
{
// m_log.DebugFormat("[MYSQL GENERIC TABLE HANDLER]: Store(T row) invoked");
using (MySqlCommand cmd = new MySqlCommand())
{
string query = "";
List<String> names = new List<String>();
List<String> values = new List<String>();
foreach (FieldInfo fi in m_Fields.Values)
{
names.Add(fi.Name);
values.Add("?" + fi.Name);
// Temporarily return more information about what field is unexpectedly null for
// http://opensimulator.org/mantis/view.php?id=5403. This might be due to a bug in the
// InventoryTransferModule or we may be required to substitute a DBNull here.
if (fi.GetValue(row) == null)
throw new NullReferenceException(
string.Format(
"[MYSQL GENERIC TABLE HANDLER]: Trying to store field {0} for {1} which is unexpectedly null",
fi.Name, row));
cmd.Parameters.AddWithValue(fi.Name, fi.GetValue(row).ToString());
}
if (m_DataField != null)
{
Dictionary<string, string> data =
(Dictionary<string, string>)m_DataField.GetValue(row);
foreach (KeyValuePair<string, string> kvp in data)
{
names.Add(kvp.Key);
values.Add("?" + kvp.Key);
cmd.Parameters.AddWithValue("?" + kvp.Key, kvp.Value);
}
}
query = String.Format("replace into {0} (`", m_Realm) + String.Join("`,`", names.ToArray()) + "`) values (" + String.Join(",", values.ToArray()) + ")";
cmd.CommandText = query;
if (ExecuteNonQuery(cmd) > 0)
return true;
return false;
}
}
public virtual bool Delete(string field, string key)
{
return Delete(new string[] { field }, new string[] { key });
}
public virtual bool Delete(string[] fields, string[] keys)
{
// m_log.DebugFormat(
// "[MYSQL GENERIC TABLE HANDLER]: Delete(string[] fields, string[] keys) invoked with {0}:{1}",
// string.Join(",", fields), string.Join(",", keys));
if (fields.Length != keys.Length)
return false;
List<string> terms = new List<string>();
using (MySqlCommand cmd = new MySqlCommand())
{
for (int i = 0 ; i < fields.Length ; i++)
{
cmd.Parameters.AddWithValue(fields[i], keys[i]);
terms.Add("`" + fields[i] + "` = ?" + fields[i]);
}
string where = String.Join(" and ", terms.ToArray());
string query = String.Format("delete from {0} where {1}", m_Realm, where);
cmd.CommandText = query;
return ExecuteNonQuery(cmd) > 0;
}
}
public long GetCount(string field, string key)
{
return GetCount(new string[] { field }, new string[] { key });
}
public long GetCount(string[] fields, string[] keys)
{
if (fields.Length != keys.Length)
return 0;
List<string> terms = new List<string>();
using (MySqlCommand cmd = new MySqlCommand())
{
for (int i = 0; i < fields.Length; i++)
{
cmd.Parameters.AddWithValue(fields[i], keys[i]);
terms.Add("`" + fields[i] + "` = ?" + fields[i]);
}
string where = String.Join(" and ", terms.ToArray());
string query = String.Format("select count(*) from {0} where {1}",
m_Realm, where);
cmd.CommandText = query;
Object result = DoQueryScalar(cmd);
return Convert.ToInt64(result);
}
}
public long GetCount(string where)
{
using (MySqlCommand cmd = new MySqlCommand())
{
string query = String.Format("select count(*) from {0} where {1}",
m_Realm, where);
cmd.CommandText = query;
object result = DoQueryScalar(cmd);
return Convert.ToInt64(result);
}
}
public object DoQueryScalar(MySqlCommand cmd)
{
if (m_trans == null)
{
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
cmd.Connection = dbcon;
Object ret = cmd.ExecuteScalar();
cmd.Connection = null;
dbcon.Close();
return ret;
}
}
else
{
cmd.Connection = m_trans.Connection;
cmd.Transaction = m_trans;
return cmd.ExecuteScalar();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Text;
using AltairStudios.Core.Mvc;
using AltairStudios.Core.Orm.Models;
using AltairStudios.Core.Orm.Providers;
using AltairStudios.Core.Util;
namespace AltairStudios.Core.Orm {
/// <summary>
/// Model.
/// </summary>
public class Model : AltairStudios.Core.Mvc.Model {
public ModelList<T> getBy<T>() {
return this.getBy<T>(false);
}
public ModelList<T> getBy<T>(bool subqueries) {
Type type = this.GetType();
PropertyInfo[] properties = this.GetType().GetProperties();
ModelList<PropertyInfo> parameters = new ModelList<PropertyInfo>();
List<string> fields = this.getFields(properties);
List<string> primaryFields = new ModelList<string>();
List<string> indexFields = new ModelList<string>();
ModelList<PropertyInfo> primaryKeys = new ModelList<PropertyInfo>();
ModelList<PropertyInfo> indexes = new ModelList<PropertyInfo>();
ModelList<PropertyInfo> fieldParams = new ModelList<PropertyInfo>();
ModelList<PropertyInfo> sublistParams = new ModelList<PropertyInfo>();
ModelList<PropertyInfo> subPrimaryKeys = new ModelList<PropertyInfo>();
for(int i = 0; i < properties.Length; i++) {
TemplatizeAttribute[] attributes = (TemplatizeAttribute[])properties[i].GetCustomAttributes(typeof(TemplatizeAttribute), true);
PrimaryKeyAttribute[] attributesPrimaryKey = (PrimaryKeyAttribute[])properties[i].GetCustomAttributes(typeof(PrimaryKeyAttribute), true);
if(attributesPrimaryKey.Length > 0) {
subPrimaryKeys.Add(properties[i]);
}
if(attributes.Length > 0 && properties[i].PropertyType.GetInterface("IModelizable") == null && properties[i].PropertyType.GetInterface("IList") == null) {
fieldParams.Add(properties[i]);
} else {
sublistParams.Add(properties[i]);
}
if(properties[i].GetValue(this, null) != null) {
if(attributes.Length > 0 && properties[i].PropertyType.GetInterface("IModelizable") == null && properties[i].PropertyType.GetInterface("IList") == null) {
parameters.Add(properties[i]);
}
//PrimaryKeyAttribute[] attributesPrimaryKey = (PrimaryKeyAttribute[])properties[i].GetCustomAttributes(typeof(PrimaryKeyAttribute), true);
if(attributesPrimaryKey.Length > 0 && ((attributesPrimaryKey[0].AutoIncrement && (int)properties[i].GetValue(this, null) != 0) || (attributesPrimaryKey[0].AutoIncrement == false && properties[i].GetValue(this, null) != ""))) {
primaryKeys.Add(properties[i]);
primaryFields.Add(properties[i].Name);
}
IndexAttribute[] attributesIndex = (IndexAttribute[])properties[i].GetCustomAttributes(typeof(IndexAttribute), true);
if(attributesIndex.Length > 0 && properties[i].GetValue(this, null) != "") {
indexes.Add(properties[i]);
indexFields.Add(properties[i].Name);
}
}
}
IDbCommand command = SqlProvider.getProvider().createCommand();
if(primaryKeys.Count > 0) {
command.CommandText = SqlProvider.getProvider().sqlString(this, type, fields, primaryKeys.ToArray());
for(int i = 0; i < primaryKeys.Count; i++) {
IDbDataParameter parameter = SqlProvider.getProvider().createParameter();
parameter.ParameterName = primaryKeys[i].Name;
parameter.Value = primaryKeys[i].GetValue(this, null);
command.Parameters.Add(parameter);
}
} else if(indexes.Count > 0) {
command.CommandText = SqlProvider.getProvider().sqlString(this, type, fields, indexes.ToArray());
for(int i = 0; i < indexes.Count; i++) {
IDbDataParameter parameter = SqlProvider.getProvider().createParameter();
parameter.ParameterName = indexes[i].Name;
parameter.Value = indexes[i].GetValue(this, null);
command.Parameters.Add(parameter);
}
} else {
command.CommandText = SqlProvider.getProvider().sqlString(this, type, fields, parameters.ToArray());
for(int i = 0; i < parameters.Count; i++) {
IDbDataParameter parameter = SqlProvider.getProvider().createParameter();
parameter.ParameterName = parameters[i].Name;
parameter.Value = parameters[i].GetValue(this, null);
command.Parameters.Add(parameter);
}
}
IDataReader reader = command.ExecuteReader();
ModelList<T> models = new ModelList<T>();
ConstructorInfo constructor = type.GetConstructor(new Type[0]);
while(reader.Read()) {
object instance = constructor.Invoke(new Object[0]);
for(int i = 0; i < fieldParams.Count; i++) {
if(reader[fieldParams[i].Name] != DBNull.Value) {
PropertyInfo property = type.GetProperty(fieldParams[i].Name);
if(fieldParams[i].GetValue(this, null) != null && fieldParams[i].GetValue(this, null).GetType() == typeof(double)) {
property.SetValue(instance, double.Parse(reader[fieldParams[i].Name].ToString()), null);
} else {
property.SetValue(instance, reader[fieldParams[i].Name], null);
}
}
}
models.Add(this.cast<T>(instance));
}
reader.Close();
if(subqueries) {
for(int i = 0; i < models.Count; i++) {
for(int j = 0; j < sublistParams.Count; j++) {
if(sublistParams[j].PropertyType.GetInterface("IModelizable") != null && sublistParams[j].PropertyType.GetInterface("IList") == null) {
models[i].GetType().GetProperty(sublistParams[j].Name).SetValue(models[i], this.GetType().GetMethod("getByForeignModel").MakeGenericMethod(sublistParams[j].PropertyType).Invoke(this, new object[]{subPrimaryKeys[0], sublistParams[j]}), null);
} else if(sublistParams[j].PropertyType.GetInterface("IModelizable") != null && sublistParams[j].PropertyType.GetInterface("IList") != null && sublistParams[j].PropertyType.GetGenericArguments()[0].GetInterface("IModelizable") != null) {
models[i].GetType().GetProperty(sublistParams[j].Name).SetValue(models[i], this.GetType().GetMethod("getByForeignModels").MakeGenericMethod(sublistParams[j].PropertyType.GetGenericArguments()[0]).Invoke(this, new object[]{subPrimaryKeys[0], sublistParams[j]}), null);
} else if(sublistParams[j].PropertyType.GetInterface("IModelizable") != null && sublistParams[j].PropertyType.GetInterface("IList") != null && sublistParams[j].PropertyType.GetGenericArguments()[0].GetInterface("IModelizable") == null) {
models[i].GetType().GetProperty(sublistParams[j].Name).SetValue(models[i], this.GetType().GetMethod("getByForeignSimple").MakeGenericMethod(sublistParams[j].PropertyType.GetGenericArguments()[0]).Invoke(this, new object[]{subPrimaryKeys[0], sublistParams[j]}), null);
} else {
models[i].GetType().GetProperty(sublistParams[j].Name).SetValue(models[i], this.GetType().GetMethod("getByForeignSimple").MakeGenericMethod(sublistParams[j].PropertyType.GetGenericArguments()[0]).Invoke(this, new object[]{subPrimaryKeys[0], sublistParams[j]}), null);
}
}
}
}
command.Connection.Close();
return models;
}
public ModelList<T> getByForeignSimple<T>(PropertyInfo primary, PropertyInfo type) {
ModelList<T> result = new ModelList<T>();
List<string> fields = new List<string>();
fields.Add(type.Name);
List<string> conditions = new List<string>();
conditions.Add(this.GetType().Name + "_" + primary.Name);
IDbCommand command = SqlProvider.getProvider().createCommand();
command.CommandText = SqlProvider.getProvider().sqlString(fields, this.GetType().Name + "_" + type.Name, conditions);
IDbDataParameter parameter = SqlProvider.getProvider().createParameter();
parameter.ParameterName = this.GetType().Name + "_" + primary.Name;
parameter.Value = primary.GetValue(this, null);
command.Parameters.Add(parameter);
IDataReader reader = command.ExecuteReader();
while(reader.Read()) {
result.Add((T)reader[0]);
}
reader.Close();
command.Connection.Close();
return result;
}
public T getByForeignModel<T>(PropertyInfo primary, PropertyInfo type) {
T result = default(T);
ModelList<T> results = this.getByForeignModels<T>(primary, type);
if(results.Count > 0) {
result = results[0];
}
return result;
}
public ModelList<T> getByForeignModels<T>(PropertyInfo primary, PropertyInfo type) {
ModelList<T> result = new ModelList<T>();
List<string> fields = new List<string>();
//fields.Add(type.Name);
PropertyInfo[] properties = null;
PropertyInfo subPrimary = null;
Type subType = null;
if(type.PropertyType.IsGenericType) {
properties = type.PropertyType.GetGenericArguments()[0].GetProperties();
subType = type.PropertyType.GetGenericArguments()[0];
} else {
properties = type.PropertyType.GetProperties();
subType = type.PropertyType;
}
for(int i = 0; i < properties.Length; i++) {
PrimaryKeyAttribute[] primarys = (PrimaryKeyAttribute[])properties[i].GetCustomAttributes(typeof(PrimaryKeyAttribute), true);
if(primarys.Length > 0) {
subPrimary = properties[i];
i = properties.Length;
}
/*if(type.PropertyType.IsGenericType) {
PropertyInfo[] subProperties = properties[i].PropertyType.GetGenericArguments()[0].GetProperties();
for(int j = 0; j < subProperties.Length; j++) {
PrimaryKeyAttribute[] primarys = (PrimaryKeyAttribute[])subProperties[j].GetCustomAttributes(typeof(PrimaryKeyAttribute), true);
if(primarys.Length > 0) {
subPrimary = subProperties[j].PropertyType.GetGenericArguments()[0];
j = subProperties.Length;
i = properties.Length;
}
}
} else {
PrimaryKeyAttribute[] primarys = (PrimaryKeyAttribute[])properties[i].GetCustomAttributes(typeof(PrimaryKeyAttribute), true);
if(primarys.Length > 0) {
subPrimary = properties[i].PropertyType;
i = properties.Length;
}
}*/
}
fields.Add(subType.Name + "_" + subPrimary.Name);
List<string> conditions = new List<string>();
conditions.Add(this.GetType().Name + "_" + primary.Name);
IDbCommand command = SqlProvider.getProvider().createCommand();
string table = this.GetType().Name + "_";
if(type.PropertyType.IsGenericType) {
table += type.PropertyType.GetGenericArguments()[0].Name;
} else {
table += type.PropertyType.Name;
}
command.CommandText = SqlProvider.getProvider().sqlString(fields, table, conditions);
IDbDataParameter parameter = SqlProvider.getProvider().createParameter();
parameter.ParameterName = this.GetType().Name + "_" + primary.Name;
parameter.Value = primary.GetValue(this, null);
command.Parameters.Add(parameter);
IDataReader reader = command.ExecuteReader();
while(reader.Read()) {
//object key = reader[type.PropertyType.Name + "_" + subPrimary.Name];
object key = reader[0];
object instance;
if(type.PropertyType.IsGenericType) {
ConstructorInfo constructor = type.PropertyType.GetGenericArguments()[0].GetConstructor(new Type[0]);
instance = constructor.Invoke(new Object[0]);
instance.GetType().GetProperty(subPrimary.Name).SetValue(instance, key, null);
} else {
ConstructorInfo constructor = type.PropertyType.GetConstructor(new Type[0]);
instance = constructor.Invoke(new Object[0]);
/*instance.GetType().GetProperty(subPrimary.Name).SetValue(instance, key, null);
result.Add(this.cast<T>(instance));*/
}
if(instance.GetType().GetInterface("IModelizable") != null && instance.GetType().GetInterface("IList") == null) {
instance = ((Model)instance).getBy<T>()[0];
}
result.Add(this.cast<T>(instance));
/*
instance.GetType().GetProperty(subPrimary.Name).SetValue(instance, key, null);
result.Add(this.cast<T>(instance));
*/
}
reader.Close();
command.Connection.Close();
return result;
}
/// <summary>
/// Insert this model instance into database.
/// </summary>
public long insert() {
PropertyInfo[] properties = this.GetType().GetProperties();
ModelList<PropertyInfo> parameters = new ModelList<PropertyInfo>();
Dictionary<string, Dictionary<long, Model>> ids = new Dictionary<string, Dictionary<long, Model>>();
Dictionary<string, List<object>> basicIds = new Dictionary<string, List<object>>();
for(int i = 0; i < properties.Length; i++) {
if(properties[i].GetValue(this, null) != null) {
TemplatizeAttribute[] attributes = (TemplatizeAttribute[])properties[i].GetCustomAttributes(typeof(TemplatizeAttribute), true);
PrimaryKeyAttribute[] primarys = (PrimaryKeyAttribute[])properties[i].GetCustomAttributes(typeof(PrimaryKeyAttribute), true);
if((primarys.Length > 0 && !primarys[0].AutoIncrement) || (primarys.Length == 0 && attributes.Length > 0)) {
if(properties[i].PropertyType.GetInterface("IModelizable") != null) {
if(properties[i].PropertyType.GetInterface("IList") != null) {
if(properties[i].PropertyType.GetGenericArguments()[0].GetInterface("IModelizable") != null) {
foreach(Model iterModel in (IEnumerable<Model>)properties[i].GetValue(this, null)) {
long subId = iterModel.insert();
string name = properties[i].PropertyType.ToString();
if(!ids.ContainsKey(name)) {
ids.Add(name, new Dictionary<long, Model>());
}
ids[name].Add(subId, iterModel);
}
} else {
string name = properties[i].PropertyType.Name;
if(!basicIds.ContainsKey(name)) {
basicIds.Add(name, new List<object>());
}
basicIds[name].Add(properties[i].GetValue(this, null));
}
} else {
long subId = ((Model)properties[i].GetValue(this, null)).insert();
string name = properties[i].PropertyType.ToString();
if(!ids.ContainsKey(name)) {
ids.Add(name, new Dictionary<long, Model>());
}
ids[name].Add(subId, ((Model)properties[i].GetValue(this, null)));
}
} else {
parameters.Add(properties[i]);
}
/*
if(Reflection.Instance.isChildOf(properties[i].PropertyType, typeof(Model))) {
long subId = ((Model)properties[i].GetValue(this, null)).insert();
string name = properties[i].PropertyType.ToString();
if(!ids.ContainsKey(name)) {
ids.Add(name, new Dictionary<long, Model>());
}
ids[name].Add(subId, ((Model)properties[i].GetValue(this, null)));
} else {
parameters.Add(properties[i]);
}*/
}
}
}
IDbCommand command = SqlProvider.getProvider().createCommand();
command.CommandText = SqlProvider.getProvider().sqlInsert(this.GetType(), parameters);
for(int i = 0; i < parameters.Count; i++) {
IDbDataParameter parameter = SqlProvider.getProvider().createParameter();
parameter.ParameterName = parameters[i].Name;
parameter.Value = parameters[i].GetValue(this, null);
command.Parameters.Add(parameter);
}
long id = (long)command.ExecuteScalar();
foreach(string key in ids.Keys) {
foreach(long longId in ids[key].Keys) {
Dictionary<string, object> sqlParams = new Dictionary<string, object>();
PropertyInfo[] properties1 = this.GetType().GetProperties();
PropertyInfo[] properties2 = ids[key][longId].GetType().GetProperties();
for(int i = 0; i < properties1.Length; i++) {
PrimaryKeyAttribute[] primaryKeys = (PrimaryKeyAttribute[])properties1[i].GetCustomAttributes(typeof(PrimaryKeyAttribute), true);
if(primaryKeys.Length > 0) {
sqlParams.Add(this.GetType().Name + "_" + properties1[i].Name, id);
}
}
for(int i = 0; i < properties2.Length; i++) {
PrimaryKeyAttribute[] primaryKeys = (PrimaryKeyAttribute[])properties2[i].GetCustomAttributes(typeof(PrimaryKeyAttribute), true);
if(primaryKeys.Length > 0) {
sqlParams.Add(ids[key][longId].GetType().Name + "_" + properties2[i].Name, longId);
}
}
this.query(SqlProvider.getProvider().sqlInsertForeign(this.GetType(), ids[key][longId].GetType()), sqlParams);
}
}
foreach(string key in basicIds.Keys) {
for(int i = 0; i < basicIds[key].Count; i++) {
Dictionary<string, object> sqlParams = new Dictionary<string, object>();
PropertyInfo[] properties1 = this.GetType().GetProperties();
for(int j = 0; j < properties1.Length; j++) {
PrimaryKeyAttribute[] primaryKeys = (PrimaryKeyAttribute[])properties1[j].GetCustomAttributes(typeof(PrimaryKeyAttribute), true);
if(primaryKeys.Length > 0) {
sqlParams.Add(this.GetType().Name + "_" + properties1[j].Name, id);
}
}
sqlParams.Add(key, basicIds[key][i]);
this.query(SqlProvider.getProvider().sqlInsertBasicForeign(this.GetType(), key, basicIds[key][i].GetType()), sqlParams);
}
}
command.Connection.Close();
return id;
}
/// <summary>
/// Update this instance.
/// </summary>
public void update() {
PropertyInfo[] properties = this.GetType().GetProperties();
ModelList<PropertyInfo> parameters = new ModelList<PropertyInfo>();
ModelList<PropertyInfo> primaryKeys = new ModelList<PropertyInfo>();
for(int i = 0; i < properties.Length; i++) {
//if(properties[i].GetValue(this, null) != null) {
TemplatizeAttribute[] attributes = (TemplatizeAttribute[])properties[i].GetCustomAttributes(typeof(TemplatizeAttribute), true);
PrimaryKeyAttribute[] primarys = (PrimaryKeyAttribute[])properties[i].GetCustomAttributes(typeof(PrimaryKeyAttribute), true);
if(primarys.Length > 0) {
primaryKeys.Add(properties[i]);
}
if(attributes.Length > 0) {
if(!Reflection.Instance.isChildOf(properties[i].PropertyType, typeof(Model))) {
parameters.Add(properties[i]);
}
}
//}
}
IDbCommand command = SqlProvider.getProvider().createCommand();
command.CommandText = SqlProvider.getProvider().sqlUpdate(this.GetType());
for(int i = 0; i < parameters.Count; i++) {
IDbDataParameter parameter = SqlProvider.getProvider().createParameter();
parameter.ParameterName = parameters[i].Name;
parameter.Value = parameters[i].GetValue(this, null);
command.Parameters.Add(parameter);
}
command.ExecuteNonQuery();
command.Connection.Close();
return;
}
/// <summary>
/// Delete this instance.
/// </summary>
public void delete() {
PropertyInfo[] properties = this.GetType().GetProperties();
ModelList<PropertyInfo> primaryKeys = new ModelList<PropertyInfo>();
for(int i = 0; i < properties.Length; i++) {
PrimaryKeyAttribute[] primarys = (PrimaryKeyAttribute[])properties[i].GetCustomAttributes(typeof(PrimaryKeyAttribute), true);
if(primarys.Length > 0) {
primaryKeys.Add(properties[i]);
}
}
IDbCommand command = SqlProvider.getProvider().createCommand();
command.CommandText = SqlProvider.getProvider().sqlDelete(this.GetType());
for(int i = 0; i < primaryKeys.Count; i++) {
IDbDataParameter parameter = SqlProvider.getProvider().createParameter();
parameter.ParameterName = primaryKeys[i].Name;
parameter.Value = primaryKeys[i].GetValue(this, null);
command.Parameters.Add(parameter);
}
command.ExecuteNonQuery();
command.Connection.Close();
return;
}
/// <summary>
/// Creates the table.
/// </summary>
/// <returns>
/// The table.
/// </returns>
public string createTable() {
return SqlProvider.getProvider().sqlCreateTable(this.GetType());
}
/// <summary>
/// Query the specified sql.
/// </summary>
/// <param name='sql'>
/// Sql.
/// </param>
public List<Dictionary<string, string>> query(string sql) {
return this.query(sql, null);
}
/// <summary>
/// Query the specified sql and parameters.
/// </summary>
/// <param name='sql'>
/// Sql.
/// </param>
/// <param name='parameters'>
/// Parameters.
/// </param>
public List<Dictionary<string, string>> query(string sql, Dictionary<string, object> parameters) {
IDbCommand command = SqlProvider.getProvider().createCommand();
command.CommandText = sql;
if(parameters != null) {
foreach(string key in parameters.Keys) {
IDbDataParameter parameter = SqlProvider.getProvider().createParameter();
parameter.ParameterName = "@" + key;
parameter.Value = parameters[key];
command.Parameters.Add(parameter);
}
}
IDataReader reader = command.ExecuteReader();
List<Dictionary<string, string>> result = new List<Dictionary<string, string>>();
while(reader.Read()) {
Dictionary<string, string> row = new Dictionary<string, string>();
for(int i = 0; i < reader.FieldCount; i++) {
row.Add(reader.GetName(i), reader[i].ToString());
}
result.Add(row);
}
reader.Close();
command.Connection.Close();
return result;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace MVP.Service.WebAPI.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
namespace Stumps.Server
{
using System;
using System.Security.Cryptography;
using System.Text;
/// <summary>
/// A class that provides the foundation for recorded HTTP requests and responses.
/// </summary>
public abstract class RecordedContextPartBase : IStumpsHttpContextPart
{
private byte[] _bodyBuffer;
/// <summary>
/// Initializes a new instance of the <see cref="RecordedContextPartBase" /> class.
/// </summary>
/// <param name="contextPart">The context part.</param>
/// <param name="decoderHandling">The <see cref="ContentDecoderHandling"/> requirements for the HTTP body.</param>
/// <exception cref="ArgumentNullException"><paramref name="contextPart"/> is <c>null</c>.</exception>
protected RecordedContextPartBase(IStumpsHttpContextPart contextPart, ContentDecoderHandling decoderHandling)
{
contextPart = contextPart ?? throw new ArgumentNullException(nameof(contextPart));
// Copy in the headers
this.Headers = new HttpHeaders();
contextPart.Headers.CopyTo(this.Headers);
// Copy the body into the context part
_bodyBuffer = new byte[contextPart.BodyLength];
if (_bodyBuffer.Length > 0)
{
Buffer.BlockCopy(contextPart.GetBody(), 0, _bodyBuffer, 0, _bodyBuffer.Length);
}
// Decode the body if necessary
if (decoderHandling == ContentDecoderHandling.DecodeRequired)
{
DecodeBody();
}
this.ExamineBody();
}
/// <summary>
/// Gets the length of the HTTP body.
/// </summary>
/// <value>
/// The length of the HTTP body.
/// </value>
public int BodyLength
{
get => _bodyBuffer.Length;
}
/// <summary>
/// Gets the MD5 hash of the HTTP body.
/// </summary>
/// <value>
/// The MD5 hash of the HTTP body.
/// </value>
public string BodyMd5Hash
{
get;
private set;
}
/// <summary>
/// Gets the collection of HTTP headers.
/// </summary>
/// <value>
/// The collection of HTTP headers.
/// </value>
public IHttpHeaders Headers
{
get;
set;
}
/// <summary>
/// Gets or sets information about how the HTTP body was classified.
/// </summary>
/// <value>
/// The information about how the HTTP body was classified.
/// </value>
public HttpBodyClassification BodyType
{
get;
private set;
}
/// <summary>
/// Gets the bytes for the HTTP body.
/// </summary>
/// <returns>
/// An array of <see cref="Byte"/> values representing the HTTP body.
/// </returns>
public byte[] GetBody() => _bodyBuffer;
/// <summary>
/// Gets the HTTP body as a <see cref="String"/>.
/// </summary>
/// <returns>A <see cref="String"/> representing the body of the HTTP response.</returns>
/// <remarks>The body is decoded using UTF8 encoding.</remarks>
public string GetBodyAsString() => GetBodyAsString(Encoding.UTF8);
/// <summary>
/// Gets the HTTP body as a <see cref="String"/>.
/// </summary>
/// <param name="encoding">The encoding used to convert the HTTP body into a <see cref="String"/>.</param>
/// <remarks>The body is decoded using UTF8 encoding.</remarks>
public string GetBodyAsString(Encoding encoding)
{
encoding = encoding ?? throw new ArgumentNullException(nameof(encoding));
return encoding.GetString(_bodyBuffer);
}
/// <summary>
/// Appends a byte array to the body of the HTTP response.
/// </summary>
/// <param name="buffer">The bytes to append to the body of the response.</param>
protected void AppendToBody(byte[] buffer)
{
if (buffer == null)
{
return;
}
var newBodyLength = _bodyBuffer.Length + buffer.Length;
var newBuffer = new byte[newBodyLength];
Buffer.BlockCopy(_bodyBuffer, 0, newBuffer, 0, _bodyBuffer.Length);
Buffer.BlockCopy(buffer, 0, newBuffer, _bodyBuffer.Length, buffer.Length);
_bodyBuffer = newBuffer;
}
/// <summary>
/// Clears the existing body of the HTTP response.
/// </summary>
protected void ClearBody() => _bodyBuffer = new byte[0];
/// <summary>
/// Examines the body for the classification, and the MD5 hash.
/// </summary>
protected void ExamineBody()
{
DetermineBodyClassification();
GenerateMd5Hash();
}
/// <summary>
/// Decodes the body of a based on the content encoding.
/// </summary>
private void DecodeBody()
{
var contentEncoding = this.Headers["Content-Encoding"];
if (contentEncoding != null)
{
var encoder = new ContentEncoder(contentEncoding);
_bodyBuffer = encoder.Decode(_bodyBuffer);
}
}
/// <summary>
/// Determines the HTTP body to determine its classification.
/// </summary>
private void DetermineBodyClassification()
{
if (_bodyBuffer.Length == 0)
{
this.BodyType = HttpBodyClassification.Empty;
}
else if ((this.Headers["Content-Type"] ?? string.Empty).StartsWith("image", StringComparison.Ordinal))
{
this.BodyType = HttpBodyClassification.Image;
}
else if (TextAnalyzer.IsText(_bodyBuffer))
{
this.BodyType = HttpBodyClassification.Text;
}
else
{
this.BodyType = HttpBodyClassification.Binary;
}
}
/// <summary>
/// Generates the MD5 hash for the HTTP body.
/// </summary>
private void GenerateMd5Hash()
{
if (_bodyBuffer == null || _bodyBuffer.Length == 0)
{
this.BodyMd5Hash = string.Empty;
return;
}
using (var hash = MD5.Create())
{
var bytes = hash.ComputeHash(_bodyBuffer);
this.BodyMd5Hash = bytes.ToHexString();
}
}
}
}
| |
#region License
// Copyright (c) 2018, FluentMigrator Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using FluentMigrator.Runner.Initialization;
using Moq;
using Moq.Protected;
using NUnit.Framework;
namespace FluentMigrator.Tests.Unit.Processors
{
[Category("BatchParser")]
public abstract class ProcessorBatchParserTestsBase
{
private const string ConnectionString = "server=this";
private ConnectionState _connectionState;
protected Mock<DbConnection> MockedConnection { get; private set; }
protected Mock<DbProviderFactory> MockedDbProviderFactory { get; private set; }
protected Mock<IConnectionStringAccessor> MockedConnectionStringAccessor { get; private set; }
private List<Mock<DbCommand>> MockedCommands { get; set; }
[SetUp]
public void SetUp()
{
_connectionState = ConnectionState.Closed;
MockedCommands = new List<Mock<DbCommand>>();
MockedConnection = new Mock<DbConnection>();
MockedDbProviderFactory = new Mock<DbProviderFactory>();
MockedConnectionStringAccessor = new Mock<IConnectionStringAccessor>();
MockedConnection.SetupGet(conn => conn.State).Returns(() => _connectionState);
MockedConnection.Setup(conn => conn.Open()).Callback(() => _connectionState = ConnectionState.Open);
MockedConnection.Setup(conn => conn.Close()).Callback(() => _connectionState = ConnectionState.Closed);
MockedConnection.SetupProperty(conn => conn.ConnectionString);
MockedConnection.Protected().Setup("Dispose", ItExpr.IsAny<bool>());
MockedConnectionStringAccessor.SetupGet(a => a.ConnectionString).Returns(ConnectionString);
MockedDbProviderFactory.Setup(factory => factory.CreateConnection())
.Returns(MockedConnection.Object);
MockedDbProviderFactory.Setup(factory => factory.CreateCommand())
.Returns(
() =>
{
var commandMock = new Mock<DbCommand>()
.SetupProperty(cmd => cmd.CommandText);
commandMock.Setup(cmd => cmd.ExecuteNonQuery()).Returns(1);
commandMock.Protected().SetupGet<DbConnection>("DbConnection").Returns(MockedConnection.Object);
commandMock.Protected().SetupSet<DbConnection>("DbConnection", ItExpr.Is<DbConnection>(v => v == MockedConnection.Object));
commandMock.Protected().Setup("Dispose", ItExpr.IsAny<bool>());
MockedCommands.Add(commandMock);
return commandMock.Object;
});
}
[TearDown]
public void TearDown()
{
foreach (var mockedCommand in MockedCommands)
{
mockedCommand.VerifyNoOtherCalls();
}
MockedDbProviderFactory.VerifyNoOtherCalls();
}
[Test]
public void TestOneCommandForMultipleLines()
{
var command = "SELECT 1\nSELECT 2";
using (var processor = CreateProcessor())
{
processor.Execute(command);
}
MockedDbProviderFactory.Verify(factory => factory.CreateConnection());
foreach (var mockedCommand in MockedCommands)
{
MockedDbProviderFactory.Verify(factory => factory.CreateCommand());
mockedCommand.VerifySet(cmd => cmd.Connection = MockedConnection.Object);
mockedCommand.VerifySet(cmd => cmd.CommandText = command);
mockedCommand.Verify(cmd => cmd.ExecuteNonQuery());
mockedCommand.Protected().Verify("Dispose", Times.Exactly(1), ItExpr.IsAny<bool>());
}
MockedConnection.Protected().Verify("Dispose", Times.Exactly(1), ItExpr.IsAny<bool>());
}
[Test]
public void TestThatTwoCommandsGetSeparatedByGo()
{
using (var processor = CreateProcessor())
{
processor.Execute("SELECT 1\nGO\nSELECT 2");
}
MockedDbProviderFactory.Verify(factory => factory.CreateConnection());
for (int index = 0; index < MockedCommands.Count; index++)
{
var command = $"SELECT {index + 1}";
var mockedCommand = MockedCommands[index];
MockedDbProviderFactory.Verify(factory => factory.CreateCommand());
mockedCommand.VerifySet(cmd => cmd.Connection = MockedConnection.Object);
mockedCommand.VerifySet(cmd => cmd.CommandText = command);
mockedCommand.Verify(cmd => cmd.ExecuteNonQuery());
mockedCommand.Protected().Verify("Dispose", Times.Exactly(1), ItExpr.IsAny<bool>());
}
MockedConnection.Protected().Verify("Dispose", Times.Exactly(1), ItExpr.IsAny<bool>());
}
[Test]
public void TestThatTwoCommandsAreNotSeparatedByGoInComment()
{
var command = "SELECT 1\n /* GO */\nSELECT 2";
using (var processor = CreateProcessor())
{
processor.Execute(command);
}
MockedDbProviderFactory.Verify(factory => factory.CreateConnection());
foreach (var mockedCommand in MockedCommands)
{
MockedDbProviderFactory.Verify(factory => factory.CreateCommand());
mockedCommand.VerifySet(cmd => cmd.Connection = MockedConnection.Object);
mockedCommand.VerifySet(cmd => cmd.CommandText = command);
mockedCommand.Verify(cmd => cmd.ExecuteNonQuery());
mockedCommand.Protected().Verify("Dispose", Times.Exactly(1), ItExpr.IsAny<bool>());
}
MockedConnection.Protected().Verify("Dispose", Times.Exactly(1), ItExpr.IsAny<bool>());
}
[Test]
public void TestThatTwoCommandsAreNotSeparatedByGoInString()
{
var command = "SELECT '\nGO\n'\nSELECT 2";
using (var processor = CreateProcessor())
{
processor.Execute(command);
}
MockedDbProviderFactory.Verify(factory => factory.CreateConnection());
foreach (var mockedCommand in MockedCommands)
{
MockedDbProviderFactory.Verify(factory => factory.CreateCommand());
mockedCommand.VerifySet(cmd => cmd.Connection = MockedConnection.Object);
mockedCommand.VerifySet(cmd => cmd.CommandText = command);
mockedCommand.Verify(cmd => cmd.ExecuteNonQuery());
mockedCommand.Protected().Verify("Dispose", Times.Exactly(1), ItExpr.IsAny<bool>());
}
MockedConnection.Protected().Verify("Dispose", Times.Exactly(1), ItExpr.IsAny<bool>());
}
[Test]
public void Issue442()
{
var command = "SELECT '\n\n\n';\nSELECT 2;";
using (var processor = CreateProcessor())
{
processor.Execute(command);
}
MockedDbProviderFactory.Verify(factory => factory.CreateConnection());
foreach (var mockedCommand in MockedCommands)
{
MockedDbProviderFactory.Verify(factory => factory.CreateCommand());
mockedCommand.VerifySet(cmd => cmd.Connection = MockedConnection.Object);
mockedCommand.VerifySet(cmd => cmd.CommandText = command);
mockedCommand.Verify(cmd => cmd.ExecuteNonQuery());
mockedCommand.Protected().Verify("Dispose", Times.Exactly(1), ItExpr.IsAny<bool>());
}
MockedConnection.Protected().Verify("Dispose", Times.Exactly(1), ItExpr.IsAny<bool>());
}
[Test]
public void Issue842()
{
var command = @"insert into MyTable (Id, Data)\nvalues (42, 'This is a list of games played by people\n\nDooM\nPokemon GO\nPotato-o-matic');";
using (var processor = CreateProcessor())
{
processor.Execute(command);
}
MockedDbProviderFactory.Verify(factory => factory.CreateConnection());
foreach (var mockedCommand in MockedCommands)
{
MockedDbProviderFactory.Verify(factory => factory.CreateCommand());
mockedCommand.VerifySet(cmd => cmd.Connection = MockedConnection.Object);
mockedCommand.VerifySet(cmd => cmd.CommandText = command);
mockedCommand.Verify(cmd => cmd.ExecuteNonQuery());
mockedCommand.Protected().Verify("Dispose", Times.Exactly(1), ItExpr.IsAny<bool>());
}
MockedConnection.Protected().Verify("Dispose", Times.Exactly(1), ItExpr.IsAny<bool>());
}
[Test]
public void TestThatGoWithRunCount()
{
using (var processor = CreateProcessor())
{
processor.Execute("SELECT 1\nGO 3\nSELECT 2\nGO\nSELECT 3\nGO 2");
}
var expected = new (string command, int count)[]
{
("SELECT 1", 3),
("SELECT 2", 1),
("SELECT 3", 2),
};
Assert.AreEqual(expected.Length, MockedCommands.Count);
MockedDbProviderFactory.Verify(factory => factory.CreateConnection());
for (var index = 0; index < MockedCommands.Count; index++)
{
var (command, count) = expected[index];
var mockedCommand = MockedCommands[index];
MockedDbProviderFactory.Verify(factory => factory.CreateCommand());
mockedCommand.VerifySet(cmd => cmd.Connection = MockedConnection.Object);
mockedCommand.VerifySet(cmd => cmd.CommandText = command);
mockedCommand.Verify(cmd => cmd.ExecuteNonQuery(), Times.Exactly(count));
mockedCommand.Protected().Verify("Dispose", Times.Exactly(1), ItExpr.IsAny<bool>());
}
MockedConnection.Protected().Verify("Dispose", Times.Exactly(1), ItExpr.IsAny<bool>());
}
protected abstract IMigrationProcessor CreateProcessor();
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32.SafeHandles;
namespace Internal.Cryptography.Pal
{
internal sealed class OpenSslX509ChainProcessor : IChainPal
{
// Constructed (0x20) | Sequence (0x10) => 0x30.
private const uint ConstructedSequenceTagId = 0x30;
public void Dispose()
{
}
public bool? Verify(X509VerificationFlags flags, out Exception exception)
{
exception = null;
return ChainVerifier.Verify(ChainElements, flags);
}
public X509ChainElement[] ChainElements { get; private set; }
public X509ChainStatus[] ChainStatus { get; private set; }
public SafeX509ChainHandle SafeHandle
{
get { return null; }
}
public static IChainPal BuildChain(
X509Certificate2 leaf,
HashSet<X509Certificate2> candidates,
HashSet<X509Certificate2> systemTrusted,
OidCollection applicationPolicy,
OidCollection certificatePolicy,
X509RevocationMode revocationMode,
X509RevocationFlag revocationFlag,
DateTime verificationTime,
ref TimeSpan remainingDownloadTime)
{
X509ChainElement[] elements;
List<X509ChainStatus> overallStatus = new List<X509ChainStatus>();
WorkingChain workingChain = new WorkingChain();
Interop.Crypto.X509StoreVerifyCallback workingCallback = workingChain.VerifyCallback;
// An X509_STORE is more comparable to Cryptography.X509Certificate2Collection than to
// Cryptography.X509Store. So read this with OpenSSL eyes, not CAPI/CNG eyes.
//
// (If you need to think of it as an X509Store, it's a volatile memory store)
using (SafeX509StoreHandle store = Interop.Crypto.X509StoreCreate())
using (SafeX509StoreCtxHandle storeCtx = Interop.Crypto.X509StoreCtxCreate())
using (SafeX509StackHandle extraCerts = Interop.Crypto.NewX509Stack())
{
Interop.Crypto.CheckValidOpenSslHandle(store);
Interop.Crypto.CheckValidOpenSslHandle(storeCtx);
Interop.Crypto.CheckValidOpenSslHandle(extraCerts);
bool lookupCrl = revocationMode != X509RevocationMode.NoCheck;
foreach (X509Certificate2 cert in candidates)
{
OpenSslX509CertificateReader pal = (OpenSslX509CertificateReader)cert.Pal;
using (SafeX509Handle handle = Interop.Crypto.X509UpRef(pal.SafeHandle))
{
if (!Interop.Crypto.PushX509StackField(extraCerts, handle))
{
throw Interop.Crypto.CreateOpenSslCryptographicException();
}
// Ownership was transferred to the cert stack.
handle.SetHandleAsInvalid();
}
if (lookupCrl)
{
CrlCache.AddCrlForCertificate(
cert,
store,
revocationMode,
verificationTime,
ref remainingDownloadTime);
// If we only wanted the end-entity certificate CRL then don't look up
// any more of them.
lookupCrl = revocationFlag != X509RevocationFlag.EndCertificateOnly;
}
}
if (revocationMode != X509RevocationMode.NoCheck)
{
if (!Interop.Crypto.X509StoreSetRevocationFlag(store, revocationFlag))
{
throw Interop.Crypto.CreateOpenSslCryptographicException();
}
}
foreach (X509Certificate2 trustedCert in systemTrusted)
{
OpenSslX509CertificateReader pal = (OpenSslX509CertificateReader)trustedCert.Pal;
if (!Interop.Crypto.X509StoreAddCert(store, pal.SafeHandle))
{
throw Interop.Crypto.CreateOpenSslCryptographicException();
}
}
SafeX509Handle leafHandle = ((OpenSslX509CertificateReader)leaf.Pal).SafeHandle;
if (!Interop.Crypto.X509StoreCtxInit(storeCtx, store, leafHandle, extraCerts))
{
throw Interop.Crypto.CreateOpenSslCryptographicException();
}
Interop.Crypto.X509StoreCtxSetVerifyCallback(storeCtx, workingCallback);
Interop.Crypto.SetX509ChainVerifyTime(storeCtx, verificationTime);
int verify = Interop.Crypto.X509VerifyCert(storeCtx);
if (verify < 0)
{
throw Interop.Crypto.CreateOpenSslCryptographicException();
}
// Because our callback tells OpenSSL that every problem is ignorable, it should tell us that the
// chain is just fine (unless it returned a negative code for an exception)
Debug.Assert(verify == 1, "verify == 1");
using (SafeX509StackHandle chainStack = Interop.Crypto.X509StoreCtxGetChain(storeCtx))
{
int chainSize = Interop.Crypto.GetX509StackFieldCount(chainStack);
elements = new X509ChainElement[chainSize];
int maybeRootDepth = chainSize - 1;
// The leaf cert is 0, up to (maybe) the root at chainSize - 1
for (int i = 0; i < chainSize; i++)
{
List<X509ChainStatus> status = new List<X509ChainStatus>();
List<Interop.Crypto.X509VerifyStatusCode> elementErrors =
i < workingChain.Errors.Count ? workingChain.Errors[i] : null;
if (elementErrors != null)
{
AddElementStatus(elementErrors, status, overallStatus);
}
IntPtr elementCertPtr = Interop.Crypto.GetX509StackField(chainStack, i);
if (elementCertPtr == IntPtr.Zero)
{
throw Interop.Crypto.CreateOpenSslCryptographicException();
}
// Duplicate the certificate handle
X509Certificate2 elementCert = new X509Certificate2(elementCertPtr);
elements[i] = new X509ChainElement(elementCert, status.ToArray(), "");
}
}
}
GC.KeepAlive(workingCallback);
if ((certificatePolicy != null && certificatePolicy.Count > 0) ||
(applicationPolicy != null && applicationPolicy.Count > 0))
{
List<X509Certificate2> certsToRead = new List<X509Certificate2>();
foreach (X509ChainElement element in elements)
{
certsToRead.Add(element.Certificate);
}
CertificatePolicyChain policyChain = new CertificatePolicyChain(certsToRead);
bool failsPolicyChecks = false;
if (certificatePolicy != null)
{
if (!policyChain.MatchesCertificatePolicies(certificatePolicy))
{
failsPolicyChecks = true;
}
}
if (applicationPolicy != null)
{
if (!policyChain.MatchesApplicationPolicies(applicationPolicy))
{
failsPolicyChecks = true;
}
}
if (failsPolicyChecks)
{
X509ChainElement leafElement = elements[0];
X509ChainStatus chainStatus = new X509ChainStatus
{
Status = X509ChainStatusFlags.NotValidForUsage,
StatusInformation = SR.Chain_NoPolicyMatch,
};
var elementStatus = new List<X509ChainStatus>(leafElement.ChainElementStatus.Length + 1);
elementStatus.AddRange(leafElement.ChainElementStatus);
AddUniqueStatus(elementStatus, ref chainStatus);
AddUniqueStatus(overallStatus, ref chainStatus);
elements[0] = new X509ChainElement(
leafElement.Certificate,
elementStatus.ToArray(),
leafElement.Information);
}
}
return new OpenSslX509ChainProcessor
{
ChainStatus = overallStatus.ToArray(),
ChainElements = elements,
};
}
private static void AddElementStatus(
List<Interop.Crypto.X509VerifyStatusCode> errorCodes,
List<X509ChainStatus> elementStatus,
List<X509ChainStatus> overallStatus)
{
foreach (var errorCode in errorCodes)
{
AddElementStatus(errorCode, elementStatus, overallStatus);
}
}
private static void AddElementStatus(
Interop.Crypto.X509VerifyStatusCode errorCode,
List<X509ChainStatus> elementStatus,
List<X509ChainStatus> overallStatus)
{
X509ChainStatusFlags statusFlag = MapVerifyErrorToChainStatus(errorCode);
Debug.Assert(
(statusFlag & (statusFlag - 1)) == 0,
"Status flag has more than one bit set",
"More than one bit is set in status '{0}' for error code '{1}'",
statusFlag,
errorCode);
foreach (X509ChainStatus currentStatus in elementStatus)
{
if ((currentStatus.Status & statusFlag) != 0)
{
return;
}
}
X509ChainStatus chainStatus = new X509ChainStatus
{
Status = statusFlag,
StatusInformation = Interop.Crypto.GetX509VerifyCertErrorString(errorCode),
};
elementStatus.Add(chainStatus);
AddUniqueStatus(overallStatus, ref chainStatus);
}
private static void AddUniqueStatus(IList<X509ChainStatus> list, ref X509ChainStatus status)
{
X509ChainStatusFlags statusCode = status.Status;
for (int i = 0; i < list.Count; i++)
{
if (list[i].Status == statusCode)
{
return;
}
}
list.Add(status);
}
private static X509ChainStatusFlags MapVerifyErrorToChainStatus(Interop.Crypto.X509VerifyStatusCode code)
{
switch (code)
{
case Interop.Crypto.X509VerifyStatusCode.X509_V_OK:
return X509ChainStatusFlags.NoError;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_NOT_YET_VALID:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_HAS_EXPIRED:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
return X509ChainStatusFlags.NotTimeValid;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_REVOKED:
return X509ChainStatusFlags.Revoked;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_SIGNATURE_FAILURE:
return X509ChainStatusFlags.NotSignatureValid;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_UNTRUSTED:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
return X509ChainStatusFlags.UntrustedRoot;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CRL_HAS_EXPIRED:
return X509ChainStatusFlags.OfflineRevocation;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CRL_NOT_YET_VALID:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CRL_SIGNATURE_FAILURE:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_KEYUSAGE_NO_CRL_SIGN:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_CRL:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION:
return X509ChainStatusFlags.RevocationStatusUnknown;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_INVALID_EXTENSION:
return X509ChainStatusFlags.InvalidExtension;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
return X509ChainStatusFlags.PartialChain;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_INVALID_PURPOSE:
return X509ChainStatusFlags.NotValidForUsage;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_INVALID_CA:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_INVALID_NON_CA:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_PATH_LENGTH_EXCEEDED:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_KEYUSAGE_NO_CERTSIGN:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE:
return X509ChainStatusFlags.InvalidBasicConstraints;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_INVALID_POLICY_EXTENSION:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_NO_EXPLICIT_POLICY:
return X509ChainStatusFlags.InvalidPolicyConstraints;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_REJECTED:
return X509ChainStatusFlags.ExplicitDistrust;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION:
return X509ChainStatusFlags.HasNotSupportedCriticalExtension;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_CHAIN_TOO_LONG:
throw new CryptographicException();
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_OUT_OF_MEM:
throw new OutOfMemoryException();
default:
Debug.Fail("Unrecognized X509VerifyStatusCode:" + code);
throw new CryptographicException();
}
}
internal static HashSet<X509Certificate2> FindCandidates(
X509Certificate2 leaf,
X509Certificate2Collection extraStore,
HashSet<X509Certificate2> downloaded,
HashSet<X509Certificate2> systemTrusted,
ref TimeSpan remainingDownloadTime)
{
var candidates = new HashSet<X509Certificate2>();
var toProcess = new Queue<X509Certificate2>();
toProcess.Enqueue(leaf);
using (var systemRootStore = new X509Store(StoreName.Root, StoreLocation.LocalMachine))
using (var systemIntermediateStore = new X509Store(StoreName.CertificateAuthority, StoreLocation.LocalMachine))
using (var userRootStore = new X509Store(StoreName.Root, StoreLocation.CurrentUser))
using (var userIntermediateStore = new X509Store(StoreName.CertificateAuthority, StoreLocation.CurrentUser))
{
systemRootStore.Open(OpenFlags.ReadOnly);
systemIntermediateStore.Open(OpenFlags.ReadOnly);
userRootStore.Open(OpenFlags.ReadOnly);
userIntermediateStore.Open(OpenFlags.ReadOnly);
X509Certificate2Collection systemRootCerts = systemRootStore.Certificates;
X509Certificate2Collection systemIntermediateCerts = systemIntermediateStore.Certificates;
X509Certificate2Collection userRootCerts = userRootStore.Certificates;
X509Certificate2Collection userIntermediateCerts = userIntermediateStore.Certificates;
// fill the system trusted collection
foreach (X509Certificate2 userRootCert in userRootCerts)
{
if (!systemTrusted.Add(userRootCert))
{
// If we have already (effectively) added another instance of this certificate,
// then this one provides no value. A Disposed cert won't harm the matching logic.
userRootCert.Dispose();
}
}
foreach (X509Certificate2 systemRootCert in systemRootCerts)
{
if (!systemTrusted.Add(systemRootCert))
{
// If we have already (effectively) added another instance of this certificate,
// (for example, because another copy of it was in the user store)
// then this one provides no value. A Disposed cert won't harm the matching logic.
systemRootCert.Dispose();
}
}
X509Certificate2Collection[] storesToCheck =
{
extraStore,
userIntermediateCerts,
systemIntermediateCerts,
userRootCerts,
systemRootCerts,
};
while (toProcess.Count > 0)
{
X509Certificate2 current = toProcess.Dequeue();
candidates.Add(current);
HashSet<X509Certificate2> results = FindIssuer(
current,
storesToCheck,
downloaded,
ref remainingDownloadTime);
if (results != null)
{
foreach (X509Certificate2 result in results)
{
if (!candidates.Contains(result))
{
toProcess.Enqueue(result);
}
}
}
}
// Avoid sending unused certs into the finalizer queue by doing only a ref check
var candidatesByReference = new HashSet<X509Certificate2>(
candidates,
ReferenceEqualityComparer<X509Certificate2>.Instance);
// Certificates come from 5 sources:
// 1) extraStore.
// These are cert objects that are provided by the user, we shouldn't dispose them.
// 2) the machine root store
// These certs are moving on to the "was I a system trust?" test, and we shouldn't dispose them.
// 3) the user root store
// These certs are moving on to the "was I a system trust?" test, and we shouldn't dispose them.
// 4) the machine intermediate store
// These certs were either path candidates, or not. If they were, don't dispose them. Otherwise do.
// 5) the user intermediate store
// These certs were either path candidates, or not. If they were, don't dispose them. Otherwise do.
DisposeUnreferenced(candidatesByReference, systemIntermediateCerts);
DisposeUnreferenced(candidatesByReference, userIntermediateCerts);
}
return candidates;
}
private static void DisposeUnreferenced(
ISet<X509Certificate2> referencedSet,
X509Certificate2Collection storeCerts)
{
foreach (X509Certificate2 cert in storeCerts)
{
if (!referencedSet.Contains(cert))
{
cert.Dispose();
}
}
}
private static HashSet<X509Certificate2> FindIssuer(
X509Certificate2 cert,
X509Certificate2Collection[] stores,
HashSet<X509Certificate2> downloadedCerts,
ref TimeSpan remainingDownloadTime)
{
if (IsSelfSigned(cert))
{
// It's a root cert, we won't make any progress.
return null;
}
SafeX509Handle certHandle = ((OpenSslX509CertificateReader)cert.Pal).SafeHandle;
foreach (X509Certificate2Collection store in stores)
{
HashSet<X509Certificate2> fromStore = null;
foreach (X509Certificate2 candidate in store)
{
var certPal = (OpenSslX509CertificateReader)candidate.Pal;
if (certPal == null)
{
continue;
}
SafeX509Handle candidateHandle = certPal.SafeHandle;
int issuerError = Interop.Crypto.X509CheckIssued(candidateHandle, certHandle);
if (issuerError == 0)
{
if (fromStore == null)
{
fromStore = new HashSet<X509Certificate2>();
}
fromStore.Add(candidate);
}
}
if (fromStore != null)
{
return fromStore;
}
}
byte[] authorityInformationAccess = null;
foreach (X509Extension extension in cert.Extensions)
{
if (StringComparer.Ordinal.Equals(extension.Oid.Value, Oids.AuthorityInformationAccess))
{
// If there's an Authority Information Access extension, it might be used for
// looking up additional certificates for the chain.
authorityInformationAccess = extension.RawData;
break;
}
}
if (authorityInformationAccess != null)
{
X509Certificate2 downloaded = DownloadCertificate(
authorityInformationAccess,
ref remainingDownloadTime);
if (downloaded != null)
{
downloadedCerts.Add(downloaded);
return new HashSet<X509Certificate2>() { downloaded };
}
}
return null;
}
private static bool IsSelfSigned(X509Certificate2 cert)
{
return StringComparer.Ordinal.Equals(cert.Subject, cert.Issuer);
}
private static X509Certificate2 DownloadCertificate(
byte[] authorityInformationAccess,
ref TimeSpan remainingDownloadTime)
{
// Don't do any work if we're over limit.
if (remainingDownloadTime <= TimeSpan.Zero)
{
return null;
}
string uri = FindHttpAiaRecord(authorityInformationAccess, Oids.CertificateAuthorityIssuers);
if (uri == null)
{
return null;
}
return CertificateAssetDownloader.DownloadCertificate(uri, ref remainingDownloadTime);
}
internal static string FindHttpAiaRecord(byte[] authorityInformationAccess, string recordTypeOid)
{
DerSequenceReader reader = new DerSequenceReader(authorityInformationAccess);
while (reader.HasData)
{
DerSequenceReader innerReader = reader.ReadSequence();
// If the sequence's first element is a sequence, unwrap it.
if (innerReader.PeekTag() == ConstructedSequenceTagId)
{
innerReader = innerReader.ReadSequence();
}
Oid oid = innerReader.ReadOid();
if (StringComparer.Ordinal.Equals(oid.Value, recordTypeOid))
{
string uri = innerReader.ReadIA5String();
Uri parsedUri;
if (!Uri.TryCreate(uri, UriKind.Absolute, out parsedUri))
{
continue;
}
if (!StringComparer.Ordinal.Equals(parsedUri.Scheme, "http"))
{
continue;
}
return uri;
}
}
return null;
}
private class WorkingChain
{
internal readonly List<List<Interop.Crypto.X509VerifyStatusCode>> Errors =
new List<List<Interop.Crypto.X509VerifyStatusCode>>();
internal int VerifyCallback(int ok, IntPtr ctx)
{
if (ok != 0)
{
return ok;
}
try
{
using (var storeCtx = new SafeX509StoreCtxHandle(ctx, ownsHandle: false))
{
Interop.Crypto.X509VerifyStatusCode errorCode = Interop.Crypto.X509StoreCtxGetError(storeCtx);
int errorDepth = Interop.Crypto.X509StoreCtxGetErrorDepth(storeCtx);
// We don't report "OK" as an error.
// For compatibility with Windows / .NET Framework, do not report X509_V_CRL_NOT_YET_VALID.
if (errorCode != Interop.Crypto.X509VerifyStatusCode.X509_V_OK &&
errorCode != Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CRL_NOT_YET_VALID)
{
while (Errors.Count <= errorDepth)
{
Errors.Add(null);
}
if (Errors[errorDepth] == null)
{
Errors[errorDepth] = new List<Interop.Crypto.X509VerifyStatusCode>();
}
Errors[errorDepth].Add(errorCode);
}
}
return 1;
}
catch
{
return -1;
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.Linq;
using System.Reflection.Emit;
using System.Reflection.Metadata.Cil.Instructions;
using System.Reflection.Metadata.Decoding;
using System.Reflection.Metadata.Ecma335;
using System.Text;
namespace System.Reflection.Metadata.Cil.Decoder
{
public struct CilDecoder
{
#region Public APIs
/// <summary>
/// Method that given a token defines if it is a type reference token.
/// </summary>
/// <param name="token">token to solve</param>
/// <returns>true if is a type reference false if not</returns>
public static bool IsTypeReference(int token)
{
return GetTokenType(token) == CilTokenType.TypeReference;
}
/// <summary>
/// Method that given a token defines if it is a type definition token.
/// </summary>
/// <param name="token">token to solve</param>
/// <returns>true if is a type definition false if not</returns>
public static bool IsTypeDefinition(int token)
{
return GetTokenType(token) == CilTokenType.TypeDefinition;
}
/// <summary>
/// Method that given a token defines if it is a user string token.
/// </summary>
/// <param name="token">token to solve</param>
/// <returns>true if is a user string false if not</returns>
public static bool IsUserString(int token)
{
return GetTokenType(token) == CilTokenType.UserString;
}
/// <summary>
/// Method that given a token defines if it is a member reference token.
/// </summary>
/// <param name="token">token to solve</param>
/// <returns>true if is a member reference false if not</returns>
public static bool IsMemberReference(int token)
{
return GetTokenType(token) == CilTokenType.MemberReference;
}
/// <summary>
/// Method that given a token defines if it is a method specification token.
/// </summary>
/// <param name="token">token to solve</param>
/// <returns>true if is a method specification false if not</returns>
public static bool IsMethodSpecification(int token)
{
return GetTokenType(token) == CilTokenType.MethodSpecification;
}
/// <summary>
/// Method that given a token defines if it is a method definition token.
/// </summary>
/// <param name="token">token to solve</param>
/// <returns>true if is a method definition false if not</returns>
public static bool IsMethodDefinition(int token)
{
return GetTokenType(token) == CilTokenType.MethodDefinition;
}
/// <summary>
/// Method that given a token defines if it is a field definition token.
/// </summary>
/// <param name="token">token to solve</param>
/// <returns>true if is a field definition false if not</returns>
public static bool IsFieldDefinition(int token)
{
return GetTokenType(token) == CilTokenType.FieldDefinition;
}
/// <summary>
/// Method that given a token defines if it is a type specification token.
/// </summary>
/// <param name="token">token to solve</param>
/// <returns>true if is a type specification false if not</returns>
public static bool IsTypeSpecification(int token)
{
return GetTokenType(token) == CilTokenType.TypeSpecification;
}
/// <summary>
/// Method that given a token defines if it is a standalone signature token.
/// </summary>
/// <param name="token">token to solve</param>
/// <returns>true if is a standalone signature false if not</returns>
public static bool IsStandaloneSignature(int token)
{
return GetTokenType(token) == CilTokenType.Signature;
}
public static string CreateByteArrayString(byte[] array)
{
if (array.Length == 0) return "()";
char[] chars = new char[3 + 3 * array.Length]; //3 equals for parenthesis and first space, 3 for 1 (space) + 2(byte).
int i = 0;
chars[i++] = '(';
chars[i++] = ' ';
foreach(byte b in array)
{
chars[i++] = HexadecimalNibble((byte)(b >> 4)); //get every byte char in Hex X2 representation.
chars[i++] = HexadecimalNibble((byte)(b & 0xF));
chars[i++] = ' ';
}
chars[i++] = ')';
return new string(chars);
}
public static string CreateVersionString(Version version)
{
int build = version.Build;
int revision = version.Revision;
if (build == -1) build = 0;
if (revision == -1) revision = 0;
return String.Format("{0}:{1}:{2}:{3}", version.Major.ToString(), version.Minor.ToString(), build.ToString(), revision.ToString());
}
public static string DecodeSignatureParamerTypes(MethodSignature<CilType> signature)
{
StringBuilder sb = new StringBuilder();
sb.Append('(');
var types = signature.ParameterTypes;
for (int i = 0; i < types.Length; i++)
{
if (i > 0)
{
sb.Append(',');
}
sb.Append(types[i].ToString());
}
sb.Append(')');
return sb.ToString();
}
internal static CilEntity DecodeEntityHandle(EntityHandle handle, ref CilReaders readers)
{
if (handle.Kind == HandleKind.TypeDefinition)
{
TypeDefinition definition = readers.MdReader.GetTypeDefinition((TypeDefinitionHandle)handle);
int token = MetadataTokens.GetToken(handle);
CilTypeDefinition type = CilTypeDefinition.Create(definition, ref readers, token);
return new CilEntity(type, EntityKind.TypeDefinition);
}
if (handle.Kind == HandleKind.TypeSpecification)
{
TypeSpecification specification = readers.MdReader.GetTypeSpecification((TypeSpecificationHandle)handle);
CilTypeSpecification type = CilTypeSpecification.Create(specification, ref readers);
return new CilEntity(type, EntityKind.TypeSpecification);
}
if (handle.Kind == HandleKind.TypeReference)
{
TypeReference reference = readers.MdReader.GetTypeReference((TypeReferenceHandle)handle);
int token = MetadataTokens.GetToken(handle);
CilTypeReference type = CilTypeReference.Create(reference, ref readers, token);
return new CilEntity(type, EntityKind.TypeReference);
}
throw new BadImageFormatException("Event definition type must be either type reference, type definition or type specification");
}
public static MethodSignature<CilType> DecodeMethodSignature(MethodDefinition methodDefinition, CilTypeProvider provider)
{
return SignatureDecoder.DecodeMethodSignature(methodDefinition.Signature, provider);
}
public static IEnumerable<CilInstruction> DecodeMethodBody(CilMethodDefinition methodDefinition)
{
return DecodeMethodBody(methodDefinition.IlReader, methodDefinition._readers.MdReader, methodDefinition.Provider, methodDefinition);
}
#endregion
#region Private and internal helpers
internal static bool HasArgument(OpCode opCode)
{
bool isLoad = opCode == OpCodes.Ldarg || opCode == OpCodes.Ldarga || opCode == OpCodes.Ldarga_S || opCode == OpCodes.Ldarg_S;
bool isStore = opCode == OpCodes.Starg_S || opCode == OpCodes.Starg;
return isLoad || isStore;
}
private static IEnumerable<CilInstruction> DecodeMethodBody(BlobReader ilReader, MetadataReader metadataReader, CilTypeProvider provider, CilMethodDefinition methodDefinition)
{
ilReader.Reset();
int intOperand;
ushort shortOperand;
int ilOffset = 0;
CilInstruction instruction = null;
while (ilReader.Offset < ilReader.Length)
{
OpCode opCode;
int expectedSize;
byte _byte = ilReader.ReadByte();
/*If the byte read is 0xfe it means is a two byte instruction,
so since it is going to read the second byte to get the actual
instruction it has to check that the offset is still less than the length.*/
if (_byte == 0xfe && ilReader.Offset < ilReader.Length)
{
opCode = CilDecoderHelpers.Instance.twoByteOpCodes[ilReader.ReadByte()];
expectedSize = 2;
}
else
{
opCode = CilDecoderHelpers.Instance.oneByteOpCodes[_byte];
expectedSize = 1;
}
switch (opCode.OperandType)
{
//The instruction size is the expected size (1 or 2 depending if it is a one or two byte instruction) + the size of the operand.
case OperandType.InlineField:
intOperand = ilReader.ReadInt32();
string fieldInfo = GetFieldInformation(metadataReader, intOperand, provider);
instruction = new CilStringInstruction(opCode, fieldInfo, intOperand, expectedSize + (int)CilInstructionSize.Int32);
break;
case OperandType.InlineString:
intOperand = ilReader.ReadInt32();
bool isPrintable;
string str = GetArgumentString(metadataReader, intOperand, out isPrintable);
instruction = new CilStringInstruction(opCode, str, intOperand, expectedSize + (int)CilInstructionSize.Int32, isPrintable);
break;
case OperandType.InlineMethod:
intOperand = ilReader.ReadInt32();
string methodCall = SolveMethodName(metadataReader, intOperand, provider);
instruction = new CilStringInstruction(opCode, methodCall, intOperand, expectedSize + (int)CilInstructionSize.Int32);
break;
case OperandType.InlineType:
intOperand = ilReader.ReadInt32();
string type = GetTypeInformation(metadataReader, intOperand, provider);
instruction = new CilStringInstruction(opCode, type, intOperand, expectedSize + (int)CilInstructionSize.Int32);
break;
case OperandType.InlineTok:
intOperand = ilReader.ReadInt32();
string tokenType = GetInlineTokenType(metadataReader, intOperand, provider);
instruction = new CilStringInstruction(opCode, tokenType, intOperand, expectedSize + (int)CilInstructionSize.Int32);
break;
case OperandType.InlineI:
instruction = new CilInt32Instruction(opCode, ilReader.ReadInt32(), -1, expectedSize + (int)CilInstructionSize.Int32);
break;
case OperandType.InlineI8:
instruction = new CilInt64Instruction(opCode, ilReader.ReadInt64(), -1, expectedSize + (int)CilInstructionSize.Int64);
break;
case OperandType.InlineR:
instruction = new CilDoubleInstruction(opCode, ilReader.ReadDouble(), -1, expectedSize + (int)CilInstructionSize.Double);
break;
case OperandType.InlineSwitch:
instruction = CreateSwitchInstruction(ref ilReader, expectedSize, ilOffset, opCode);
break;
case OperandType.ShortInlineBrTarget:
instruction = new CilInt16BranchInstruction(opCode, ilReader.ReadSByte(), ilOffset, expectedSize + (int)CilInstructionSize.Byte);
break;
case OperandType.InlineBrTarget:
instruction = new CilBranchInstruction(opCode, ilReader.ReadInt32(), ilOffset, expectedSize + (int)CilInstructionSize.Int32);
break;
case OperandType.ShortInlineI:
instruction = new CilByteInstruction(opCode, ilReader.ReadByte(), -1, expectedSize + (int)CilInstructionSize.Byte);
break;
case OperandType.ShortInlineR:
instruction = new CilSingleInstruction(opCode, ilReader.ReadSingle(), -1, expectedSize + (int)CilInstructionSize.Single);
break;
case OperandType.InlineNone:
instruction = new CilInstructionWithNoValue(opCode, expectedSize);
break;
case OperandType.ShortInlineVar:
byte token = ilReader.ReadByte();
instruction = new CilInt16VariableInstruction(opCode, GetVariableName(opCode, token, methodDefinition), token, expectedSize + (int)CilInstructionSize.Byte);
break;
case OperandType.InlineVar:
shortOperand = ilReader.ReadUInt16();
instruction = new CilVariableInstruction(opCode, GetVariableName(opCode, shortOperand, methodDefinition), shortOperand, expectedSize + (int)CilInstructionSize.Int16);
break;
case OperandType.InlineSig:
intOperand = ilReader.ReadInt32();
instruction = new CilStringInstruction(opCode, GetSignature(metadataReader, intOperand, provider), intOperand, expectedSize + (int)CilInstructionSize.Int32);
break;
default:
break;
}
ilOffset += instruction.Size;
yield return instruction;
}
}
internal static CilLocal[] DecodeLocalSignature(MethodBodyBlock methodBody, MetadataReader metadataReader, CilTypeProvider provider)
{
if (methodBody.LocalSignature.IsNil)
{
return new CilLocal[0];
}
ImmutableArray<CilType> localTypes = SignatureDecoder.DecodeLocalSignature(methodBody.LocalSignature, provider);
CilLocal[] locals = new CilLocal[localTypes.Length];
for (int i = 0; i < localTypes.Length; i++)
{
string name = "V_" + i;
locals[i] = new CilLocal(name, localTypes[i].ToString());
}
return locals;
}
internal static CilParameter[] DecodeParameters(MethodSignature<CilType> signature, ParameterHandleCollection parameters, ref CilReaders readers)
{
ImmutableArray<CilType> types = signature.ParameterTypes;
int requiredCount = Math.Min(signature.RequiredParameterCount, types.Length);
if (requiredCount == 0)
{
return new CilParameter[0];
}
CilParameter[] result = new CilParameter[requiredCount];
for (int i = 0; i < requiredCount; i++)
{
var parameter = readers.MdReader.GetParameter(parameters.ElementAt(i));
result[i] = CilParameter.Create(parameter, ref readers, types[i].ToString());
}
return result;
}
internal static IEnumerable<string> DecodeGenericParameters(MethodDefinition methodDefinition, CilMethodDefinition method)
{
foreach (var handle in methodDefinition.GetGenericParameters())
{
var parameter = method._readers.MdReader.GetGenericParameter(handle);
yield return method._readers.MdReader.GetString(parameter.Name);
}
}
internal static CilType DecodeType(EntityHandle type, CilTypeProvider provider)
{
return SignatureDecoder.DecodeType(type, provider, null);
}
private static string GetSignature(MetadataReader metadataReader, int intOperand, CilTypeProvider provider)
{
if (IsStandaloneSignature(intOperand))
{
var handle = MetadataTokens.StandaloneSignatureHandle(intOperand);
var standaloneSignature = metadataReader.GetStandaloneSignature(handle);
var signature = SignatureDecoder.DecodeMethodSignature(standaloneSignature.Signature, provider);
return string.Format("{0}{1}", GetMethodReturnType(signature), provider.GetParameterList(signature));
}
throw new ArgumentException("Get signature invalid token");
}
private static string GetVariableName(OpCode opCode, int token, CilMethodDefinition methodDefinition)
{
if (HasArgument(opCode))
{
if (methodDefinition.Signature.Header.IsInstance)
{
token--; //the first parameter is "this".
}
return methodDefinition.GetParameter(token).Name;
}
return methodDefinition.GetLocal(token).Name;
}
private static string GetInlineTokenType(MetadataReader metadataReader, int intOperand, CilTypeProvider provider)
{
if (IsMethodDefinition(intOperand) || IsMethodSpecification(intOperand) || IsMemberReference(intOperand))
{
return "method " + SolveMethodName(metadataReader, intOperand, provider);
}
if (IsFieldDefinition(intOperand))
{
return "field " + GetFieldInformation(metadataReader, intOperand, provider);
}
return GetTypeInformation(metadataReader, intOperand, provider);
}
private static string GetTypeInformation(MetadataReader metadataReader, int intOperand, CilTypeProvider provider)
{
if (IsTypeReference(intOperand))
{
var refHandle = MetadataTokens.TypeReferenceHandle(intOperand);
return SignatureDecoder.DecodeType(refHandle, provider, null).ToString();
}
if (IsTypeSpecification(intOperand))
{
var typeHandle = MetadataTokens.TypeSpecificationHandle(intOperand);
return SignatureDecoder.DecodeType(typeHandle, provider, null).ToString();
}
var defHandle = MetadataTokens.TypeDefinitionHandle(intOperand);
return SignatureDecoder.DecodeType(defHandle, provider, null).ToString();
}
private static CilInstruction CreateSwitchInstruction(ref BlobReader ilReader, int expectedSize, int ilOffset, OpCode opCode)
{
uint caseNumber = ilReader.ReadUInt32();
int[] jumps = new int[caseNumber];
for (int i = 0; i < caseNumber; i++)
{
jumps[i] = ilReader.ReadInt32();
}
int size = (int)CilInstructionSize.Int32 + expectedSize;
size += (int)caseNumber * (int)CilInstructionSize.Int32;
return new CilSwitchInstruction(opCode, ilOffset, jumps, (int)caseNumber, caseNumber, size);
}
private static string GetArgumentString(MetadataReader metadataReader, int intOperand, out bool isPrintable)
{
if (IsUserString(intOperand))
{
UserStringHandle usrStr = MetadataTokens.UserStringHandle(intOperand);
var str = metadataReader.GetUserString(usrStr);
str = ProcessAndNormalizeString(str, out isPrintable);
return str;
}
throw new ArgumentException("Invalid argument, must be a user string metadata token.");
}
private static string ProcessAndNormalizeString(string str, out bool isPrintable)
{
foreach (char c in str)
{
UnicodeCategory category = CharUnicodeInfo.GetUnicodeCategory(c);
if (category == UnicodeCategory.Control || category == UnicodeCategory.OtherNotAssigned || category == UnicodeCategory.OtherSymbol || c == '"')
{
byte[] bytes = Encoding.Unicode.GetBytes(str);
isPrintable = false;
return string.Format("bytearray{0}", CreateByteArrayString(bytes));
}
}
isPrintable = true;
return str;
}
private static string GetMethodReturnType(MethodSignature<CilType> signature)
{
string returnTypeStr = signature.ReturnType.ToString();
return signature.Header.IsInstance ? "instance " + returnTypeStr : returnTypeStr;
}
private static string GetMemberRef(MetadataReader metadataReader, int token, CilTypeProvider provider, string genericParameterSignature = "")
{
var refHandle = MetadataTokens.MemberReferenceHandle(token);
var reference = metadataReader.GetMemberReference(refHandle);
var parentToken = MetadataTokens.GetToken(reference.Parent);
string type;
if (IsTypeSpecification(parentToken))
{
var typeSpecificationHandle = MetadataTokens.TypeSpecificationHandle(parentToken);
type = SignatureDecoder.DecodeType(typeSpecificationHandle, provider, null).ToString();
}
else
{
var parentHandle = MetadataTokens.TypeReferenceHandle(parentToken);
type = SignatureDecoder.DecodeType(parentHandle, provider, null).ToString(false);
}
string signatureValue;
string parameters = string.Empty;
if (reference.GetKind() == MemberReferenceKind.Method)
{
MethodSignature<CilType> signature = SignatureDecoder.DecodeMethodSignature(reference.Signature, provider);
signatureValue = GetMethodReturnType(signature);
parameters = provider.GetParameterList(signature);
return String.Format("{0} {1}::{2}{3}{4}", signatureValue, type, GetString(metadataReader, reference.Name), genericParameterSignature,parameters);
}
signatureValue = SignatureDecoder.DecodeFieldSignature(reference.Signature, provider).ToString();
return String.Format("{0} {1}::{2}{3}", signatureValue, type, GetString(metadataReader, reference.Name), parameters);
}
internal static string SolveMethodName(MetadataReader metadataReader, int token, CilTypeProvider provider)
{
string genericParameters = string.Empty;
if (IsMethodSpecification(token))
{
var methodHandle = MetadataTokens.MethodSpecificationHandle(token);
var methodSpec = metadataReader.GetMethodSpecification(methodHandle);
token = MetadataTokens.GetToken(methodSpec.Method);
genericParameters = GetGenericParametersSignature(methodSpec, provider);
}
if (IsMemberReference(token))
{
return GetMemberRef(metadataReader, token, provider, genericParameters);
}
var handle = MetadataTokens.MethodDefinitionHandle(token);
var definition = metadataReader.GetMethodDefinition(handle);
var parent = definition.GetDeclaringType();
MethodSignature<CilType> signature = SignatureDecoder.DecodeMethodSignature(definition.Signature, provider);
var returnType = GetMethodReturnType(signature);
var parameters = provider.GetParameterList(signature);
var parentType = SignatureDecoder.DecodeType(parent, provider, null);
return string.Format("{0} {1}::{2}{3}{4}",returnType, parentType.ToString(false), GetString(metadataReader, definition.Name), genericParameters, parameters);
}
private static string GetGenericParametersSignature(MethodSpecification methodSpec, CilTypeProvider provider)
{
var genericParameters = SignatureDecoder.DecodeMethodSpecificationSignature(methodSpec.Signature, provider);
StringBuilder sb = new StringBuilder();
int i;
for(i = 0; i < genericParameters.Length; i++)
{
if(i == 0)
{
sb.Append("<");
}
sb.Append(genericParameters[i]);
sb.Append(",");
}
if(i > 0)
{
sb.Length--;
sb.Append(">");
}
return sb.ToString();
}
private static string GetFieldInformation(MetadataReader metadataReader, int intOperand, CilTypeProvider provider)
{
if(IsMemberReference(intOperand))
{
return GetMemberRef(metadataReader, intOperand, provider);
}
var handle = MetadataTokens.FieldDefinitionHandle(intOperand);
var definition = metadataReader.GetFieldDefinition(handle);
var typeHandle = definition.GetDeclaringType();
var typeSignature = SignatureDecoder.DecodeType(typeHandle, provider, null);
var signature = SignatureDecoder.DecodeFieldSignature(definition.Signature, provider);
return String.Format("{0} {1}::{2}", signature.ToString(), typeSignature.ToString(false), GetString(metadataReader, definition.Name));
}
private static string GetString(MetadataReader metadataReader, StringHandle handle)
{
return CilDecoderHelpers.Instance.NormalizeString(metadataReader.GetString(handle));
}
private static CilTokenType GetTokenType(int token)
{
return unchecked((CilTokenType)(token >> 24));
}
private static char HexadecimalNibble(byte b)
{
return (char)(b >= 0 && b <= 9 ? '0' + b : 'A' + (b - 10));
}
internal static string DecodeOverridenMethodName(MetadataReader metadataReader, int token, CilTypeProvider provider)
{
var handle = MetadataTokens.MethodDefinitionHandle(token);
var definition = metadataReader.GetMethodDefinition(handle);
var parent = definition.GetDeclaringType();
var parentType = SignatureDecoder.DecodeType(parent, provider, null);
return string.Format("{0}::{1}", parentType.ToString(false), GetString(metadataReader, definition.Name));
}
internal static string GetCachedValue(StringHandle value, CilReaders readers, ref string storage)
{
if (storage != null)
{
return storage;
}
storage = readers.MdReader.GetString(value);
return storage;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Csla;
namespace Oranikle.Studio.Controls
{
public class BaseUserControl : System.Windows.Forms.UserControl
{
public enum SaveStatus
{
NoNeed,
SaveSucceeded,
SaveFailed,
WillRetry
}
public delegate void EmptyDelegate();
public delegate bool PreSaveOperation(object parameter);
public delegate Oranikle.Studio.Controls.BaseUserControl.SaveStatus SaveRecordDelegate(Oranikle.Studio.Controls.BaseUserControl.PreSaveOperation op, object opParameter);
public class SaveMessages
{
private string _InitialMessage;
private string _NoNeed;
private string _SaveFailed;
private string _SaveSucceed;
public string InitialMessage
{
get
{
return _InitialMessage;
}
set
{
_InitialMessage = value;
}
}
public string NoNeed
{
get
{
return _NoNeed;
}
set
{
_NoNeed = value;
}
}
public string SaveFailed
{
get
{
return _SaveFailed;
}
set
{
_SaveFailed = value;
}
}
public string SaveSucceed
{
get
{
return _SaveSucceed;
}
set
{
_SaveSucceed = value;
}
}
public SaveMessages(string initialMessage, string noNeed, string saveSucceed, string saveFailed)
{
InitialMessage = initialMessage;
NoNeed = noNeed;
SaveSucceed = saveSucceed;
SaveFailed = saveFailed;
}
} // class SaveMessages
public const int WM_CHAR = 258;
public const int WM_ERASEBKGND = 20;
public const int WM_LBUTTONCLICK = 513;
public const int WM_NCCALCSIZE = 131;
public const int WM_NCPAINT = 133;
public const int WM_PAINT = 15;
public const int WM_PARENTNOTIFY = 528;
private static bool designMode;
public static int RichTextBoxIndentPixel;
public static new bool DesignMode
{
get
{
return Oranikle.Studio.Controls.BaseUserControl.designMode;
}
}
public BaseUserControl()
{
SetStyle(System.Windows.Forms.ControlStyles.UserMouse, true);
SetStyle(System.Windows.Forms.ControlStyles.SupportsTransparentBackColor, true);
SetStyle(System.Windows.Forms.ControlStyles.DoubleBuffer, true);
SetStyle(System.Windows.Forms.ControlStyles.OptimizedDoubleBuffer, true);
UpdateStyles();
DoubleBuffered = true;
}
static BaseUserControl()
{
Oranikle.Studio.Controls.BaseUserControl.designMode = true;
Oranikle.Studio.Controls.BaseUserControl.RichTextBoxIndentPixel = 10;
}
protected bool EqualNullableSmartDate(System.Nullable<Csla.SmartDate> d1, System.Nullable<Csla.SmartDate> d2)
{
if (!d1.HasValue && !d2.HasValue)
return true;
if (!d1.HasValue && d2.HasValue)
return false;
if (!d2.HasValue && d1.HasValue)
return false;
Csla.SmartDate smartDate = d1.Value;
return smartDate.Equals(d2.Value);
}
protected System.Nullable<Csla.SmartDate> GetSmartDateFromString(string s)
{
System.Nullable<Csla.SmartDate> nullable;
System.Nullable<Csla.SmartDate> nullable1;
System.Nullable<Csla.SmartDate> nullable2;
if ((s == null) || s == System.String.Empty || (s.Length == 0))
{
nullable1 = new System.Nullable<Csla.SmartDate>();
return nullable1;
}
try
{
nullable2 = new System.Nullable<Csla.SmartDate>(new Csla.SmartDate(s));
}
catch
{
nullable = new System.Nullable<Csla.SmartDate>();
nullable2 = nullable;
}
return nullable2;
}
public void ShowInitialMessage(Oranikle.Studio.Controls.BaseUserControl.SaveMessages messages)
{
if ((ParentForm is Oranikle.Studio.Controls.IFormWithStatusBar))
{
string s = null;
if (messages != null)
s = messages.InitialMessage;
if (s != null)
((Oranikle.Studio.Controls.IFormWithStatusBar)ParentForm).StartProgressBar(s);
}
}
public void ShowLoadRecordFinish(string successMessage, string failMessage, bool success)
{
ShowOperationFinish(successMessage, failMessage, success);
}
public void ShowLoadRecordStart(string startMessage)
{
ShowOperationStart(startMessage);
}
public void ShowLoadVersionFinish(string successMessage, string failMessage, bool success)
{
ShowOperationFinish(successMessage, failMessage, success);
}
public void ShowLoadVersionStart(string startMessage)
{
ShowOperationStart(startMessage);
}
public void ShowOperationFinish(string successMessage, string failMessage, bool success)
{
if (success)
{
ShowOperationFinishSuccess(successMessage);
return;
}
ShowOperationFinishFail(failMessage);
}
public void ShowOperationFinishFail(string failMessage)
{
if (ParentForm is Oranikle.Studio.Controls.IFormWithStatusBar)
return;
((Oranikle.Studio.Controls.IFormWithStatusBar)ParentForm).EndProgressBar(Oranikle.Studio.Controls.EnumStatusBarStatusType.StatusType.Error, failMessage);
}
public void ShowOperationFinishSuccess(string successMessage)
{
if (ParentForm is Oranikle.Studio.Controls.IFormWithStatusBar)
return;
((Oranikle.Studio.Controls.IFormWithStatusBar)ParentForm).EndProgressBar(Oranikle.Studio.Controls.EnumStatusBarStatusType.StatusType.Info, successMessage);
}
public void ShowOperationStart(string startMessage)
{
if ((ParentForm is Oranikle.Studio.Controls.IFormWithStatusBar))
((Oranikle.Studio.Controls.IFormWithStatusBar)ParentForm).StartProgressBar(startMessage);
}
public void ShowSaveFailedMessage(Oranikle.Studio.Controls.BaseUserControl.SaveMessages messages)
{
if ((ParentForm is Oranikle.Studio.Controls.IFormWithStatusBar))
{
string s = null;
if (messages != null)
s = messages.SaveFailed;
if (s != null)
((Oranikle.Studio.Controls.IFormWithStatusBar)ParentForm).EndProgressBar(Oranikle.Studio.Controls.EnumStatusBarStatusType.StatusType.Error, s);
}
}
public void ShowSaveNoNeedMessage(Oranikle.Studio.Controls.BaseUserControl.SaveMessages messages)
{
if ((ParentForm is Oranikle.Studio.Controls.IFormWithStatusBar))
{
string s = null;
if (messages != null)
s = messages.NoNeed;
if (s != null)
((Oranikle.Studio.Controls.IFormWithStatusBar)ParentForm).EndProgressBar(Oranikle.Studio.Controls.EnumStatusBarStatusType.StatusType.Info, s);
}
}
public void ShowSaveResultMessage(Oranikle.Studio.Controls.BaseUserControl.SaveMessages messages, Oranikle.Studio.Controls.BaseUserControl.SaveStatus status)
{
switch (status)
{
case Oranikle.Studio.Controls.BaseUserControl.SaveStatus.NoNeed:
ShowSaveNoNeedMessage(messages);
return;
case Oranikle.Studio.Controls.BaseUserControl.SaveStatus.SaveFailed:
ShowSaveFailedMessage(messages);
return;
case Oranikle.Studio.Controls.BaseUserControl.SaveStatus.SaveSucceeded:
ShowSaveSucceedMessage(messages);
break;
case Oranikle.Studio.Controls.BaseUserControl.SaveStatus.WillRetry:
break;
}
}
public void ShowSaveSucceedMessage(Oranikle.Studio.Controls.BaseUserControl.SaveMessages messages)
{
if ((ParentForm is Oranikle.Studio.Controls.IFormWithStatusBar))
{
string s = null;
if (messages != null)
s = messages.SaveSucceed;
if (s != null)
((Oranikle.Studio.Controls.IFormWithStatusBar)ParentForm).EndProgressBar(Oranikle.Studio.Controls.EnumStatusBarStatusType.StatusType.Success, s);
}
}
public static System.Collections.Generic.List<System.Windows.Forms.Control> GetAllChildControls(System.Windows.Forms.Control c)
{
System.Collections.Generic.List<System.Windows.Forms.Control> list = new System.Collections.Generic.List<System.Windows.Forms.Control>();
Oranikle.Studio.Controls.BaseUserControl.GetAllChildControlsHelper(c, list);
return list;
}
protected static void GetAllChildControlsHelper(System.Windows.Forms.Control c, System.Collections.Generic.List<System.Windows.Forms.Control> l)
{
l.Add(c);
foreach (System.Windows.Forms.Control control in c.Controls)
{
Oranikle.Studio.Controls.BaseUserControl.GetAllChildControlsHelper(control, l);
}
}
public static void SetDesignMode(bool value)
{
Oranikle.Studio.Controls.BaseUserControl.designMode = value;
}
} // class BaseUserControl
}
| |
/*
* 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.Data;
using System.Data.SqlClient;
using System.Reflection;
using System.Collections.Generic;
using OpenMetaverse;
using log4net;
using OpenSim.Framework;
namespace OpenSim.Data.MSSQL
{
/// <summary>
/// A MSSQL Interface for the Asset server
/// </summary>
public class MSSQLAssetData : AssetDataBase
{
private const string _migrationStore = "AssetStore";
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private long m_ticksToEpoch;
/// <summary>
/// Database manager
/// </summary>
private MSSQLManager m_database;
#region IPlugin Members
override public void Dispose() { }
/// <summary>
/// <para>Initialises asset interface</para>
/// </summary>
// [Obsolete("Cannot be default-initialized!")]
override public void Initialise()
{
m_log.Info("[MSSQLAssetData]: " + Name + " cannot be default-initialized!");
throw new PluginNotInitialisedException(Name);
}
/// <summary>
/// Initialises asset interface
/// </summary>
/// <para>
/// a string instead of file, if someone writes the support
/// </para>
/// <param name="connectionString">connect string</param>
override public void Initialise(string connectionString)
{
m_ticksToEpoch = new System.DateTime(1970, 1, 1).Ticks;
if (!string.IsNullOrEmpty(connectionString))
{
m_database = new MSSQLManager(connectionString);
}
else
{
IniFile gridDataMSSqlFile = new IniFile("mssql_connection.ini");
string settingDataSource = gridDataMSSqlFile.ParseFileReadValue("data_source");
string settingInitialCatalog = gridDataMSSqlFile.ParseFileReadValue("initial_catalog");
string settingPersistSecurityInfo = gridDataMSSqlFile.ParseFileReadValue("persist_security_info");
string settingUserId = gridDataMSSqlFile.ParseFileReadValue("user_id");
string settingPassword = gridDataMSSqlFile.ParseFileReadValue("password");
m_database =
new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId,
settingPassword);
}
//New migration to check for DB changes
m_database.CheckMigration(_migrationStore);
}
/// <summary>
/// Database provider version.
/// </summary>
override public string Version
{
get { return m_database.getVersion(); }
}
/// <summary>
/// The name of this DB provider.
/// </summary>
override public string Name
{
get { return "MSSQL Asset storage engine"; }
}
#endregion
#region IAssetDataPlugin Members
/// <summary>
/// Fetch Asset from m_database
/// </summary>
/// <param name="assetID">the asset UUID</param>
/// <returns></returns>
override public AssetBase GetAsset(UUID assetID)
{
string sql = "SELECT * FROM assets WHERE id = @id";
using (AutoClosingSqlCommand command = m_database.Query(sql))
{
command.Parameters.Add(m_database.CreateParameter("id", assetID));
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
AssetBase asset = new AssetBase();
// Region Main
asset.FullID = new UUID((Guid)reader["id"]);
asset.Name = (string)reader["name"];
asset.Description = (string)reader["description"];
asset.Type = Convert.ToSByte(reader["assetType"]);
asset.Local = Convert.ToBoolean(reader["local"]);
asset.Temporary = Convert.ToBoolean(reader["temporary"]);
asset.Data = (byte[])reader["data"];
return asset;
}
return null; // throw new Exception("No rows to return");
}
}
}
/// <summary>
/// Create asset in m_database
/// </summary>
/// <param name="asset">the asset</param>
override public void StoreAsset(AssetBase asset)
{
if (ExistsAsset(asset.FullID))
UpdateAsset(asset);
else
InsertAsset(asset);
}
private void InsertAsset(AssetBase asset)
{
if (ExistsAsset(asset.FullID))
{
return;
}
string sql = @"INSERT INTO assets
([id], [name], [description], [assetType], [local],
[temporary], [create_time], [access_time], [data])
VALUES
(@id, @name, @description, @assetType, @local,
@temporary, @create_time, @access_time, @data)";
string assetName = asset.Name;
if (asset.Name.Length > 64)
{
assetName = asset.Name.Substring(0, 64);
m_log.Warn("[ASSET DB]: Name field truncated from " + asset.Name.Length + " to " + assetName.Length + " characters on add");
}
string assetDescription = asset.Description;
if (asset.Description.Length > 64)
{
assetDescription = asset.Description.Substring(0, 64);
m_log.Warn("[ASSET DB]: Description field truncated from " + asset.Description.Length + " to " + assetDescription.Length + " characters on add");
}
using (AutoClosingSqlCommand command = m_database.Query(sql))
{
int now = (int)((System.DateTime.Now.Ticks - m_ticksToEpoch) / 10000000);
command.Parameters.Add(m_database.CreateParameter("id", asset.FullID));
command.Parameters.Add(m_database.CreateParameter("name", assetName));
command.Parameters.Add(m_database.CreateParameter("description", assetDescription));
command.Parameters.Add(m_database.CreateParameter("assetType", asset.Type));
command.Parameters.Add(m_database.CreateParameter("local", asset.Local));
command.Parameters.Add(m_database.CreateParameter("temporary", asset.Temporary));
command.Parameters.Add(m_database.CreateParameter("access_time", now));
command.Parameters.Add(m_database.CreateParameter("create_time", now));
command.Parameters.Add(m_database.CreateParameter("data", asset.Data));
try
{
command.ExecuteNonQuery();
}
catch(Exception e)
{
m_log.Error("[ASSET DB]: Error inserting item :" + e.Message);
}
}
}
/// <summary>
/// Update asset in m_database
/// </summary>
/// <param name="asset">the asset</param>
private void UpdateAsset(AssetBase asset)
{
string sql = @"UPDATE assets set id = @id, name = @name, description = @description, assetType = @assetType,
local = @local, temporary = @temporary, data = @data
WHERE id = @keyId;";
string assetName = asset.Name;
if (asset.Name.Length > 64)
{
assetName = asset.Name.Substring(0, 64);
m_log.Warn("[ASSET DB]: Name field truncated from " + asset.Name.Length + " to " + assetName.Length + " characters on update");
}
string assetDescription = asset.Description;
if (asset.Description.Length > 64)
{
assetDescription = asset.Description.Substring(0, 64);
m_log.Warn("[ASSET DB]: Description field truncated from " + asset.Description.Length + " to " + assetDescription.Length + " characters on update");
}
using (AutoClosingSqlCommand command = m_database.Query(sql))
{
command.Parameters.Add(m_database.CreateParameter("id", asset.FullID));
command.Parameters.Add(m_database.CreateParameter("name", assetName));
command.Parameters.Add(m_database.CreateParameter("description", assetDescription));
command.Parameters.Add(m_database.CreateParameter("assetType", asset.Type));
command.Parameters.Add(m_database.CreateParameter("local", asset.Local));
command.Parameters.Add(m_database.CreateParameter("temporary", asset.Temporary));
command.Parameters.Add(m_database.CreateParameter("data", asset.Data));
command.Parameters.Add(m_database.CreateParameter("@keyId", asset.FullID));
try
{
command.ExecuteNonQuery();
}
catch (Exception e)
{
m_log.Error(e.ToString());
}
}
}
// Commented out since currently unused - this probably should be called in GetAsset()
// private void UpdateAccessTime(AssetBase asset)
// {
// using (AutoClosingSqlCommand cmd = m_database.Query("UPDATE assets SET access_time = @access_time WHERE id=@id"))
// {
// int now = (int)((System.DateTime.Now.Ticks - m_ticksToEpoch) / 10000000);
// cmd.Parameters.AddWithValue("@id", asset.FullID.ToString());
// cmd.Parameters.AddWithValue("@access_time", now);
// try
// {
// cmd.ExecuteNonQuery();
// }
// catch (Exception e)
// {
// m_log.Error(e.ToString());
// }
// }
// }
/// <summary>
/// Check if asset exist in m_database
/// </summary>
/// <param name="uuid"></param>
/// <returns>true if exist.</returns>
override public bool ExistsAsset(UUID uuid)
{
if (GetAsset(uuid) != null)
{
return true;
}
return false;
}
/// <summary>
/// Returns a list of AssetMetadata objects. The list is a subset of
/// the entire data set offset by <paramref name="start" /> containing
/// <paramref name="count" /> elements.
/// </summary>
/// <param name="start">The number of results to discard from the total data set.</param>
/// <param name="count">The number of rows the returned list should contain.</param>
/// <returns>A list of AssetMetadata objects.</returns>
public override List<AssetMetadata> FetchAssetMetadataSet(int start, int count)
{
List<AssetMetadata> retList = new List<AssetMetadata>(count);
string sql = @"SELECT (name,description,assetType,temporary,id), Row = ROW_NUMBER()
OVER (ORDER BY (some column to order by))
WHERE Row >= @Start AND Row < @Start + @Count";
using (AutoClosingSqlCommand command = m_database.Query(sql))
{
command.Parameters.Add(m_database.CreateParameter("start", start));
command.Parameters.Add(m_database.CreateParameter("count", count));
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
AssetMetadata metadata = new AssetMetadata();
metadata.FullID = new UUID((Guid)reader["id"]);
metadata.Name = (string)reader["name"];
metadata.Description = (string)reader["description"];
metadata.Type = Convert.ToSByte(reader["assetType"]);
metadata.Temporary = Convert.ToBoolean(reader["temporary"]);
}
}
}
return retList;
}
#endregion
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. 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.Text;
using System.Xml;
using System.Diagnostics;
using System.IO;
using System.Globalization;
namespace DocumentFormat.OpenXml
{
/// <summary>
/// Represents an Open XML non element node (i.e. PT, Comments, Entity, Notation, XmlDeclaration).
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
public class OpenXmlMiscNode : OpenXmlElement
{
const string strCDataSectionName = "#cdata-section";
const string strCommentName = "#comment";
const string strTextName = "#text";
const string strNonSignificantWhitespaceName = "#whitespace";
const string strSignificantWhitespaceName = "#significant-whitespace";
const string strXmlDeclaration = "xml-declaration";
XmlNodeType _nodeType;
/// <summary>
/// Initializes a new instance of the OpenXmlMiscNode class using the
/// supplied XmlNodeType value.
/// </summary>
/// <param name="nodeType">
/// The XmlNodeType value.
/// </param>
public OpenXmlMiscNode(XmlNodeType nodeType)
: base()
{
switch (nodeType)
{
case XmlNodeType.Element:
case XmlNodeType.Attribute:
case XmlNodeType.Document:
case XmlNodeType.DocumentFragment:
case XmlNodeType.DocumentType: // not allowed when DtdProcessing = DtdProcessing.Prohibit
case XmlNodeType.EndElement:
case XmlNodeType.EndEntity:
case XmlNodeType.Entity: // not allowed when DtdProcessing = DtdProcessing.Prohibit
case XmlNodeType.EntityReference:
case XmlNodeType.Notation: // not allowed when DtdProcessing = DtdProcessing.Prohibit
case XmlNodeType.None:
throw new ArgumentOutOfRangeException("nodeType");
}
this.XmlNodeType = nodeType;
}
/// <summary>
/// Initializes a new instance of the OpenXmlMiscNode class using the
/// supplied XmlNodeType and outer XML values.
/// </summary>
/// <param name="nodeType">The XmlNodeType value.</param>
/// <param name="outerXml">The outer XML of the element.</param>
public OpenXmlMiscNode(XmlNodeType nodeType, string outerXml)
: this(nodeType)
{
if ( String.IsNullOrEmpty( outerXml ) )
{
throw new ArgumentNullException("outerXml");
}
// check the out XML match the nodeType
using (StringReader stringReader = new StringReader(outerXml))
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Prohibit; // set true explicitly for serucity fix
using (XmlReader xmlReader = XmlConvertingReaderFactory.Create(stringReader, settings))
{
xmlReader.Read();
if (xmlReader.NodeType != nodeType)
{
throw new ArgumentException(ExceptionMessages.InvalidOuterXmlForMiscNode);
}
xmlReader.Close();
}
}
this.RawOuterXml = outerXml;
}
/// <summary>
/// Specifies the type of XML node.
/// </summary>
public XmlNodeType XmlNodeType
{
get { return _nodeType; }
internal set { _nodeType = value; }
}
/// <summary>
/// The type ID of the element.
/// </summary>
internal override int ElementTypeId
{
get { return ReservedElementTypeIds.OpenXmlMiscNodeId; }
}
internal override byte NamespaceId
{
get
{
throw new InvalidOperationException();
}
}
/// <summary>
/// Gets a value that indicates whether the current element has any child
/// elements.
/// </summary>
public override bool HasChildren
{
get { return false; }
}
/// <summary>
/// When overridden in a derived class, gets the local name of the node.
/// </summary>
public override string LocalName
{
get
{
string localName = string.Empty;
switch (this._nodeType)
{
case XmlNodeType.CDATA:
localName = strCDataSectionName;
break;
case XmlNodeType.Comment:
localName = strCommentName;
break;
case XmlNodeType.ProcessingInstruction:
using (StringReader stringReader = new StringReader(this.OuterXml))
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Prohibit; // set true explicitly for security fix
using (XmlReader xmlReader = XmlConvertingReaderFactory.Create(stringReader, settings))
{
xmlReader.Read();
localName = xmlReader.LocalName;
xmlReader.Close();
}
}
break;
case XmlNodeType.Text:
localName = strTextName;
break;
case XmlNodeType.Whitespace:
localName = strNonSignificantWhitespaceName;
break;
case XmlNodeType.SignificantWhitespace:
localName = strSignificantWhitespaceName;
break;
case XmlNodeType.XmlDeclaration:
localName = strXmlDeclaration;
break;
case XmlNodeType.Element:
case XmlNodeType.Attribute:
case XmlNodeType.Document:
case XmlNodeType.DocumentFragment:
case XmlNodeType.DocumentType: // not allowed when DtdProcessing = DtdProcessing.Prohibit
case XmlNodeType.EndElement:
case XmlNodeType.EndEntity:
case XmlNodeType.Entity: // not allowed when DtdProcessing = DtdProcessing.Prohibit
case XmlNodeType.EntityReference:
case XmlNodeType.Notation: // not allowed when DtdProcessing = DtdProcessing.Prohibit
case XmlNodeType.None:
Debug.Assert(false);
break;
}
return localName;
}
}
/// <summary>
/// Gets the namespace URI of the current node.
/// </summary>
public override string NamespaceUri
{
get
{
return string.Empty;
}
}
/// <summary>
/// Gets or sets the namespace prefix of the current node.
/// </summary>
public override string Prefix
{
get
{
return string.Empty;
}
}
/// <summary>
/// When overridden in a derived class, gets the qualified name of the node.
/// </summary>
public override XmlQualifiedName XmlQualifiedName
{
get
{
throw new InvalidOperationException();
}
}
/// <summary>
/// Gets or sets the markup that represents only the child nodes of the
/// current node.
/// </summary>
public override string InnerXml
{
get
{
return String.Empty;
}
set
{
throw new InvalidOperationException(ExceptionMessages.InnerXmlCannotBeSet);
}
}
/// <summary>
/// When overridden in a derived class, creates a duplicate of the node.
/// </summary>
/// <param name="deep">
/// Specify true to recursively clone the subtree under the specified
/// node; false to clone only the node itself.
/// </param>
/// <returns>The cloned node. </returns>
public override OpenXmlElement CloneNode(bool deep)
{
OpenXmlMiscNode element = new OpenXmlMiscNode(this.XmlNodeType);
element.OuterXml = this.OuterXml;
return element;
}
/// <summary>
/// Removes all child elements.
/// </summary>
public override void RemoveAllChildren()
{
}
/// <summary>
/// Saves all the children of the node to the specified XmlWriter.
/// </summary>
/// <param name="w">The XmlWriter to which you want to save. </param>
internal override void WriteContentTo(XmlWriter w)
{
throw new NotImplementedException(ExceptionMessages.NonImplemented);
}
/// <summary>
/// Saves the current node to the specified XmlWriter.
/// </summary>
/// <param name="xmlWriter">
/// The XmlWriter at which to save the current node.
/// </param>
public override void WriteTo(XmlWriter xmlWriter)
{
if (xmlWriter == null)
{
throw new ArgumentNullException("xmlWriter");
}
// write out the raw xml
xmlWriter.WriteRaw(this.RawOuterXml);
}
internal override void LazyLoad(XmlReader xmlReader)
{
this.Populate(xmlReader, OpenXmlLoadMode.Full);
}
internal override void ParseXml()
{
// do nothing
}
/// <summary>
/// Holds the XmlReader.Value on loading.
/// </summary>
internal string Value
{
get;
private set;
}
/// <summary>
/// Load the out xml from the XmlReader.
/// </summary>
/// <param name="xmlReader"></param>
/// <remarks>The XmlReader not be moved.</remarks>
internal void LoadOuterXml(System.Xml.XmlReader xmlReader)
{
switch (xmlReader.NodeType)
{
case XmlNodeType.None:
Debug.Assert(xmlReader.NodeType != XmlNodeType.None);
break;
case XmlNodeType.XmlDeclaration:
Debug.Assert(xmlReader.NodeType != XmlNodeType.XmlDeclaration);
// this.RawOuterXml = String.Format("<?xml version='1.0'?>");
this.Value = xmlReader.Value; // version='1.0'
break;
case XmlNodeType.Element:
Debug.Assert(xmlReader.NodeType != XmlNodeType.Element);
break;
case XmlNodeType.EndElement:
Debug.Assert(xmlReader.NodeType != XmlNodeType.EndElement);
break;
case XmlNodeType.Notation:
Debug.Assert(xmlReader.NodeType != XmlNodeType.Notation);
break;
case XmlNodeType.Attribute:
Debug.Assert(xmlReader.NodeType != XmlNodeType.Attribute);
break;
case XmlNodeType.Text:
this.Value = xmlReader.Value;
this.RawOuterXml = xmlReader.Value;
break;
case XmlNodeType.CDATA:
this.Value = xmlReader.Value;
this.RawOuterXml = String.Format(CultureInfo.InvariantCulture, "<![CDATA[{0}]]>", xmlReader.Value);
break;
case XmlNodeType.SignificantWhitespace:
this.Value = xmlReader.Value;
this.RawOuterXml = xmlReader.Value;
break;
case XmlNodeType.Whitespace:
break; // O15:#3024890, OpenXmlMiscNode ignores the Whitespace NodeType.
case XmlNodeType.ProcessingInstruction:
this.Value = xmlReader.Value;
this.RawOuterXml = String.Format(CultureInfo.InvariantCulture, "<?{0} {1}?>", xmlReader.Name, xmlReader.Value);
break;
case XmlNodeType.Comment:
this.Value = xmlReader.Value;
this.RawOuterXml = String.Format(CultureInfo.InvariantCulture, "<!--{0}-->", xmlReader.Value);
break;
case XmlNodeType.Document:
Debug.Assert(xmlReader.NodeType != XmlNodeType.Document);
break;
case XmlNodeType.DocumentType:
// this.RawOuterXml = String.Format(CultureInfo.InvariantCulture, "<!DOCTYPE {0} [{1}]", xmlReader.Name, xmlReader.Value);
Debug.Assert(xmlReader.NodeType != XmlNodeType.DocumentType);
break;
case XmlNodeType.EntityReference:
Debug.Assert(xmlReader.NodeType != XmlNodeType.EntityReference);
this.RawOuterXml = xmlReader.Name;
break;
case XmlNodeType.Entity:
Debug.Assert(xmlReader.NodeType != XmlNodeType.Entity);
break;
case XmlNodeType.DocumentFragment:
case XmlNodeType.EndEntity:
default:
Debug.Assert(false, xmlReader.NodeType.ToString());
break;
}
}
/// <summary>
/// Do nothing for MiscNode.
/// Override this method because the MC loading algorithm try to call this method in parent's Populate.
/// While the OpenXmlElement.LoadAttributes() will cause the reader be moved which should not.
/// </summary>
/// <param name="xmlReader"></param>
internal override void LoadAttributes(XmlReader xmlReader)
{
return;
}
internal override void Populate(XmlReader xmlReader, OpenXmlLoadMode loadMode)
{
this.LoadOuterXml(xmlReader);
xmlReader.Read();
// this.RawOuterXml = xmlReader.ReadOuterXml();
}
/// <summary>
/// Whether this element is available in a specific version of Office Application.
/// For OpenXmlMiscNode, always return true, no matter what the version is.
/// </summary>
/// <param name="version">The Office file format version.</param>
/// <returns>Returns true if the element is defined in the specified version.</returns>
internal override bool IsInVersion(FileFormatVersions version)
{
return true;
}
internal static OpenXmlMiscNode CreateFromText(string text)
{
Debug.Assert(text != null);
var newMiscNode = new OpenXmlMiscNode(XmlNodeType.Text);
newMiscNode.Value = text;
newMiscNode.RawOuterXml = text;
return newMiscNode;
}
internal static OpenXmlMiscNode CreateFromCdata(string value)
{
Debug.Assert(value != null);
var newMiscNode = new OpenXmlMiscNode(XmlNodeType.CDATA);
newMiscNode.Value = value;
newMiscNode.RawOuterXml = String.Format(CultureInfo.InvariantCulture, "<![CDATA[{0}]]>", value); ;
return newMiscNode;
}
internal static OpenXmlMiscNode CreateFromSignificantWhitespace(string whitespace)
{
Debug.Assert(whitespace != null);
var newMiscNode = new OpenXmlMiscNode(XmlNodeType.SignificantWhitespace);
newMiscNode.Value = whitespace;
newMiscNode.RawOuterXml = whitespace;
return newMiscNode;
}
}
}
| |
/*
*
* 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.
*
*/
#if !FEATURE_CONDITIONALWEAKTABLE_ENUMERATOR
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Support
{
#if FEATURE_SERIALIZABLE
[Serializable]
#endif
internal sealed class WeakDictionary<TKey, TValue> : IDictionary<TKey, TValue> where TKey : class
{
private IDictionary<WeakKey<TKey>, TValue> _hm;
private int _gcCollections = 0;
public WeakDictionary(int initialCapacity)
: this(initialCapacity, Enumerable.Empty<KeyValuePair<TKey, TValue>>())
{ }
public WeakDictionary()
: this(32, Enumerable.Empty<KeyValuePair<TKey, TValue>>())
{ }
public WeakDictionary(IEnumerable<KeyValuePair<TKey, TValue>> otherDictionary)
: this(32, otherDictionary)
{ }
private WeakDictionary(int initialCapacity, IEnumerable<KeyValuePair<TKey, TValue>> otherDict)
{
_hm = new JCG.Dictionary<WeakKey<TKey>, TValue>(initialCapacity);
foreach (var kvp in otherDict)
{
_hm.Add(new WeakKey<TKey>(kvp.Key), kvp.Value);
}
}
// LUCENENET NOTE: Added AddOrUpdate method so we don't need so many conditional compilation blocks.
// This is just to cascade the call to this[key] = value
public void AddOrUpdate(TKey key, TValue value) => this[key] = value;
private void Clean()
{
if (_hm.Count == 0) return;
var newHm = new JCG.Dictionary<WeakKey<TKey>, TValue>(_hm.Count);
foreach (var entry in _hm.Where(x => x.Key != null && x.Key.IsAlive))
{
newHm.Add(entry.Key, entry.Value);
}
_hm = newHm;
}
private void CleanIfNeeded()
{
int currentColCount = GC.CollectionCount(0);
if (currentColCount > _gcCollections)
{
Clean();
_gcCollections = currentColCount;
}
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
foreach (var kvp in _hm.Where(x => x.Key.IsAlive))
{
yield return new KeyValuePair<TKey, TValue>(kvp.Key.Target, kvp.Value);
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
{
CleanIfNeeded();
((ICollection<KeyValuePair<WeakKey<TKey>, TValue>>)_hm).Add(
new KeyValuePair<WeakKey<TKey>, TValue>(new WeakKey<TKey>(item.Key), item.Value));
}
public void Clear()
{
_hm.Clear();
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
{
return ((ICollection<KeyValuePair<WeakKey<TKey>, TValue>>)_hm).Contains(
new KeyValuePair<WeakKey<TKey>, TValue>(new WeakKey<TKey>(item.Key), item.Value));
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
{
return ((ICollection<KeyValuePair<WeakKey<TKey>, TValue>>)_hm).Remove(
new KeyValuePair<WeakKey<TKey>, TValue>(new WeakKey<TKey>(item.Key), item.Value));
}
public int Count
{
get
{
CleanIfNeeded();
return _hm.Count;
}
}
public bool IsReadOnly => false;
public bool ContainsKey(TKey key)
{
return _hm.ContainsKey(new WeakKey<TKey>(key));
}
public void Add(TKey key, TValue value)
{
CleanIfNeeded();
_hm.Add(new WeakKey<TKey>(key), value);
}
public bool Remove(TKey key)
{
return _hm.Remove(new WeakKey<TKey>(key));
}
public bool TryGetValue(TKey key, out TValue value)
{
return _hm.TryGetValue(new WeakKey<TKey>(key), out value);
}
public TValue this[TKey key]
{
get => _hm[new WeakKey<TKey>(key)];
set
{
CleanIfNeeded();
_hm[new WeakKey<TKey>(key)] = value;
}
}
public ICollection<TKey> Keys
{
get
{
CleanIfNeeded();
return new KeyCollection(_hm);
}
}
public ICollection<TValue> Values
{
get
{
CleanIfNeeded();
return _hm.Values;
}
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
throw new NotSupportedException();
}
#region KeyCollection
private class KeyCollection : ICollection<TKey>
{
private readonly IDictionary<WeakKey<TKey>, TValue> _internalDict;
public KeyCollection(IDictionary<WeakKey<TKey>, TValue> dict)
{
_internalDict = dict;
}
public IEnumerator<TKey> GetEnumerator()
{
foreach (var key in _internalDict.Keys)
{
yield return key.Target;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void CopyTo(TKey[] array, int arrayIndex)
{
throw new NotImplementedException("Implement this as needed");
}
public int Count => _internalDict.Count + 1;
public bool IsReadOnly => true;
#region Explicit Interface Definitions
bool ICollection<TKey>.Contains(TKey item)
{
throw new NotSupportedException();
}
void ICollection<TKey>.Add(TKey item)
{
throw new NotSupportedException();
}
void ICollection<TKey>.Clear()
{
throw new NotSupportedException();
}
bool ICollection<TKey>.Remove(TKey item)
{
throw new NotSupportedException();
}
#endregion Explicit Interface Definitions
}
#endregion KeyCollection
/// <summary>
/// A weak reference wrapper for the hashtable keys. Whenever a key\value pair
/// is added to the hashtable, the key is wrapped using a WeakKey. WeakKey saves the
/// value of the original object hashcode for fast comparison.
/// </summary>
private class WeakKey<T> where T : class
{
private readonly WeakReference reference;
private readonly int hashCode;
public WeakKey(T key)
{
if (key == null)
throw new ArgumentNullException("key");
hashCode = key.GetHashCode();
reference = new WeakReference(key);
}
public override int GetHashCode()
{
return hashCode;
}
public override bool Equals(object obj)
{
if (!reference.IsAlive || obj == null) return false;
if (object.ReferenceEquals(this, obj))
{
return true;
}
if (obj is WeakKey<T> other)
{
var referenceTarget = reference.Target; // Careful: can be null in the mean time...
return referenceTarget != null && referenceTarget.Equals(other.Target);
}
return false;
}
public T Target => (T)reference.Target;
public bool IsAlive => reference.IsAlive;
}
}
}
#endif
| |
using System.IO;
using Rafty.Log;
using Microsoft.Data.Sqlite;
using Newtonsoft.Json;
using System;
using Rafty.Infrastructure;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
using Microsoft.Extensions.Logging;
namespace Rafty.IntegrationTests
{
public class SqlLiteLog : ILog
{
private readonly string _path;
private readonly SemaphoreSlim _sempaphore = new SemaphoreSlim(1,1);
private readonly ILogger _logger;
private readonly NodeId _nodeId;
public SqlLiteLog(NodeId nodeId, ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<SqlLiteLog>();
_nodeId = nodeId;
_path = $"{nodeId.Id.Replace("/","").Replace(":","")}.db";
_sempaphore.Wait();
if (!File.Exists(_path))
{
var fs = File.Create(_path);
fs.Dispose();
using(var connection = new SqliteConnection($"Data Source={_path};"))
{
connection.Open();
const string sql = @"create table logs (
id integer primary key,
data text not null
)";
using(var command = new SqliteCommand(sql, connection))
{
var result = command.ExecuteNonQuery();
_logger.LogInformation(result == 0
? $"id: {_nodeId.Id} create database, result: {result}"
: $"id: {_nodeId.Id} did not create database., result: {result}");
}
}
}
_sempaphore.Release();
}
public async Task<int> LastLogIndex()
{
_sempaphore.Wait();
var result = 1;
using(var connection = new SqliteConnection($"Data Source={_path};"))
{
connection.Open();
var sql = @"select id from logs order by id desc limit 1";
using(var command = new SqliteCommand(sql, connection))
{
var index = Convert.ToInt32(await command.ExecuteScalarAsync());
if(index > result)
{
result = index;
}
}
}
_sempaphore.Release();
return result;
}
public async Task<long> LastLogTerm()
{
_sempaphore.Wait();
long result = 0;
using(var connection = new SqliteConnection($"Data Source={_path};"))
{
connection.Open();
var sql = @"select data from logs order by id desc limit 1";
using(var command = new SqliteCommand(sql, connection))
{
var data = Convert.ToString(await command.ExecuteScalarAsync());
var jsonSerializerSettings = new JsonSerializerSettings() {
TypeNameHandling = TypeNameHandling.All
};
var log = JsonConvert.DeserializeObject<LogEntry>(data, jsonSerializerSettings);
if(log != null && log.Term > result)
{
result = log.Term;
}
}
}
_sempaphore.Release();
return result;
}
public async Task<int> Count()
{
_sempaphore.Wait();
var result = 0;
using(var connection = new SqliteConnection($"Data Source={_path};"))
{
connection.Open();
var sql = @"select count(id) from logs";
using(var command = new SqliteCommand(sql, connection))
{
var index = Convert.ToInt32(await command.ExecuteScalarAsync());
if(index > result)
{
result = index;
}
}
}
_sempaphore.Release();
return result;
}
public async Task<int> Apply(LogEntry log)
{
_sempaphore.Wait();
using(var connection = new SqliteConnection($"Data Source={_path};"))
{
connection.Open();
var jsonSerializerSettings = new JsonSerializerSettings() {
TypeNameHandling = TypeNameHandling.All
};
var data = JsonConvert.SerializeObject(log, jsonSerializerSettings);
//todo - sql injection dont copy this..
var sql = $"insert into logs (data) values ('{data}')";
_logger.LogInformation($"id: {_nodeId.Id}, sql: {sql}");
using(var command = new SqliteCommand(sql, connection))
{
var result = await command.ExecuteNonQueryAsync();
_logger.LogInformation($"id: {_nodeId.Id}, insert log result: {result}");
}
sql = "select last_insert_rowid()";
using(var command = new SqliteCommand(sql, connection))
{
var result = await command.ExecuteScalarAsync();
_logger.LogInformation($"id: {_nodeId.Id}, about to release semaphore");
_sempaphore.Release();
_logger.LogInformation($"id: {_nodeId.Id}, saved log to sqlite");
return Convert.ToInt32(result);
}
}
}
public async Task DeleteConflictsFromThisLog(int index, LogEntry logEntry)
{
_sempaphore.Wait();
using(var connection = new SqliteConnection($"Data Source={_path};"))
{
connection.Open();
//todo - sql injection dont copy this..
var sql = $"select data from logs where id = {index};";
_logger.LogInformation($"id: {_nodeId.Id} sql: {sql}");
using(var command = new SqliteCommand(sql, connection))
{
var data = Convert.ToString(await command.ExecuteScalarAsync());
var jsonSerializerSettings = new JsonSerializerSettings() {
TypeNameHandling = TypeNameHandling.All
};
_logger.LogInformation($"id {_nodeId.Id} got log for index: {index}, data is {data} and new log term is {logEntry.Term}");
var log = JsonConvert.DeserializeObject<LogEntry>(data, jsonSerializerSettings);
if(logEntry != null && log != null && logEntry.Term != log.Term)
{
//todo - sql injection dont copy this..
var deleteSql = $"delete from logs where id >= {index};";
_logger.LogInformation($"id: {_nodeId.Id} sql: {deleteSql}");
using(var deleteCommand = new SqliteCommand(deleteSql, connection))
{
var result = await deleteCommand.ExecuteNonQueryAsync();
}
}
}
}
_sempaphore.Release();
}
public async Task<bool> IsDuplicate(int index, LogEntry logEntry)
{
_sempaphore.Wait();
using(var connection = new SqliteConnection($"Data Source={_path};"))
{
connection.Open();
//todo - sql injection dont copy this..
var sql = $"select data from logs where id = {index};";
using(var command = new SqliteCommand(sql, connection))
{
var data = Convert.ToString(await command.ExecuteScalarAsync());
var jsonSerializerSettings = new JsonSerializerSettings() {
TypeNameHandling = TypeNameHandling.All
};
var log = JsonConvert.DeserializeObject<LogEntry>(data, jsonSerializerSettings);
if(logEntry != null && log != null && logEntry.Term == log.Term)
{
_sempaphore.Release();
return true;
}
}
}
_sempaphore.Release();
return false;
}
public async Task<LogEntry> Get(int index)
{
_sempaphore.Wait();
using(var connection = new SqliteConnection($"Data Source={_path};"))
{
connection.Open();
//todo - sql injection dont copy this..
var sql = $"select data from logs where id = {index}";
using(var command = new SqliteCommand(sql, connection))
{
var data = Convert.ToString(await command.ExecuteScalarAsync());
var jsonSerializerSettings = new JsonSerializerSettings() {
TypeNameHandling = TypeNameHandling.All
};
var log = JsonConvert.DeserializeObject<LogEntry>(data, jsonSerializerSettings);
_sempaphore.Release();
return log;
}
}
}
public async Task<List<(int index, LogEntry logEntry)>> GetFrom(int index)
{
_sempaphore.Wait();
var logsToReturn = new List<(int, LogEntry)>();
using(var connection = new SqliteConnection($"Data Source={_path};"))
{
connection.Open();
//todo - sql injection dont copy this..
var sql = $"select id, data from logs where id >= {index}";
using(var command = new SqliteCommand(sql, connection))
{
using(var reader = await command.ExecuteReaderAsync())
{
while(reader.Read())
{
var id = Convert.ToInt32(reader[0]);
var data = (string)reader[1];
var jsonSerializerSettings = new JsonSerializerSettings() {
TypeNameHandling = TypeNameHandling.All
};
var log = JsonConvert.DeserializeObject<LogEntry>(data, jsonSerializerSettings);
logsToReturn.Add((id, log));
}
}
}
_sempaphore.Release();
return logsToReturn;
}
}
public async Task<long> GetTermAtIndex(int index)
{
_sempaphore.Wait();
long result = 0;
using(var connection = new SqliteConnection($"Data Source={_path};"))
{
connection.Open();
//todo - sql injection dont copy this..
var sql = $"select data from logs where id = {index}";
using(var command = new SqliteCommand(sql, connection))
{
var data = Convert.ToString(await command.ExecuteScalarAsync());
var jsonSerializerSettings = new JsonSerializerSettings() {
TypeNameHandling = TypeNameHandling.All
};
var log = JsonConvert.DeserializeObject<LogEntry>(data, jsonSerializerSettings);
if(log != null && log.Term > result)
{
result = log.Term;
}
}
}
_sempaphore.Release();
return result;
}
public async Task Remove(int indexOfCommand)
{
_sempaphore.Wait();
using(var connection = new SqliteConnection($"Data Source={_path};"))
{
connection.Open();
//todo - sql injection dont copy this..
var deleteSql = $"delete from logs where id >= {indexOfCommand};";
_logger.LogInformation($"id: {_nodeId.Id} Remove {deleteSql}");
using(var deleteCommand = new SqliteCommand(deleteSql, connection))
{
var result = await deleteCommand.ExecuteNonQueryAsync();
}
}
_sempaphore.Release();
}
}
}
| |
/* Copyright (c) 2006 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define USE_TRACING
using System;
using System.Collections.Generic;
using Google.GData.Client;
namespace Google.GData.YouTube {
/// <summary>
/// enum to define different activities.
/// </summary>
public enum ActivityType
{
/// <summary>
/// a user rated an entry
/// </summary>
Rated,
/// <summary>
/// a user shared a video
/// </summary>
Shared,
/// <summary>
/// a user uploaded a video
/// </summary>
Uploaded,
/// <summary>
/// a user added something to his favorites
/// </summary>
Favorited,
/// <summary>
/// a user added a friend
/// </summary>
FriendAdded,
/// <summary>
/// a user added something to his subscriptions
/// </summary>
SubscriptionAdded,
/// <summary>
/// a user commented on something
/// </summary>
Commented,
/// <summary>
/// undfined -> there was no Type for this entry
/// </summary>
Undefined
}
//////////////////////////////////////////////////////////////////////
/// <summary>
/// Entry API customization class for retrieving activies
/// </summary>
//////////////////////////////////////////////////////////////////////
public class ActivityEntry : AbstractEntry
{
/// <summary>
/// Category used to label entries that indicate a user marking a video as a favorite
/// </summary>
public static AtomCategory VIDEORATED_CATEGORY =
new AtomCategory(YouTubeNameTable.VideoRatedCategory, new AtomUri(YouTubeNameTable.EventsCategorySchema));
/// <summary>
/// Category used to label entries that indicate a user marking a video as a favorite
/// </summary>
public static AtomCategory VIDEOSHARED_CATEGORY =
new AtomCategory(YouTubeNameTable.VideoSharedCategory, new AtomUri(YouTubeNameTable.EventsCategorySchema));
/// <summary>
/// Category used to label entries that indicate a user marking a video as a favorite
/// </summary>
public static AtomCategory VIDEOUPLOADED_CATEGORY =
new AtomCategory(YouTubeNameTable.VideoUploadedCategory, new AtomUri(YouTubeNameTable.EventsCategorySchema));
/// <summary>
/// Category used to label entries that indicate a user marking a video as a favorite
/// </summary>
public static AtomCategory VIDEOFAVORITED_CATEGORY =
new AtomCategory(YouTubeNameTable.VideoFavoritedCategory, new AtomUri(YouTubeNameTable.EventsCategorySchema));
/// <summary>
/// Category used to label entries that indicate a user commenting on a video
/// </summary>
public static AtomCategory VIDEOCOMMENTED_CATEGORY =
new AtomCategory(YouTubeNameTable.VideoCommentedCategory, new AtomUri(YouTubeNameTable.EventsCategorySchema));
/// <summary>
/// Category used to label entries that indicate a user added a friend
/// </summary>
public static AtomCategory FRIENDADDED_CATEGORY =
new AtomCategory(YouTubeNameTable.FriendAddedCategory, new AtomUri(YouTubeNameTable.EventsCategorySchema));
/// <summary>
/// Category used to label entries that indicate a user added a subscripton
/// </summary>
public static AtomCategory USERSUBSCRIPTIONADDED_CATEGORY =
new AtomCategory(YouTubeNameTable.UserSubscriptionAddedCategory, new AtomUri(YouTubeNameTable.EventsCategorySchema));
/// <summary>
/// Constructs a new EventEmtry instance
/// </summary>
public ActivityEntry()
: base()
{
this.AddExtension(new VideoId());
this.AddExtension(new UserName());
}
/// <summary>
/// The type of Event, the user action that caused this.
/// </summary>
/// <returns></returns>
public ActivityType Type
{
get
{
if (this.Categories.Contains(VIDEORATED_CATEGORY))
{
return ActivityType.Rated;
}
else if (this.Categories.Contains(VIDEOSHARED_CATEGORY))
{
return ActivityType.Shared;
}
else if (this.Categories.Contains(VIDEOFAVORITED_CATEGORY))
{
return ActivityType.Favorited;
}
else if (this.Categories.Contains(VIDEOCOMMENTED_CATEGORY))
{
return ActivityType.Commented;
}
else if (this.Categories.Contains(VIDEOUPLOADED_CATEGORY))
{
return ActivityType.Uploaded;
}
else if (this.Categories.Contains(FRIENDADDED_CATEGORY))
{
return ActivityType.FriendAdded;
}
else if (this.Categories.Contains(USERSUBSCRIPTIONADDED_CATEGORY))
{
return ActivityType.SubscriptionAdded;
}
return ActivityType.Undefined;
}
}
/// <summary>
/// property accessor for the VideoID, if applicable
/// </summary>
public VideoId VideoId
{
get
{
return FindExtension(YouTubeNameTable.VideoID,
YouTubeNameTable.NSYouTube) as VideoId;
}
}
/// <summary>
/// property accessor for the UseName, if applicable
/// </summary>
public UserName Username
{
get
{
return FindExtension(YouTubeNameTable.UserName,
YouTubeNameTable.NSYouTube) as UserName;
}
}
//////////////////////////////////////////////////////////////////////
/// <summary>returns the video relation link uri, which can be used to
/// retrieve the video entry</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public AtomUri VideoLink
{
get
{
AtomLink link = this.Links.FindService(YouTubeNameTable.KIND_VIDEO, AtomLink.ATOM_TYPE);
// scan the link collection
return link == null ? null : link.HRef;
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.IntroduceVariable
{
internal partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax>
{
private partial class State
{
public SemanticDocument Document { get; private set; }
public TExpressionSyntax Expression { get; private set; }
public bool InAttributeContext { get; private set; }
public bool InBlockContext { get; private set; }
public bool InConstructorInitializerContext { get; private set; }
public bool InFieldContext { get; private set; }
public bool InParameterContext { get; private set; }
public bool InQueryContext { get; private set; }
public bool InExpressionBodiedMemberContext { get; private set; }
public bool IsConstant { get; private set; }
private SemanticMap _semanticMap;
private readonly TService _service;
public State(TService service, SemanticDocument document)
{
_service = service;
this.Document = document;
}
public static State Generate(
TService service,
SemanticDocument document,
TextSpan textSpan,
CancellationToken cancellationToken)
{
var state = new State(service, document);
if (!state.TryInitialize(textSpan, cancellationToken))
{
return null;
}
return state;
}
private bool TryInitialize(
TextSpan textSpan,
CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return false;
}
var tree = this.Document.SyntaxTree;
var syntaxFacts = this.Document.Project.LanguageServices.GetService<ISyntaxFactsService>();
this.Expression = this.GetExpressionUnderSpan(tree, textSpan, cancellationToken);
if (this.Expression == null)
{
return false;
}
var containingType = this.Expression.AncestorsAndSelf()
.Select(n => this.Document.SemanticModel.GetDeclaredSymbol(n, cancellationToken))
.OfType<INamedTypeSymbol>()
.FirstOrDefault();
containingType = containingType ?? this.Document.SemanticModel.Compilation.ScriptClass;
if (containingType == null || containingType.TypeKind == TypeKind.Interface)
{
return false;
}
if (!CanIntroduceVariable(cancellationToken))
{
return false;
}
this.IsConstant = this.Document.SemanticModel.GetConstantValue(this.Expression, cancellationToken).HasValue;
// Note: the ordering of these clauses are important. They go, generally, from
// innermost to outermost order.
if (IsInQueryContext(cancellationToken))
{
if (CanGenerateInto<TQueryExpressionSyntax>(cancellationToken))
{
this.InQueryContext = true;
return true;
}
return false;
}
if (IsInConstructorInitializerContext(cancellationToken))
{
if (CanGenerateInto<TTypeDeclarationSyntax>(cancellationToken))
{
this.InConstructorInitializerContext = true;
return true;
}
return false;
}
var enclosingBlocks = _service.GetContainingExecutableBlocks(this.Expression);
if (enclosingBlocks.Any())
{
// If we're inside a block, then don't even try the other options (like field,
// constructor initializer, etc.). This is desirable behavior. If we're in a
// block in a field, then we're in a lambda, and we want to offer to generate
// a local, and not a field.
if (IsInBlockContext(cancellationToken))
{
this.InBlockContext = true;
return true;
}
return false;
}
// The ordering of checks is important here. If we are inside a block within an Expression
// bodied member, we should treat it as if we are in block context.
// For example, in such a scenario we should generate inside the block, instead of rewriting
// a concise expression bodied member to its equivalent that has a body with a block.
// For this reason, block should precede expression bodied member check.
if (_service.IsInExpressionBodiedMember(this.Expression))
{
if (CanGenerateInto<TTypeDeclarationSyntax>(cancellationToken))
{
this.InExpressionBodiedMemberContext = true;
return true;
}
return false;
}
if (CanGenerateInto<TTypeDeclarationSyntax>(cancellationToken))
{
if (IsInParameterContext(cancellationToken))
{
this.InParameterContext = true;
return true;
}
else if (IsInFieldContext(cancellationToken))
{
this.InFieldContext = true;
return true;
}
else if (IsInAttributeContext(cancellationToken))
{
this.InAttributeContext = true;
return true;
}
}
return false;
}
public SemanticMap GetSemanticMap(CancellationToken cancellationToken)
{
_semanticMap = _semanticMap ?? this.Document.SemanticModel.GetSemanticMap(this.Expression, cancellationToken);
return _semanticMap;
}
private TExpressionSyntax GetExpressionUnderSpan(SyntaxTree tree, TextSpan textSpan, CancellationToken cancellationToken)
{
var root = tree.GetRoot(cancellationToken);
var startToken = root.FindToken(textSpan.Start);
var stopToken = root.FindToken(textSpan.End);
if (textSpan.End <= stopToken.SpanStart)
{
stopToken = stopToken.GetPreviousToken(includeSkipped: true);
}
if (startToken.RawKind == 0 || stopToken.RawKind == 0)
{
return null;
}
var containingExpressions1 = startToken.GetAncestors<TExpressionSyntax>().ToList();
var containingExpressions2 = stopToken.GetAncestors<TExpressionSyntax>().ToList();
var commonExpression = containingExpressions1.FirstOrDefault(containingExpressions2.Contains);
if (commonExpression == null)
{
return null;
}
if (!(textSpan.Start >= commonExpression.FullSpan.Start &&
textSpan.Start <= commonExpression.SpanStart))
{
return null;
}
if (!(textSpan.End >= commonExpression.Span.End &&
textSpan.End <= commonExpression.FullSpan.End))
{
return null;
}
return commonExpression;
}
private bool CanIntroduceVariable(
CancellationToken cancellationToken)
{
// Don't generate a variable for an expression that's the only expression in a
// statement. Otherwise we'll end up with something like "v;" which is not
// legal in C#.
if (!_service.CanIntroduceVariableFor(this.Expression))
{
return false;
}
if (this.Expression is TTypeSyntax)
{
return false;
}
// Even though we're creating a variable, we still ask if we can be replaced with an
// RValue and not an LValue. This is because introduction of a local adds a *new* LValue
// location, and we want to ensure that any writes will still happen to the *original*
// LValue location. i.e. if you have: "a[1] = b" then you don't want to change that to
// "var c = a[1]; c = b", as that write is no longer happening into the right LValue.
//
// In essense, this says "i can be replaced with an expression as long as i'm not being
// written to".
var semanticFacts = this.Document.Project.LanguageServices.GetService<ISemanticFactsService>();
return semanticFacts.CanReplaceWithRValue(this.Document.SemanticModel, this.Expression, cancellationToken);
}
private bool CanGenerateInto<TSyntax>(CancellationToken cancellationToken)
where TSyntax : SyntaxNode
{
if (this.Document.SemanticModel.Compilation.ScriptClass != null)
{
return true;
}
var syntax = this.Expression.GetAncestor<TSyntax>();
return syntax != null && !syntax.OverlapsHiddenPosition(cancellationToken);
}
private bool IsInTypeDeclarationOrValidCompilationUnit()
{
if (this.Expression.GetAncestorOrThis<TTypeDeclarationSyntax>() != null)
{
return true;
}
// If we're interactive/script, we can generate into the compilation unit.
if (this.Document.Document.SourceCodeKind != SourceCodeKind.Regular)
{
return true;
}
return false;
}
}
}
}
| |
// ObjectValue.cs
//
// Authors: Lluis Sanchez Gual <lluis@novell.com>
// Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2008 Novell, Inc (http://www.novell.com)
// Copyright (c) 2012 Xamarin Inc. (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
using System;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using Mono.Debugging.Backend;
namespace Mono.Debugging.Client
{
[Serializable]
public class ObjectValue
{
ObjectPath path;
int arrayCount = -1;
bool isNull;
string name;
string value;
string typeName;
string displayValue;
string childSelector;
ObjectValueFlags flags;
IObjectValueSource source;
IObjectValueUpdater updater;
List<ObjectValue> children;
ManualResetEvent evaluatedEvent;
[NonSerialized]
readonly object mutex = new object ();
[NonSerialized]
UpdateCallback updateCallback;
[NonSerialized]
EventHandler valueChanged;
[NonSerialized]
StackFrame parentFrame;
static ObjectValue Create (IObjectValueSource source, ObjectPath path, string typeName)
{
var val = new ObjectValue ();
val.typeName = typeName;
val.source = source;
val.path = path;
return val;
}
public static ObjectValue CreateObject (IObjectValueSource source, ObjectPath path, string typeName, string value, ObjectValueFlags flags, ObjectValue[] children)
{
return CreateObject (source, path, typeName, new EvaluationResult (value), flags, children);
}
public static ObjectValue CreateObject (IObjectValueSource source, ObjectPath path, string typeName, EvaluationResult value, ObjectValueFlags flags, ObjectValue[] children)
{
var val = Create (source, path, typeName);
val.flags = flags | ObjectValueFlags.Object;
val.displayValue = value.DisplayValue;
val.value = value.Value;
if (children != null) {
val.children = new List<ObjectValue> ();
val.children.AddRange (children);
}
return val;
}
public static ObjectValue CreateNullObject (IObjectValueSource source, string name, string typeName, ObjectValueFlags flags)
{
return CreateNullObject (source, new ObjectPath (name), typeName, flags);
}
public static ObjectValue CreateNullObject (IObjectValueSource source, ObjectPath path, string typeName, ObjectValueFlags flags)
{
var val = Create (source, path, typeName);
val.flags = flags | ObjectValueFlags.Object;
val.value = "(null)";
val.isNull = true;
return val;
}
public static ObjectValue CreatePrimitive (IObjectValueSource source, ObjectPath path, string typeName, EvaluationResult value, ObjectValueFlags flags)
{
var val = Create (source, path, typeName);
val.flags = flags | ObjectValueFlags.Primitive;
val.displayValue = value.DisplayValue;
val.value = value.Value;
return val;
}
public static ObjectValue CreateArray (IObjectValueSource source, ObjectPath path, string typeName, int arrayCount, ObjectValueFlags flags, ObjectValue[] children)
{
var val = Create (source, path, typeName);
val.flags = flags | ObjectValueFlags.Array;
val.value = "[" + arrayCount + "]";
val.arrayCount = arrayCount;
if (children != null && children.Length > 0) {
val.children = new List<ObjectValue> ();
val.children.AddRange (children);
}
return val;
}
public static ObjectValue CreateUnknown (IObjectValueSource source, ObjectPath path, string typeName)
{
var val = Create (source, path, typeName);
val.flags = ObjectValueFlags.Unknown | ObjectValueFlags.ReadOnly;
return val;
}
public static ObjectValue CreateUnknown (string name)
{
return CreateUnknown (null, new ObjectPath (name), "");
}
public static ObjectValue CreateError (IObjectValueSource source, ObjectPath path, string typeName, string value, ObjectValueFlags flags)
{
var val = Create (source, path, typeName);
val.flags = flags | ObjectValueFlags.Error;
val.value = value;
return val;
}
public static ObjectValue CreateImplicitNotSupported (IObjectValueSource source, ObjectPath path, string typeName, ObjectValueFlags flags)
{
var val = Create (source, path, typeName);
val.flags = flags | ObjectValueFlags.ImplicitNotSupported;
val.value = "Implicit evaluation is disabled";
return val;
}
public static ObjectValue CreateNotSupported (IObjectValueSource source, ObjectPath path, string typeName, string message, ObjectValueFlags flags)
{
var val = Create (source, path, typeName);
val.flags = flags | ObjectValueFlags.NotSupported;
val.value = message;
return val;
}
public static ObjectValue CreateFatalError (string name, string message, ObjectValueFlags flags)
{
var val = new ObjectValue ();
val.flags = flags | ObjectValueFlags.Error;
val.value = message;
val.name = name;
return val;
}
public static ObjectValue CreateEvaluating (IObjectValueUpdater updater, ObjectPath path, ObjectValueFlags flags)
{
var val = Create (null, path, null);
val.flags = flags | ObjectValueFlags.Evaluating;
val.updater = updater;
return val;
}
public static ObjectValue CreateShowMore ()
{
return new ObjectValue () {
flags = ObjectValueFlags.IEnumerable,
name = ""
};
}
public DebuggerSession DebuggerSession {
get {
return parentFrame?.DebuggerSession;
}
}
/// <summary>
/// Gets the flags of the value
/// </summary>
public ObjectValueFlags Flags {
get { return flags; }
}
/// <summary>
/// Name of the value (for example, the property name)
/// </summary>
public string Name {
get { return name ?? path[path.Length - 1]; }
set { name = value; }
}
/// <summary>
/// Gets or sets the value of the object
/// </summary>
/// <value>
/// The value.
/// </value>
/// <exception cref='InvalidOperationException'>
/// Is thrown when trying to set a value on a read-only ObjectValue
/// </exception>
/// <remarks>
/// This value is a string representation of the ObjectValue. The content depends on several evaluation
/// options. For example, if ToString calls are enabled, this value will be the result of calling
/// ToString.
/// If the object is a primitive type, in general the Value will be an expression that represents the
/// value in the target language. For example, when debugging C#, if the property is an string, the value
/// will include the quotation marks and chars like '\' will be properly escaped.
/// If you need to get the real CLR value of the object, use GetRawValue.
/// </remarks>
public virtual string Value {
get {
return value;
}
set {
if (IsReadOnly || source == null)
throw new InvalidOperationException ("Value is not editable");
var res = source.SetValue (path, value, null);
if (res != null) {
this.value = res.Value;
displayValue = res.DisplayValue;
isNull = value == null;
}
}
}
/// <summary>
/// Gets or sets the display value of this object
/// </summary>
/// <remarks>
/// This method returns a string to be used when showing the value of this object.
/// In most cases, the Value and DisplayValue properties return the same text, but there are some cases
/// in which DisplayValue may return a more convenient textual representation of the value, which
/// may not be a valid target language expression.
/// For example in C#, an enum Value includes the full enum type name (e.g. "Gtk.ResponseType.OK"),
/// while DisplayValue only has the enum value name ("OK").
/// </remarks>
public string DisplayValue {
get { return displayValue ?? Value; }
set { displayValue = value; }
}
/// <summary>
/// Sets the value of this object, using the default evaluation options
/// </summary>
public void SetValue (string value)
{
SetValue (value, parentFrame.DebuggerSession.EvaluationOptions);
}
/// <summary>
/// Sets the value of this object, using the specified evaluation options
/// </summary>
/// <param name='value'>
/// The value
/// </param>
/// <param name='options'>
/// The options
/// </param>
/// <exception cref='InvalidOperationException'>
/// Is thrown if the value is read-only
/// </exception>
public void SetValue (string value, EvaluationOptions options)
{
if (IsReadOnly || source == null)
throw new InvalidOperationException ("Value is not editable");
var res = source.SetValue (path, value, options);
if (res != null) {
this.value = res.Value;
displayValue = res.DisplayValue;
}
}
/// <summary>
/// Gets the raw value of this object
/// </summary>
/// <returns>
/// The raw value.
/// </returns>
/// <remarks>
/// This method can be used to get the CLR value of the object. For example, if this ObjectValue is
/// a property of type String, this method will return the System.String value of the property.
/// If this ObjectValue refers to an object instead of a primitive value, then a RawValue object
/// will be returned. RawValue can be used to get and set members of an object, and to call methods.
/// If this ObjectValue refers to an array, then a RawValueArray object will be returned.
/// </remarks>
public object GetRawValue ()
{
var ops = parentFrame.DebuggerSession.EvaluationOptions.Clone ();
ops.EllipsizeStrings = false;
return GetRawValue (ops);
}
/// <summary>
/// Gets the raw value of this object
/// </summary>
/// <param name='options'>
/// The evaluation options
/// </param>
/// <returns>
/// The raw value.
/// </returns>
/// <remarks>
/// This method can be used to get the CLR value of the object. For example, if this ObjectValue is
/// a property of type String, this method will return the System.String value of the property.
/// If this ObjectValue refers to an object instead of a primitive value, then a RawValue object
/// will be returned. RawValue can be used to get and set members of an object, and to call methods.
/// If this ObjectValue refers to an array, then a RawValueArray object will be returned.
/// </remarks>
public object GetRawValue (EvaluationOptions options)
{
if (source == null && (IsEvaluating || IsEvaluatingGroup)) {
if (!WaitHandle.WaitOne (options.EvaluationTimeout)) {
throw new Evaluation.TimeOutException ();
}
}
var res = source.GetRawValue (path, options);
if (res is IRawObject raw)
raw.Connect (parentFrame.DebuggerSession, options);
return res;
}
/// <summary>
/// Sets the raw value of this object
/// </summary>
/// <param name='value'>
/// The value
/// </param>
/// <remarks>
/// The provided value can be a primitive type, a RawValue object or a RawValueArray object.
/// </remarks>
public void SetRawValue (object value)
{
SetRawValue (value, parentFrame.DebuggerSession.EvaluationOptions);
}
/// <summary>
/// Sets the raw value of this object
/// </summary>
/// <param name='value'>
/// The value
/// </param>
/// <param name='options'>
/// The evaluation options
/// </param>
/// <remarks>
/// The provided value can be a primitive type, a RawValue object or a RawValueArray object.
/// </remarks>
public void SetRawValue (object value, EvaluationOptions options)
{
if (source == null && (IsEvaluating || IsEvaluatingGroup)) {
if (!WaitHandle.WaitOne (options.EvaluationTimeout)) {
throw new Evaluation.TimeOutException ();
}
}
source.SetRawValue (path, value, options);
}
/// <summary>
/// Full name of the type of the object
/// </summary>
public string TypeName {
get { return typeName; }
set { typeName = value; }
}
/// <summary>
/// Gets or sets the child selector.
/// </summary>
/// <remarks>
/// The child selector is an expression which can be concatenated to a parent expression to get this child.
/// For example, if this object is a reference to a field named 'foo' of an object, the child
/// selector is '.foo'.
/// </remarks>
public string ChildSelector {
get {
if (childSelector != null)
return childSelector;
if ((flags & ObjectValueFlags.ArrayElement) != 0)
return Name;
return "." + Name;
}
set { childSelector = value; }
}
/// <summary>
/// Gets a value indicating whether this object has children.
/// </summary>
/// <value>
/// <c>true</c> if this instance has children; otherwise, <c>false</c>.
/// </value>
public bool HasChildren {
get {
if (isNull)
return false;
if (IsEvaluating)
return false;
if (children != null)
return children.Count > 0;
if (source == null)
return false;
if (IsArray)
return arrayCount > 0;
if (IsObject)
return true;
return false;
}
}
/// <summary>
/// Gets a child value
/// </summary>
/// <returns>
/// The child.
/// </returns>
/// <param name='name'>
/// Name of the member
/// </param>
/// <remarks>
/// This method can be used to get a member of an object (such as a field or property)
/// </remarks>
public ObjectValue GetChild (string name)
{
return GetChild (name, parentFrame?.DebuggerSession.EvaluationOptions);
}
/// <summary>
/// Gets a child value
/// </summary>
/// <returns>
/// The child.
/// </returns>
/// <param name='name'>
/// Name of the member
/// </param>
/// <param name='options'>
/// Options to be used to evaluate the child
/// </param>
/// <remarks>
/// This method can be used to get a member of an object (such as a field or property)
/// </remarks>
public ObjectValue GetChild (string name, EvaluationOptions options)
{
if (IsArray)
throw new InvalidOperationException ("Object is an array.");
if (IsEvaluating)
return null;
if (children == null) {
children = new List<ObjectValue> ();
if (source != null) {
try {
var cs = source.GetChildren (path, -1, -1, options);
ConnectCallbacks (parentFrame, cs);
children.AddRange (cs);
} catch (Exception ex) {
children = null;
return CreateFatalError ("", ex.Message, ObjectValueFlags.ReadOnly);
}
}
}
foreach (var child in children) {
if (child.Name == name)
return child;
}
return null;
}
/// <summary>
/// Gets all children of the object
/// </summary>
/// <returns>
/// An array of all child values
/// </returns>
public ObjectValue[] GetAllChildren ()
{
return GetAllChildren (parentFrame.DebuggerSession.EvaluationOptions);
}
/// <summary>
/// Gets all children of the object
/// </summary>
/// <returns>
/// An array of all child values
/// </returns>
/// <param name='options'>
/// Options to be used to evaluate the children
/// </param>
public ObjectValue[] GetAllChildren (EvaluationOptions options)
{
if (IsEvaluating)
return new ObjectValue[0];
if (IsArray) {
GetArrayItem (arrayCount - 1);
return children.ToArray ();
}
if (children == null) {
children = new List<ObjectValue> ();
if (source != null) {
try {
var cs = source.GetChildren (path, -1, -1, options);
ConnectCallbacks (parentFrame, cs);
children.AddRange (cs);
} catch (Exception ex) {
if (parentFrame != null)
parentFrame.DebuggerSession.OnDebuggerOutput (true, ex.ToString ());
children.Add (CreateFatalError ("", ex.Message, ObjectValueFlags.ReadOnly));
}
}
}
return children.ToArray ();
}
public ObjectValue[] GetRangeOfChildren (int index, int count)
{
return GetRangeOfChildren (index, count, parentFrame.DebuggerSession.EvaluationOptions);
}
public ObjectValue[] GetRangeOfChildren (int index, int count, EvaluationOptions options)
{
if (IsEvaluating)
return new ObjectValue[0];
if (IsArray) {
GetArrayItem (arrayCount - 1);
if (index >= ArrayCount)
return new ObjectValue[0];
return children.Skip (index).Take (Math.Min (count, ArrayCount - index)).ToArray ();
}
if (children == null) {
children = new List<ObjectValue> ();
}
if (children.Count < index + count) {
if (source != null) {
try {
ObjectValue[] cs = source.GetChildren (path, children.Count, index + count, options);
ConnectCallbacks (parentFrame, cs);
children.AddRange (cs);
} catch (Exception ex) {
if (parentFrame != null)
parentFrame.DebuggerSession.OnDebuggerOutput (true, ex.ToString ());
children.Add (CreateFatalError ("", ex.Message, ObjectValueFlags.ReadOnly));
}
}
}
if (index >= children.Count)
return new ObjectValue[0];
return children.Skip (index).Take (Math.Min (count, children.Count - index)).ToArray ();
}
/// <summary>
/// Gets an item of an array
/// </summary>
/// <returns>
/// The array item.
/// </returns>
/// <param name='index'>
/// Item index
/// </param>
/// <exception cref='InvalidOperationException'>
/// Is thrown if this object is not an array (IsArray returns false)
/// </exception>
public ObjectValue GetArrayItem (int index)
{
return GetArrayItem (index, parentFrame.DebuggerSession.EvaluationOptions);
}
/// <summary>
/// Gets an item of an array
/// </summary>
/// <returns>
/// The array item.
/// </returns>
/// <param name='index'>
/// Item index
/// </param>
/// <param name='options'>
/// Options to be used to evaluate the item
/// </param>
/// <exception cref='InvalidOperationException'>
/// Is thrown if this object is not an array (IsArray returns false)
/// </exception>
public ObjectValue GetArrayItem (int index, EvaluationOptions options)
{
if (!IsArray)
throw new InvalidOperationException ("Object is not an array.");
if (index >= arrayCount || index < 0 || IsEvaluating)
throw new IndexOutOfRangeException ();
if (children == null)
children = new List<ObjectValue> ();
if (index >= children.Count) {
int nc = (index + 50);
if (nc > arrayCount)
nc = arrayCount;
nc = nc - children.Count;
try {
var items = source.GetChildren (path, children.Count, nc, options);
ConnectCallbacks (parentFrame, items);
children.AddRange (items);
} catch (Exception ex) {
return CreateFatalError ("", ex.Message, ObjectValueFlags.ArrayElement | ObjectValueFlags.ReadOnly);
}
}
return children [index];
}
/// <summary>
/// Gets the number of items of an array
/// </summary>
/// <exception cref='InvalidOperationException'>
/// Is thrown if this object is not an array (IsArray returns false)
/// </exception>
public int ArrayCount {
get {
if (!IsArray)
throw new InvalidOperationException ("Object is not an array.");
if (IsEvaluating)
return 0;
return arrayCount;
}
}
public bool IsNull {
get { return isNull; }
}
public bool IsReadOnly {
get { return HasFlag (ObjectValueFlags.ReadOnly); }
}
public bool IsArray {
get { return HasFlag (ObjectValueFlags.Array); }
}
public bool IsObject {
get { return HasFlag (ObjectValueFlags.Object); }
}
public bool IsPrimitive {
get { return HasFlag (ObjectValueFlags.Primitive); }
}
public bool IsUnknown {
get { return HasFlag (ObjectValueFlags.Unknown); }
}
public bool IsNotSupported {
get { return HasFlag (ObjectValueFlags.NotSupported); }
}
public bool IsImplicitNotSupported {
get { return HasFlag (ObjectValueFlags.ImplicitNotSupported); }
}
public bool IsError {
get { return HasFlag (ObjectValueFlags.Error); }
}
public bool IsEvaluating {
get { return HasFlag (ObjectValueFlags.Evaluating); }
}
public bool IsEvaluatingGroup {
get { return HasFlag (ObjectValueFlags.EvaluatingGroup); }
}
public bool CanRefresh {
get { return source != null && !HasFlag (ObjectValueFlags.NoRefresh); }
}
public bool HasFlag (ObjectValueFlags flag)
{
return (flags & flag) != 0;
}
public event EventHandler ValueChanged {
add {
lock (mutex) {
valueChanged += value;
if (!IsEvaluating)
value (this, EventArgs.Empty);
}
}
remove {
lock (mutex) {
valueChanged -= value;
}
}
}
/// <summary>
/// Refreshes the value of this object
/// </summary>
/// <remarks>
/// This method can be called to get a more up-to-date value for this object.
/// </remarks>
public void Refresh ()
{
Refresh (parentFrame.DebuggerSession.EvaluationOptions);
}
/// <summary>
/// Refreshes the value of this object
/// </summary>
/// <remarks>
/// This method can be called to get a more up-to-date value for this object.
/// </remarks>
public void Refresh (EvaluationOptions options)
{
if (!CanRefresh)
return;
var val = source.GetValue (path, options);
UpdateFrom (val, true);
}
/// <summary>
/// Gets a wait handle which can be used to wait for the evaluation of this object to end
/// </summary>
/// <value>
/// The wait handle.
/// </value>
public WaitHandle WaitHandle {
get {
lock (mutex) {
if (evaluatedEvent == null)
evaluatedEvent = new ManualResetEvent (!IsEvaluating);
return evaluatedEvent;
}
}
}
internal IObjectValueUpdater Updater {
get { return updater; }
}
internal void UpdateFrom (ObjectValue val, bool notify)
{
lock (mutex) {
arrayCount = val.arrayCount;
if (val.name != null)
name = val.name;
value = val.value;
displayValue = val.displayValue;
typeName = val.typeName;
flags = val.flags;
source = val.source;
children = val.children;
path = val.path;
updater = val.updater;
ConnectCallbacks (parentFrame, this);
if (evaluatedEvent != null)
evaluatedEvent.Set ();
if (notify && valueChanged != null)
valueChanged (this, EventArgs.Empty);
}
}
internal UpdateCallback GetUpdateCallback ()
{
if (IsEvaluating) {
if (updateCallback == null)
updateCallback = new UpdateCallback (new UpdateCallbackProxy (this), path);
return updateCallback;
}
return null;
}
~ObjectValue ()
{
#if !NETCOREAPP
if (updateCallback != null)
System.Runtime.Remoting.RemotingServices.Disconnect ((UpdateCallbackProxy)updateCallback.Callback);
#endif
}
internal static void ConnectCallbacks (StackFrame parentFrame, params ObjectValue[] values)
{
Dictionary<IObjectValueUpdater, List<UpdateCallback>> callbacks = null;
var valueList = new List<ObjectValue> (values);
for (int n = 0; n < valueList.Count; n++) {
var val = valueList [n];
val.source = parentFrame.DebuggerSession.WrapDebuggerObject (val.source);
val.updater = parentFrame.DebuggerSession.WrapDebuggerObject (val.updater);
val.parentFrame = parentFrame;
var cb = val.GetUpdateCallback ();
if (cb != null) {
if (callbacks == null)
callbacks = new Dictionary<IObjectValueUpdater, List<UpdateCallback>> ();
List<UpdateCallback> list;
if (!callbacks.TryGetValue (val.Updater, out list)) {
list = new List<UpdateCallback> ();
callbacks [val.Updater] = list;
}
list.Add (cb);
}
if (val.children != null)
valueList.AddRange (val.children);
}
if (callbacks != null) {
// Do the callback connection in a background thread
ThreadPool.QueueUserWorkItem (delegate {
foreach (KeyValuePair<IObjectValueUpdater, List<UpdateCallback>> cbs in callbacks) {
cbs.Key.RegisterUpdateCallbacks (cbs.Value.ToArray ());
}
});
}
}
}
class UpdateCallbackProxy: MarshalByRefObject, IObjectValueUpdateCallback
{
readonly WeakReference valRef;
public void UpdateValue (ObjectValue newValue)
{
var val = valRef.Target as ObjectValue;
if (val != null)
val.UpdateFrom (newValue, true);
}
public UpdateCallbackProxy (ObjectValue val)
{
valRef = new WeakReference (val);
}
}
}
| |
/// <summary>
/// This class handles sending data to the Game Analytics servers.
/// JSON data is sent using a MD5 hashed authorization header, containing the JSON data and private key
/// </summary>
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System;
//using LitJson;
using System.Linq;
#if !UNITY_FLASH && !UNITY_WP8 && !UNITY_METRO
using System.Security.Cryptography;
#endif
#if UNITY_METRO && !UNITY_EDITOR
using GA_Compatibility.Collections;
#endif
public class GA_Submit
{
/// <summary>
/// Handlers for success and fail during submit to the GA server
/// </summary>
public delegate void SubmitSuccessHandler(List<Item> items, bool success);
public delegate void SubmitErrorHandler(List<Item> items);
/// <summary>
/// Types of services on the GA server
/// </summary>
public enum CategoryType { GA_User, GA_Event, GA_Log, GA_Purchase, GA_Error }
/// <summary>
/// An item is a message (parameters) and the category (GA service) the message should be sent to
/// </summary>
public struct Item
{
public CategoryType Type;
public Hashtable Parameters;
public float AddTime;
public int Count;
}
/// <summary>
/// All the different types of GA services
/// </summary>
public Dictionary<CategoryType, string> Categories;
#region private values
private string _publicKey;
private string _privateKey;
private string _baseURL = "://api.gameanalytics.com";
private string _version = "1";
#endregion
#region public methods
/// <summary>
/// Sets the users public and private keys for the GA server
/// </summary>
/// <param name="publicKey">
/// The public key which identifies this users game <see cref="System.String"/>
/// </param>
/// <param name="privateKey">
/// The private key used to encode messages <see cref="System.String"/>
/// </param>
public void SetupKeys(string publicKey, string privateKey)
{
_publicKey = publicKey;
_privateKey = privateKey;
Categories = new Dictionary<CategoryType, string>()
{
{ CategoryType.GA_User, "user" },
{ CategoryType.GA_Event, "design" },
{ CategoryType.GA_Log, "quality" },
{ CategoryType.GA_Purchase, "business" },
{ CategoryType.GA_Error, "error" }
};
}
/// <summary>
/// Devides a list of messages into categories and calls Submit to send the messages to the GA servers.
/// </summary>
/// <param name="item">
/// The list of messages (queue) <see cref="Item"/>
/// </param>
/// <param name="successEvent">
/// If successful this will be fired <see cref="SubmitSuccessHandler"/>
/// </param>
/// <param name="errorEvent">
/// If an error occurs this will be fired <see cref="SubmitErrorHandler"/>
/// </param>
public void SubmitQueue(List<Item> queue, SubmitSuccessHandler successEvent, SubmitErrorHandler errorEvent, bool gaTracking, string pubKey, string priKey)
{
if ((_publicKey.Equals("") || _privateKey.Equals("")) && (pubKey.Equals("") || priKey.Equals("")))
{
if (!gaTracking)
GA.LogError("Game Key and/or Secret Key not set. Open GA_Settings to set keys.");
return;
}
//GA_TODO: Optimize by moving dictionary outside this fucntion. Submit is called often
Dictionary<CategoryType, List<Item>> categories = new Dictionary<CategoryType, List<Item>>();
/* Put all the items in the queue into a list containing only the messages of that category type.
* This way we end up with a list of items for each category type */
foreach (Item item in queue)
{
if (categories.ContainsKey(item.Type))
{
/* If we already added another item of this type then remove the UserID, SessionID, and Build values if necessary.
* These values only need to be present in each message once, since they will be the same for all items */
/* TODO: below not supported yet in API (exclude information)
* activate once redundant data can be trimmed */
/*
if (item.Parameters.ContainsKey(GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.UserID]))
item.Parameters.Remove(GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.UserID]);
if (item.Parameters.ContainsKey(GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.SessionID]))
item.Parameters.Remove(GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.SessionID]);
if (item.Parameters.ContainsKey(GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.Build]))
item.Parameters.Remove(GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.Build]);
*/
/* TODO: remove below when API supports exclusion of data */
if (!item.Parameters.ContainsKey(GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.UserID]))
item.Parameters.Add(GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.UserID], GA.API.GenericInfo.UserID);
if (!item.Parameters.ContainsKey(GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.SessionID]))
item.Parameters.Add(GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.SessionID], GA.API.GenericInfo.SessionID);
if (!item.Parameters.ContainsKey(GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.Build]))
item.Parameters.Add(GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.Build], GA.SettingsGA.Build);
categories[item.Type].Add(item);
}
else
{
/* If we did not add another item of this type yet, then add the UserID, SessionID, and Build values if necessary.
* These values only need to be present in each message once, since they will be the same for all items */
if (!item.Parameters.ContainsKey(GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.UserID]))
item.Parameters.Add(GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.UserID], GA.API.GenericInfo.UserID);
if (!item.Parameters.ContainsKey(GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.SessionID]))
item.Parameters.Add(GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.SessionID], GA.API.GenericInfo.SessionID);
if (!item.Parameters.ContainsKey(GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.Build]))
item.Parameters.Add(GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.Build], GA.SettingsGA.Build);
categories.Add(item.Type, new List<Item> { item });
}
}
GA.RunCoroutine(Submit(categories, successEvent, errorEvent, gaTracking, pubKey, priKey));
}
/// <summary>
/// Takes a dictionary with a item list for each category type. All items in each category are submitted together to the GA server.
/// </summary>
/// <param name="item">
/// The list of items, each holding a message and service type <see cref="Item"/>
/// </param>
/// <param name="successEvent">
/// If successful this will be fired <see cref="SubmitSuccessHandler"/>
/// </param>
/// <param name="errorEvent">
/// If an error occurs this will be fired <see cref="SubmitErrorHandler"/>
/// </param>
/// <returns>
/// A <see cref="IEnumerator"/>
/// </returns>
public IEnumerator Submit(Dictionary<CategoryType, List<Item>> categories, SubmitSuccessHandler successEvent, SubmitErrorHandler errorEvent, bool gaTracking, string pubKey, string priKey)
{
if (pubKey.Equals(""))
pubKey = _publicKey;
if (priKey.Equals(""))
priKey = _privateKey;
//For each existing category, submit a message containing all the items of that category type
foreach (KeyValuePair<CategoryType, List<Item>> kvp in categories)
{
List<Item> items = kvp.Value;
if (items.Count == 0)
{
yield break;
}
//Since all the items must have the same category (we make sure they do below) we can get the category from the first item
CategoryType serviceType = items[0].Type;
string url = GetURL(Categories[serviceType], pubKey);
//Make sure that all items are of the same category type, and put all the parameter collections into a list
List<Hashtable> itemsParameters = new List<Hashtable>();
for (int i = 0; i < items.Count; i++)
{
if (serviceType != items[i].Type)
{
GA.LogWarning("GA Error: All messages in a submit must be of the same service/category type.");
if (errorEvent != null)
{
errorEvent(items);
}
yield break;
}
// if user ID is missing from the item add it now (could f.x. happen if custom user id is enabled,
// and the item was added before the custom user id was provided)
if (!items[i].Parameters.ContainsKey(GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.UserID]))
items[i].Parameters.Add(GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.UserID], GA.API.GenericInfo.UserID);
else if (items[i].Parameters[GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.UserID]] == null)
items[i].Parameters[GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.UserID]] = GA.API.GenericInfo.UserID;
Hashtable parameters;
if (items[i].Count > 1)
{
/* so far we don't do anything special with stacked messages - we just send a single message
* GA_TODO: stacked messages should be handle correctly.*/
parameters = items[i].Parameters;
}
else
{
parameters = items[i].Parameters;
}
itemsParameters.Add(parameters);
}
//Make a JSON array string out of the list of parameter collections
string json = DictToJson(itemsParameters);
/* If we do not have access to a network connection (or we are roaming (mobile devices) and GA_static_api.Settings.ALLOWROAMING is false),
* and data is set to be archived, then archive the data and pretend the message was sent successfully */
if (GA.SettingsGA.ArchiveData && !gaTracking && !GA.SettingsGA.InternetConnectivity)
{
if (GA.SettingsGA.DebugMode)
{
GA.Log("GA: Archiving data (no network connection).");
}
GA.API.Archive.ArchiveData(json, serviceType);
if (successEvent != null)
{
successEvent(items, true);
}
yield break;
}
else if (!GA.SettingsGA.InternetConnectivity)
{
if (!gaTracking)
GA.LogWarning("GA Error: No network connection.");
if (errorEvent != null)
{
errorEvent(items);
}
yield break;
}
//Prepare the JSON array string for sending by converting it to a byte array
byte[] data = Encoding.UTF8.GetBytes(json);
WWW www = null;
#if !UNITY_WP8 && !UNITY_METRO
//Set the authorization header to contain an MD5 hash of the JSON array string + the private key
Hashtable headers = new Hashtable();
headers.Add("Authorization", CreateMD5Hash(json + priKey));
//headers.Add("Content-Length", data.Length);
//Try to send the data
www = new WWW(url, data, headers);
#else
//Set the authorization header to contain an MD5 hash of the JSON array string + the private key
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("Authorization", CreateMD5Hash(json + priKey));
//headers.Add("Content-Length", data.Length.ToString());
//Try to send the data
www = new WWW(url, data, headers);
#endif
#if !UNITY_FLASH && !UNITY_WP8 && !UNITY_METRO
//Set thread priority low
www.threadPriority = ThreadPriority.Low;
#endif
//Wait for response
yield return www;
if (GA.SettingsGA.DebugMode && !gaTracking)
{
GA.Log("GA URL: " + url);
GA.Log("GA Submit: " + json);
GA.Log("GA Hash: " + CreateMD5Hash(json + priKey));
}
try
{
if (!string.IsNullOrEmpty(www.error) && !CheckServerReply(www))
{
throw new Exception(www.error);
}
//Get the JSON object from the response
Hashtable returnParam = (Hashtable)GA_MiniJSON.JsonDecode(www.text);
//If the response contains the key "status" with the value "ok" we know that the message was sent and recieved successfully
if ((returnParam != null &&
returnParam.ContainsKey("status") && returnParam["status"].ToString().Equals("ok")) ||
CheckServerReply(www))
{
if (GA.SettingsGA.DebugMode && !gaTracking)
{
GA.Log("GA Result: " + www.text);
}
if (successEvent != null)
{
successEvent(items, true);
}
}
else
{
/* The message was not sent and recieved successfully: Stop submitting all together if something
* is completely wrong and we know we will not be able to submit any messages at all..
* Such as missing or invalid public and/or private keys */
if (returnParam != null &&
returnParam.ContainsKey("message") && returnParam["message"].ToString().Equals("Game not found") &&
returnParam.ContainsKey("code") && returnParam["code"].ToString().Equals("400"))
{
if (!gaTracking)
GA.LogWarning("GA Error: " + www.text + " (NOTE: make sure your Game Key and Secret Key match the keys you recieved from the Game Analytics website. It might take a few minutes before a newly added game will be able to recieve data.)");
//An error event with a null parameter will stop the GA wrapper from submitting messages
if (errorEvent != null)
{
errorEvent(null);
}
}
else
{
if (!gaTracking)
GA.LogWarning("GA Error: " + www.text);
if (errorEvent != null)
{
errorEvent(items);
}
}
}
}
catch (Exception e)
{
if (!gaTracking)
GA.LogWarning("GA Error: " + e.Message);
/* If we hit one of these errors we should not attempt to send the message again
* (if necessary we already threw a GA Error which may be tracked) */
if (e.Message.Contains("400 Bad Request"))
{
//An error event with a null parameter will stop the GA wrapper from submitting messages
if (errorEvent != null)
{
errorEvent(null);
}
}
else
{
if (errorEvent != null)
{
errorEvent(items);
}
}
}
}
}
/// <summary>
/// Gets the base url to the GA server
/// </summary>
/// <param name="inclVersion">
/// Should the version be included? <see cref="System.Boolean"/>
/// </param>
/// <returns>
/// A string representing the base url (+ version if inclVersion is true) <see cref="System.String"/>
/// </returns>
public string GetBaseURL(bool inclVersion)
{
if (inclVersion)
return GetUrlStart() + _baseURL + "/" + _version;
return GetUrlStart() + _baseURL;
}
/// <summary>
/// Gets the url on the GA server matching the specific service we are interested in
/// </summary>
/// <param name="category">
/// Determines the GA service/category <see cref="System.String"/>
/// </param>
/// <returns>
/// A string representing the url matching our service choice on the GA server <see cref="System.String"/>
/// </returns>
public string GetURL(string category, string pubKey)
{
return GetUrlStart() + _baseURL + "/" + _version + "/" + pubKey + "/" + category;
}
private string GetUrlStart()
{
if (Application.absoluteURL.StartsWith("https"))
return "https";
else
return "http";
}
/// <summary>
/// Encodes the input as a MD5 hash
/// </summary>
/// <param name="input">
/// The input we want encoded <see cref="System.String"/>
/// </param>
/// <returns>
/// The MD5 hash encoded result of input <see cref="System.String"/>
/// </returns>
public string CreateMD5Hash(string input)
{
#if !UNITY_FLASH && !UNITY_WP8 && !UNITY_METRO
// Gets the MD5 hash for input
MD5 md5 = new MD5CryptoServiceProvider();
byte[] data = Encoding.UTF8.GetBytes(input);
byte[] hash = md5.ComputeHash(data);
// Transforms as hexa
string hexaHash = "";
foreach (byte b in hash) {
hexaHash += String.Format("{0:x2}", b);
}
// Returns MD5 hexa hash as string
return hexaHash;
#elif UNITY_WP8 || UNITY_METRO
byte[] data = Encoding.UTF8.GetBytes(input);
byte[] hash = MD5Core.GetHash(data);
// Transforms as hexa
string hexaHash = "";
foreach (byte b in hash) {
hexaHash += String.Format("{0:x2}", b);
}
// Returns MD5 hexa hash as string
return hexaHash;
#else
return MD5Wrapper.Md5Sum(input);
#endif
}
/// <summary>
/// Encodes the input as a MD5 hash
/// </summary>
/// <param name="input">
/// The input we want encoded <see cref="System.String"/>
/// </param>
/// <returns>
/// The MD5 hash encoded result of input <see cref="System.String"/>
/// </returns>
/*public string CreateMD5Hash(byte[] input)
{
#if !UNITY_FLASH
// Gets the MD5 hash for input
MD5 md5 = new MD5CryptoServiceProvider();
byte[] hash = md5.ComputeHash(input);
// Transforms as hexa
string hexaHash = "";
foreach (byte b in hash) {
hexaHash += String.Format("{0:x2}", b);
}
// Returns MD5 hexa hash as string
return hexaHash;
#else
return MD5Wrapper.Md5Sum(input.ToString());
#endif
}*/
/// <summary>
/// Encodes the input as a sha1 hash
/// </summary>
/// <param name="input">
/// The input we want to encoded <see cref="System.String"/>
/// </param>
/// <returns>
/// The sha1 hash encoded result of input <see cref="System.String"/>
/// </returns>
#if !UNITY_FLASH && !UNITY_WP8 && !UNITY_METRO
public string CreateSha1Hash(string input)
{
// Gets the sha1 hash for input
SHA1 sha1 = new SHA1CryptoServiceProvider();
byte[] data = Encoding.UTF8.GetBytes(input);
byte[] hash = sha1.ComputeHash(data);
// Returns sha1 hash as string
return Convert.ToBase64String(hash);
}
public string GetPrivateKey()
{
return _privateKey;
}
#endif
#endregion
#region private methods
/// <summary>
/// Check if a reply from the server was accepted. All response codes from 200 to 299 are accepted.
/// </summary>
/// <param name="www">
/// The www object which contains response headers
/// </param>
/// <returns>
/// Return true if response code is from 200 to 299. Otherwise returns false.
/// </returns>
public bool CheckServerReply(WWW www)
{
try
{
if (!string.IsNullOrEmpty(www.error))
{
string errStart = www.error.Substring(0, 3);
if (errStart.Equals("201") || errStart.Equals("202") || errStart.Equals("203") || errStart.Equals("204") || errStart.Equals("205") || errStart.Equals("206"))
return true;
}
if (!www.responseHeaders.ContainsKey("STATUS"))
return false;
string status = www.responseHeaders["STATUS"];
string[] splitStatus = status.Split(' ');
int responseCode;
if (splitStatus.Length > 1 && int.TryParse(splitStatus[1], out responseCode))
{
if (responseCode >= 200 && responseCode < 300)
return true;
}
return false;
}
catch
{
return false;
}
}
#endregion
/// <summary>
/// Dicts to json. This function is 35% faster than the LitJson library.
/// </summary>
/// <returns>
/// The to json.
/// </returns>
/// <param name='list'>
/// List.
/// </param>
public static string DictToJson(List<Hashtable> list)
{
string b = "[";
int d = 0;
int c = 0;
foreach(var dict in list)
{
b += '{';
c = 0;
foreach(var key in dict.Keys)
{
c++;
b += "\""+key+"\":\""+dict[key]+"\"";
if(c<dict.Keys.Count)
b += ',';
}
b += '}';
d++;
if(d<list.Count)
b += ',';
}
b += "]";
return b;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans.Metadata;
using Orleans.Runtime.GrainDirectory;
using Orleans.Runtime.MembershipService;
using Orleans.Versions;
using Orleans.Versions.Compatibility;
using Orleans.Versions.Selector;
namespace Orleans.Runtime.Management
{
/// <summary>
/// Implementation class for the Orleans management grain.
/// </summary>
internal class ManagementGrain : Grain, IManagementGrain
{
private readonly IInternalGrainFactory internalGrainFactory;
private readonly ISiloStatusOracle siloStatusOracle;
private readonly IVersionStore versionStore;
private readonly MembershipTableManager membershipTableManager;
private readonly GrainManifest siloManifest;
private readonly ClusterManifest clusterManifest;
private readonly ILogger logger;
private readonly Catalog catalog;
private readonly GrainLocator grainLocator;
public ManagementGrain(
IInternalGrainFactory internalGrainFactory,
ISiloStatusOracle siloStatusOracle,
IVersionStore versionStore,
ILogger<ManagementGrain> logger,
MembershipTableManager membershipTableManager,
IClusterManifestProvider clusterManifestProvider,
Catalog catalog,
GrainLocator grainLocator)
{
this.membershipTableManager = membershipTableManager;
this.siloManifest = clusterManifestProvider.LocalGrainManifest;
this.clusterManifest = clusterManifestProvider.Current;
this.internalGrainFactory = internalGrainFactory;
this.siloStatusOracle = siloStatusOracle;
this.versionStore = versionStore;
this.logger = logger;
this.catalog = catalog;
this.grainLocator = grainLocator;
}
public async Task<Dictionary<SiloAddress, SiloStatus>> GetHosts(bool onlyActive = false)
{
await this.membershipTableManager.Refresh();
return this.siloStatusOracle.GetApproximateSiloStatuses(onlyActive);
}
public async Task<MembershipEntry[]> GetDetailedHosts(bool onlyActive = false)
{
logger.Info("GetDetailedHosts onlyActive={0}", onlyActive);
await this.membershipTableManager.Refresh();
var table = this.membershipTableManager.MembershipTableSnapshot;
MembershipEntry[] result;
if (onlyActive)
{
result = table.Entries
.Where(item => item.Value.Status == SiloStatus.Active)
.Select(x => x.Value)
.ToArray();
}
else
{
result = table.Entries
.Select(x => x.Value)
.ToArray();
}
return result;
}
public Task ForceGarbageCollection(SiloAddress[] siloAddresses)
{
var silos = GetSiloAddresses(siloAddresses);
logger.Info("Forcing garbage collection on {0}", Utils.EnumerableToString(silos));
List<Task> actionPromises = PerformPerSiloAction(silos,
s => GetSiloControlReference(s).ForceGarbageCollection());
return Task.WhenAll(actionPromises);
}
public Task ForceActivationCollection(SiloAddress[] siloAddresses, TimeSpan ageLimit)
{
var silos = GetSiloAddresses(siloAddresses);
return Task.WhenAll(GetSiloAddresses(silos).Select(s =>
GetSiloControlReference(s).ForceActivationCollection(ageLimit)));
}
public async Task ForceActivationCollection(TimeSpan ageLimit)
{
Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true);
SiloAddress[] silos = hosts.Keys.ToArray();
await ForceActivationCollection(silos, ageLimit);
}
public Task ForceRuntimeStatisticsCollection(SiloAddress[] siloAddresses)
{
var silos = GetSiloAddresses(siloAddresses);
logger.Info("Forcing runtime statistics collection on {0}", Utils.EnumerableToString(silos));
List<Task> actionPromises = PerformPerSiloAction(
silos,
s => GetSiloControlReference(s).ForceRuntimeStatisticsCollection());
return Task.WhenAll(actionPromises);
}
public Task<SiloRuntimeStatistics[]> GetRuntimeStatistics(SiloAddress[] siloAddresses)
{
var silos = GetSiloAddresses(siloAddresses);
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("GetRuntimeStatistics on {0}", Utils.EnumerableToString(silos));
var promises = new List<Task<SiloRuntimeStatistics>>();
foreach (SiloAddress siloAddress in silos)
promises.Add(GetSiloControlReference(siloAddress).GetRuntimeStatistics());
return Task.WhenAll(promises);
}
public async Task<SimpleGrainStatistic[]> GetSimpleGrainStatistics(SiloAddress[] hostsIds)
{
var all = GetSiloAddresses(hostsIds).Select(s =>
GetSiloControlReference(s).GetSimpleGrainStatistics()).ToList();
await Task.WhenAll(all);
return all.SelectMany(s => s.Result).ToArray();
}
public async Task<SimpleGrainStatistic[]> GetSimpleGrainStatistics()
{
Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true);
SiloAddress[] silos = hosts.Keys.ToArray();
return await GetSimpleGrainStatistics(silos);
}
public async Task<DetailedGrainStatistic[]> GetDetailedGrainStatistics(string[] types = null, SiloAddress[] hostsIds = null)
{
if (hostsIds == null)
{
Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true);
hostsIds = hosts.Keys.ToArray();
}
var all = GetSiloAddresses(hostsIds).Select(s =>
GetSiloControlReference(s).GetDetailedGrainStatistics(types)).ToList();
await Task.WhenAll(all);
return all.SelectMany(s => s.Result).ToArray();
}
public async Task<int> GetGrainActivationCount(GrainReference grainReference)
{
Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true);
List<SiloAddress> hostsIds = hosts.Keys.ToList();
var tasks = new List<Task<DetailedGrainReport>>();
foreach (var silo in hostsIds)
tasks.Add(GetSiloControlReference(silo).GetDetailedGrainReport(grainReference.GrainId));
await Task.WhenAll(tasks);
return tasks.Select(s => s.Result).Select(r => r.LocalActivations.Count).Sum();
}
public async Task SetCompatibilityStrategy(CompatibilityStrategy strategy)
{
await SetStrategy(
store => store.SetCompatibilityStrategy(strategy),
siloControl => siloControl.SetCompatibilityStrategy(strategy));
}
public async Task SetSelectorStrategy(VersionSelectorStrategy strategy)
{
await SetStrategy(
store => store.SetSelectorStrategy(strategy),
siloControl => siloControl.SetSelectorStrategy(strategy));
}
public async Task SetCompatibilityStrategy(GrainInterfaceType interfaceType, CompatibilityStrategy strategy)
{
CheckIfIsExistingInterface(interfaceType);
await SetStrategy(
store => store.SetCompatibilityStrategy(interfaceType, strategy),
siloControl => siloControl.SetCompatibilityStrategy(interfaceType, strategy));
}
public async Task SetSelectorStrategy(GrainInterfaceType interfaceType, VersionSelectorStrategy strategy)
{
CheckIfIsExistingInterface(interfaceType);
await SetStrategy(
store => store.SetSelectorStrategy(interfaceType, strategy),
siloControl => siloControl.SetSelectorStrategy(interfaceType, strategy));
}
public async Task<int> GetTotalActivationCount()
{
Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true);
List<SiloAddress> silos = hosts.Keys.ToList();
var tasks = new List<Task<int>>();
foreach (var silo in silos)
tasks.Add(GetSiloControlReference(silo).GetActivationCount());
await Task.WhenAll(tasks);
int sum = 0;
foreach (Task<int> task in tasks)
sum += task.Result;
return sum;
}
public Task<object[]> SendControlCommandToProvider(string providerTypeFullName, string providerName, int command, object arg)
{
return ExecutePerSiloCall(isc => isc.SendControlCommandToProvider(providerTypeFullName, providerName, command, arg),
String.Format("SendControlCommandToProvider of type {0} and name {1} command {2}.", providerTypeFullName, providerName, command));
}
public ValueTask<SiloAddress> GetActivationAddress(IAddressable reference)
{
var grainReference = reference as GrainReference;
var grainId = grainReference.GrainId;
GrainProperties grainProperties = default;
if (!siloManifest.Grains.TryGetValue(grainId.Type, out grainProperties))
{
var grainManifest = clusterManifest.AllGrainManifests
.SelectMany(m => m.Grains.Where(g => g.Key == grainId.Type))
.FirstOrDefault();
if (grainManifest.Value != null)
{
grainProperties = grainManifest.Value;
}
else
{
throw new ArgumentException($"Unable to find Grain type '{grainId.Type}'. Make sure it is added to the Application Parts Manager at the Silo configuration.");
}
}
if (grainProperties != default &&
grainProperties.Properties.TryGetValue(WellKnownGrainTypeProperties.PlacementStrategy, out string placementStrategy))
{
if (placementStrategy == nameof(StatelessWorkerPlacement))
{
throw new InvalidOperationException(
$"Grain '{grainReference.ToString()}' is a Stateless Worker. This type of grain can't be looked up by this method"
);
}
}
if (grainLocator.TryLocalLookup(grainId, out var result))
{
return new ValueTask<SiloAddress>(result?.Silo);
}
return LookupAsync(grainId, grainLocator);
static async ValueTask<SiloAddress> LookupAsync(GrainId grainId, GrainLocator grainLocator)
{
var result = await grainLocator.Lookup(grainId);
return result?.Silo;
}
}
private void CheckIfIsExistingInterface(GrainInterfaceType interfaceType)
{
GrainInterfaceType lookupId;
if (GenericGrainInterfaceType.TryParse(interfaceType, out var generic))
{
lookupId = generic.Value;
}
else
{
lookupId = interfaceType;
}
if (!this.siloManifest.Interfaces.TryGetValue(lookupId, out _))
{
throw new ArgumentException($"Interface '{interfaceType} not found", nameof(interfaceType));
}
}
private async Task SetStrategy(Func<IVersionStore, Task> storeFunc, Func<ISiloControl, Task> applyFunc)
{
await storeFunc(versionStore);
var silos = GetSiloAddresses(null);
var actionPromises = PerformPerSiloAction(
silos,
s => applyFunc(GetSiloControlReference(s)));
try
{
await Task.WhenAll(actionPromises);
}
catch (Exception)
{
// ignored: silos that failed to set the new strategy will reload it from the storage
// in the future.
}
}
private async Task<object[]> ExecutePerSiloCall(Func<ISiloControl, Task<object>> action, string actionToLog)
{
var silos = await GetHosts(true);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.Debug("Executing {0} against {1}", actionToLog, Utils.EnumerableToString(silos.Keys));
}
var actionPromises = new List<Task<object>>();
foreach (SiloAddress siloAddress in silos.Keys.ToArray())
actionPromises.Add(action(GetSiloControlReference(siloAddress)));
return await Task.WhenAll(actionPromises);
}
private SiloAddress[] GetSiloAddresses(SiloAddress[] silos)
{
if (silos != null && silos.Length > 0)
return silos;
return this.siloStatusOracle
.GetApproximateSiloStatuses(true).Keys.ToArray();
}
/// <summary>
/// Perform an action for each silo.
/// </summary>
/// <remarks>
/// Because SiloControl contains a reference to a system target, each method call using that reference
/// will get routed either locally or remotely to the appropriate silo instance auto-magically.
/// </remarks>
/// <param name="siloAddresses">List of silos to perform the action for</param>
/// <param name="perSiloAction">The action function to be performed for each silo</param>
/// <returns>Array containing one Task for each silo the action was performed for</returns>
private List<Task> PerformPerSiloAction(SiloAddress[] siloAddresses, Func<SiloAddress, Task> perSiloAction)
{
var requestsToSilos = new List<Task>();
foreach (SiloAddress siloAddress in siloAddresses)
requestsToSilos.Add(perSiloAction(siloAddress));
return requestsToSilos;
}
private ISiloControl GetSiloControlReference(SiloAddress silo)
{
return this.internalGrainFactory.GetSystemTarget<ISiloControl>(Constants.SiloControlType, silo);
}
}
}
| |
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace Burrows.Pipeline.Inspectors
{
using System;
using System.Text;
using Context;
using Magnum.Extensions;
using Saga;
using Saga.Pipeline;
using Sinks;
using Util;
public class PipelineViewer :
PipelineInspectorBase<PipelineViewer>
{
private readonly StringBuilder _text = new StringBuilder();
int _depth;
public string Text
{
get { return _text.ToString(); }
}
public bool Inspect(InboundMessagePipeline pipeline)
{
Append("Pipeline");
return true;
}
public bool Inspect(OutboundMessagePipeline pipeline)
{
Append("Pipeline");
return true;
}
public bool Inspect<TMessage>(MessageRouter<TMessage> router)
where TMessage : class
{
Append(string.Format("Routed ({0})", GetMessageName<TMessage>()));
return true;
}
public bool Inspect<TMessage>(OutboundMessageFilter<TMessage> element) where TMessage : class
{
Append(string.Format("Filtered '{0}'", GetMessageName<TMessage>()));
return true;
}
public bool Inspect(InboundMessageInterceptor element)
{
Append(string.Format("Interceptor"));
return true;
}
public bool Inspect(OutboundMessageInterceptor element)
{
Append(string.Format("Interceptor"));
return true;
}
public bool Inspect<TMessage>(InstanceMessageSink<TMessage> sink)
where TMessage : class
{
Append(string.Format("Consumed by Instance ({0})", GetMessageName<TMessage>()));
return true;
}
public bool Inspect<TMessage>(EndpointMessageSink<TMessage> sink)
where TMessage : class
{
Append(string.Format("Send {0} to Endpoint {1}", GetMessageName<TMessage>(), sink.Endpoint.Address.Uri));
return true;
}
public bool Inspect<TMessage>(IPipelineSink<TMessage> sink)
where TMessage : class
{
Append(string.Format("Unknown Message Sink {0} ({1})", sink.GetType().ToFriendlyName(),
typeof (TMessage).ToFriendlyName()));
return true;
}
public bool Inspect<T, TMessage, TKey>(CorrelatedMessageRouter<T, TMessage, TKey> sink)
where TMessage : class, ICorrelatedBy<TKey>
where T : class, IMessageContext<TMessage>
{
Append(string.Format("Correlated by {1} ({0})", GetMessageName<TMessage>(), typeof(TKey).ToFriendlyName()));
return true;
}
public bool Inspect<T, TMessage, TKey>(CorrelatedMessageSinkRouter<T, TMessage, TKey> sink)
where T : class
where TMessage : class, ICorrelatedBy<TKey>
{
Append(string.Format("Routed for Correlation Id {1} ({0})", GetMessageName<TMessage>(), sink.CorrelationId));
return true;
}
public bool Inspect<T,TMessage>(RequestMessageRouter<T,TMessage> router)
where T : class, IConsumeContext<TMessage>
where TMessage : class
{
Append(string.Format("Routed Request {0}", GetMessageName<TMessage>()));
return true;
}
public bool Inspect<TMessage>(InboundConvertMessageSink<TMessage> converter)
where TMessage : class
{
Append(string.Format("Translated to {0}", GetMessageName<TMessage>()));
return true;
}
public bool Inspect<TMessage>(OutboundConvertMessageSink<TMessage> converter)
where TMessage : class
{
Append(string.Format("Translated to {0}", GetMessageName<TMessage>()));
return true;
}
public bool Inspect<TComponent, TMessage>(ConsumerMessageSink<TComponent, TMessage> sink)
where TMessage : class
where TComponent : class, Consumes<TMessage>.All
{
Append(string.Format("Consumed by Component {0} ({1})", GetComponentName<TComponent>(),
GetMessageName<TMessage>()));
return true;
}
public bool Inspect<TComponent, TMessage>(ContextConsumerMessageSink<TComponent, TMessage> sink)
where TMessage : class
where TComponent : class, Consumes<IConsumeContext<TMessage>>.All
{
Append(string.Format("Consumed by Component {0} ({1} w/Context)", GetComponentName<TComponent>(),
GetMessageName<TMessage>()));
return true;
}
public bool Inspect<TComponent, TMessage>(CorrelatedSagaMessageSink<TComponent, TMessage> sink)
where TMessage : class, ICorrelatedBy<Guid>
where TComponent : class, Consumes<TMessage>.All, ISaga
{
string policyDescription = GetPolicy(sink.Policy);
Append(string.Format("{0} Saga {1} ({2})", policyDescription, GetComponentName<TComponent>(),
GetMessageName<TMessage>()));
return true;
}
public bool Inspect<TComponent, TMessage>(PropertySagaMessageSink<TComponent, TMessage> sink)
where TMessage : class
where TComponent : class, Consumes<TMessage>.All, ISaga
{
string policyDescription = GetPolicy(sink.Policy);
string expression = sink.Selector.ToString();
Append(string.Format("{0} Saga {1} ({2}): {3}", policyDescription, GetComponentName<TComponent>(),
GetMessageName<TMessage>(), expression));
return true;
}
public bool Inspect<TComponent, TMessage>(PropertySagaStateMachineMessageSink<TComponent, TMessage> sink)
where TMessage : class
where TComponent : SagaStateMachine<TComponent>, ISaga
{
string policyDescription = GetPolicy(sink.Policy);
string expression = sink.Selector.ToString();
Append(string.Format("{0} Saga {1} ({2}): {3}", policyDescription, GetComponentName<TComponent>(),
GetMessageName<TMessage>(), expression));
return true;
}
public bool Inspect<TComponent, TMessage>(CorrelatedSagaStateMachineMessageSink<TComponent, TMessage> sink)
where TMessage : class, ICorrelatedBy<Guid>
where TComponent : SagaStateMachine<TComponent>, ISaga
{
string policyDescription = GetPolicy(sink.Policy);
Append(string.Format("{0} SagaStateMachine {1} ({2})", policyDescription, GetComponentName<TComponent>(),
GetMessageName<TMessage>()));
return true;
}
public bool Inspect<TComponent, TMessage>(SelectedConsumerMessageSink<TComponent, TMessage> sink)
where TMessage : class
where TComponent : class, Consumes<TMessage>.Selected
{
Append(string.Format("Conditionally Consumed by Component {0} ({1})", GetComponentName<TComponent>(),
GetMessageName<TMessage>()));
return true;
}
public bool Inspect<TComponent, TMessage>(SelectedContextConsumerMessageSink<TComponent, TMessage> sink)
where TMessage : class
where TComponent : class, Consumes<IConsumeContext<TMessage>>.Selected
{
Append(string.Format("Conditionally Consumed by Component {0} ({1} w/Context)", GetComponentName<TComponent>(),
GetMessageName<TMessage>()));
return true;
}
static string GetMessageName<TMessage>() where TMessage : class
{
Type messageType = typeof (TMessage);
if (messageType.IsGenericType && messageType.GetGenericTypeDefinition().Implements<IMessageContext>())
messageType = messageType.GetGenericArguments()[0];
return messageType.ToMessageName();
}
static string GetComponentName<TComponent>()
{
Type componentType = typeof (TComponent);
string componentName = componentType.IsGenericType
? componentType.GetGenericTypeDefinition().ToFriendlyName()
: componentType.ToFriendlyName();
return componentName;
}
protected override void IncreaseDepth()
{
_depth++;
}
protected override void DecreaseDepth()
{
_depth--;
}
void Pad()
{
_text.Append(new string('\t', _depth));
}
void Append(string text)
{
Pad();
_text.AppendFormat(text).AppendLine();
}
public static void Trace<T>(IPipelineSink<T> pipeline)
where T : class
{
var viewer = new PipelineViewer();
pipeline.Inspect(viewer);
System.Diagnostics.Trace.WriteLine(viewer.Text);
}
public static void Trace<T>(IPipelineSink<T> pipeline, Action<string> callback)
where T : class
{
var viewer = new PipelineViewer();
pipeline.Inspect(viewer);
callback(viewer.Text);
}
static string GetPolicy<TComponent, TMessage>(ISagaPolicy<TComponent, TMessage> policy)
where TComponent : class, ISaga
where TMessage : class
{
string description;
Type policyType = policy.GetType().GetGenericTypeDefinition();
if (policyType == typeof (InitiatingSagaPolicy<,>))
description = "Initiates New";
else if (policyType == typeof (ExistingOrIgnoreSagaPolicy<,>))
description = "Orchestrates Existing";
else if (policyType == typeof (CreateOrUseExistingSagaPolicy<,>))
description = "Initiates New Or Orchestrates Existing";
else
description = policyType.ToFriendlyName();
return description;
}
}
}
| |
// 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.Diagnostics;
using System.Text;
using System.Threading;
using System.Security;
namespace System.Text
{
// DBCSCodePageEncoding
//
internal class DBCSCodePageEncoding : BaseCodePageEncoding
{
// Pointers to our memory section parts
protected unsafe char* mapBytesToUnicode = null; // char 65536
protected unsafe ushort* mapUnicodeToBytes = null; // byte 65536
protected const char UNKNOWN_CHAR_FLAG = (char)0x0;
protected const char UNICODE_REPLACEMENT_CHAR = (char)0xFFFD;
protected const char LEAD_BYTE_CHAR = (char)0xFFFE; // For lead bytes
// Note that even though we provide bytesUnknown and byteCountUnknown,
// They aren't actually used because of the fallback mechanism. (char is though)
private ushort _bytesUnknown;
private int _byteCountUnknown;
protected char charUnknown = (char)0;
public DBCSCodePageEncoding(int codePage) : this(codePage, codePage)
{
}
internal DBCSCodePageEncoding(int codePage, int dataCodePage) : base(codePage, dataCodePage)
{
}
internal DBCSCodePageEncoding(int codePage, int dataCodePage, EncoderFallback enc, DecoderFallback dec) : base(codePage, dataCodePage, enc, dec)
{
}
// MBCS data section:
//
// We treat each multibyte pattern as 2 bytes in our table. If it's a single byte, then the high byte
// for that position will be 0. When the table is loaded, leading bytes are flagged with 0xFFFE, so
// when reading the table look up with each byte. If the result is 0xFFFE, then use 2 bytes to read
// further data. FFFF is a special value indicating that the Unicode code is the same as the
// character code (this helps us support code points < 0x20). FFFD is used as replacement character.
//
// Normal table:
// WCHAR* - Starting with MB code point 0.
// FFFF indicates we are to use the multibyte value for our code point.
// FFFE is the lead byte mark. (This should only appear in positions < 0x100)
// FFFD is the replacement (unknown character) mark.
// 2-20 means to advance the pointer 2-0x20 characters.
// 1 means to advance to the multibyte position contained in the next char.
// 0 has no specific meaning (May not be possible.)
//
// Table ends when multibyte position has advanced to 0xFFFF.
//
// Bytes->Unicode Best Fit table:
// WCHAR* - Same as normal table, except first wchar is byte position to start at.
//
// Unicode->Bytes Best Fit Table:
// WCHAR* - Same as normal table, except first wchar is char position to start at and
// we loop through unicode code points and the table has the byte points that
// correspond to those unicode code points.
// We have a managed code page entry, so load our tables
//
protected override unsafe void LoadManagedCodePage()
{
Debug.Assert(m_codePageHeader?.Length > 0);
fixed (byte* pBytes = &m_codePageHeader[0])
{
CodePageHeader* pCodePage = (CodePageHeader*)pBytes;
// Should be loading OUR code page
Debug.Assert(pCodePage->CodePage == dataTableCodePage,
"[DBCSCodePageEncoding.LoadManagedCodePage]Expected to load data table code page");
// Make sure we're really a 1-byte code page
if (pCodePage->ByteCount != 2)
throw new NotSupportedException(SR.Format(SR.NotSupported_NoCodepageData, CodePage));
// Remember our unknown bytes & chars
_bytesUnknown = pCodePage->ByteReplace;
charUnknown = pCodePage->UnicodeReplace;
// Need to make sure the fallback buffer's fallback char is correct
if (DecoderFallback is InternalDecoderBestFitFallback)
{
((InternalDecoderBestFitFallback)(DecoderFallback)).cReplacement = charUnknown;
}
// Is our replacement bytesUnknown a single or double byte character?
_byteCountUnknown = 1;
if (_bytesUnknown > 0xff)
_byteCountUnknown++;
// We use fallback encoder, which uses ?, which so far all of our tables do as well
Debug.Assert(_bytesUnknown == 0x3f,
"[DBCSCodePageEncoding.LoadManagedCodePage]Expected 0x3f (?) as unknown byte character");
// Get our mapped section (bytes to allocate = 2 bytes per 65536 Unicode chars + 2 bytes per 65536 DBCS chars)
// Plus 4 byte to remember CP # when done loading it. (Don't want to get IA64 or anything out of alignment)
byte* pNativeMemory = GetNativeMemory(65536 * 2 * 2 + 4 + iExtraBytes);
mapBytesToUnicode = (char*)pNativeMemory;
mapUnicodeToBytes = (ushort*)(pNativeMemory + 65536 * 2);
// Need to read our data file and fill in our section.
// WARNING: Multiple code pieces could do this at once (so we don't have to lock machine-wide)
// so be careful here. Only stick legal values in here, don't stick temporary values.
// Move to the beginning of the data section
byte[] buffer = new byte[m_dataSize];
lock (s_streamLock)
{
s_codePagesEncodingDataStream.Seek(m_firstDataWordOffset, SeekOrigin.Begin);
s_codePagesEncodingDataStream.Read(buffer, 0, m_dataSize);
}
fixed (byte* pBuffer = buffer)
{
char* pData = (char*)pBuffer;
// We start at bytes position 0
int bytePosition = 0;
int useBytes = 0;
while (bytePosition < 0x10000)
{
// Get the next byte
char input = *pData;
pData++;
// build our table:
if (input == 1)
{
// Use next data as our byte position
bytePosition = (int)(*pData);
pData++;
continue;
}
else if (input < 0x20 && input > 0)
{
// Advance input characters
bytePosition += input;
continue;
}
else if (input == 0xFFFF)
{
// Same as our bytePosition
useBytes = bytePosition;
input = unchecked((char)bytePosition);
}
else if (input == LEAD_BYTE_CHAR) // 0xfffe
{
// Lead byte mark
Debug.Assert(bytePosition < 0x100, "[DBCSCodePageEncoding.LoadManagedCodePage]expected lead byte to be < 0x100");
useBytes = bytePosition;
// input stays 0xFFFE
}
else if (input == UNICODE_REPLACEMENT_CHAR)
{
// Replacement char is already done
bytePosition++;
continue;
}
else
{
// Use this character
useBytes = bytePosition;
// input == input;
}
// We may need to clean up the selected character & position
if (CleanUpBytes(ref useBytes))
{
// Use this selected character at the selected position, don't do this if not supposed to.
if (input != LEAD_BYTE_CHAR)
{
// Don't do this for lead byte marks.
mapUnicodeToBytes[input] = unchecked((ushort)useBytes);
}
mapBytesToUnicode[useBytes] = input;
}
bytePosition++;
}
}
// See if we have any clean up to do
CleanUpEndBytes(mapBytesToUnicode);
}
}
// Any special processing for this code page
protected virtual bool CleanUpBytes(ref int bytes)
{
return true;
}
// Any special processing for this code page
protected virtual unsafe void CleanUpEndBytes(char* chars)
{
}
// Private object for locking instead of locking on a public type for SQL reliability work.
private static Object s_InternalSyncObject;
private static Object InternalSyncObject
{
get
{
if (s_InternalSyncObject == null)
{
Object o = new Object();
Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null);
}
return s_InternalSyncObject;
}
}
// Read in our best fit table
protected unsafe override void ReadBestFitTable()
{
// Lock so we don't confuse ourselves.
lock (InternalSyncObject)
{
// If we got a best fit array already then don't do this
if (arrayUnicodeBestFit == null)
{
//
// Read in Best Fit table.
//
// First we have to advance past original character mapping table
// Move to the beginning of the data section
byte[] buffer = new byte[m_dataSize];
lock (s_streamLock)
{
s_codePagesEncodingDataStream.Seek(m_firstDataWordOffset, SeekOrigin.Begin);
s_codePagesEncodingDataStream.Read(buffer, 0, m_dataSize);
}
fixed (byte* pBuffer = buffer)
{
char* pData = (char*)pBuffer;
// We start at bytes position 0
int bytesPosition = 0;
while (bytesPosition < 0x10000)
{
// Get the next byte
char input = *pData;
pData++;
// build our table:
if (input == 1)
{
// Use next data as our byte position
bytesPosition = (int)(*pData);
pData++;
}
else if (input < 0x20 && input > 0)
{
// Advance input characters
bytesPosition += input;
}
else
{
// All other cases add 1 to bytes position
bytesPosition++;
}
}
// Now bytesPosition is at start of bytes->unicode best fit table
char* pBytes2Unicode = pData;
// Now pData should be pointing to first word of bytes -> unicode best fit table
// (which we're also not using at the moment)
int iBestFitCount = 0;
bytesPosition = *pData;
pData++;
while (bytesPosition < 0x10000)
{
// Get the next byte
char input = *pData;
pData++;
// build our table:
if (input == 1)
{
// Use next data as our byte position
bytesPosition = (int)(*pData);
pData++;
}
else if (input < 0x20 && input > 0)
{
// Advance input characters
bytesPosition += input;
}
else
{
// Use this character (unless it's unknown, unk just skips 1)
if (input != UNICODE_REPLACEMENT_CHAR)
{
int correctedChar = bytesPosition;
if (CleanUpBytes(ref correctedChar))
{
// Sometimes correction makes them the same as no best fit, skip those.
if (mapBytesToUnicode[correctedChar] != input)
{
iBestFitCount++;
}
}
}
// Position gets incremented in any case.
bytesPosition++;
}
}
// Now we know how big the best fit table has to be
char[] arrayTemp = new char[iBestFitCount * 2];
// Now we know how many best fits we have, so go back & read them in
iBestFitCount = 0;
pData = pBytes2Unicode;
bytesPosition = *pData;
pData++;
bool bOutOfOrder = false;
// Read it all in again
while (bytesPosition < 0x10000)
{
// Get the next byte
char input = *pData;
pData++;
// build our table:
if (input == 1)
{
// Use next data as our byte position
bytesPosition = (int)(*pData);
pData++;
}
else if (input < 0x20 && input > 0)
{
// Advance input characters
bytesPosition += input;
}
else
{
// Use this character (unless its unknown, unk just skips 1)
if (input != UNICODE_REPLACEMENT_CHAR)
{
int correctedChar = bytesPosition;
if (CleanUpBytes(ref correctedChar))
{
// Sometimes correction makes them same as no best fit, skip those.
if (mapBytesToUnicode[correctedChar] != input)
{
if (correctedChar != bytesPosition)
bOutOfOrder = true;
arrayTemp[iBestFitCount++] = unchecked((char)correctedChar);
arrayTemp[iBestFitCount++] = input;
}
}
}
// Position gets incremented in any case.
bytesPosition++;
}
}
// If they're out of order we need to sort them.
if (bOutOfOrder)
{
Debug.Assert((arrayTemp.Length / 2) < 20,
"[DBCSCodePageEncoding.ReadBestFitTable]Expected small best fit table < 20 for code page " + CodePage + ", not " + arrayTemp.Length / 2);
for (int i = 0; i < arrayTemp.Length - 2; i += 2)
{
int iSmallest = i;
char cSmallest = arrayTemp[i];
for (int j = i + 2; j < arrayTemp.Length; j += 2)
{
// Find smallest one for front
if (cSmallest > arrayTemp[j])
{
cSmallest = arrayTemp[j];
iSmallest = j;
}
}
// If smallest one is something else, switch them
if (iSmallest != i)
{
char temp = arrayTemp[iSmallest];
arrayTemp[iSmallest] = arrayTemp[i];
arrayTemp[i] = temp;
temp = arrayTemp[iSmallest + 1];
arrayTemp[iSmallest + 1] = arrayTemp[i + 1];
arrayTemp[i + 1] = temp;
}
}
}
// Remember our array
arrayBytesBestFit = arrayTemp;
// Now were at beginning of Unicode -> Bytes best fit table, need to count them
char* pUnicode2Bytes = pData;
int unicodePosition = *(pData++);
iBestFitCount = 0;
while (unicodePosition < 0x10000)
{
// Get the next byte
char input = *pData;
pData++;
// build our table:
if (input == 1)
{
// Use next data as our byte position
unicodePosition = (int)*pData;
pData++;
}
else if (input < 0x20 && input > 0)
{
// Advance input characters
unicodePosition += input;
}
else
{
// Same as our unicodePosition or use this character
if (input > 0)
iBestFitCount++;
unicodePosition++;
}
}
// Allocate our table
arrayTemp = new char[iBestFitCount * 2];
// Now do it again to fill the array with real values
pData = pUnicode2Bytes;
unicodePosition = *(pData++);
iBestFitCount = 0;
while (unicodePosition < 0x10000)
{
// Get the next byte
char input = *pData;
pData++;
// build our table:
if (input == 1)
{
// Use next data as our byte position
unicodePosition = (int)*pData;
pData++;
}
else if (input < 0x20 && input > 0)
{
// Advance input characters
unicodePosition += input;
}
else
{
if (input > 0)
{
// Use this character, may need to clean it up
int correctedChar = (int)input;
if (CleanUpBytes(ref correctedChar))
{
arrayTemp[iBestFitCount++] = unchecked((char)unicodePosition);
// Have to map it to Unicode because best fit will need Unicode value of best fit char.
arrayTemp[iBestFitCount++] = mapBytesToUnicode[correctedChar];
}
}
unicodePosition++;
}
}
// Remember our array
arrayUnicodeBestFit = arrayTemp;
}
}
}
}
// GetByteCount
// Note: We start by assuming that the output will be the same as count. Having
// an encoder or fallback may change that assumption
public override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
Debug.Assert(count >= 0, "[DBCSCodePageEncoding.GetByteCount]count is negative");
Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetByteCount]chars is null");
// Assert because we shouldn't be able to have a null encoder.
Debug.Assert(EncoderFallback != null, "[DBCSCodePageEncoding.GetByteCount]Attempting to use null fallback");
CheckMemorySection();
// Get any left over characters
char charLeftOver = (char)0;
if (encoder != null)
{
charLeftOver = encoder.charLeftOver;
// Only count if encoder.m_throwOnOverflow
if (encoder.InternalHasFallbackBuffer && encoder.FallbackBuffer.Remaining > 0)
throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, EncodingName, encoder.Fallback.GetType()));
}
// prepare our end
int byteCount = 0;
char* charEnd = chars + count;
// For fallback we will need a fallback buffer
EncoderFallbackBuffer fallbackBuffer = null;
EncoderFallbackBufferHelper fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer);
// We may have a left over character from last time, try and process it.
if (charLeftOver > 0)
{
Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[DBCSCodePageEncoding.GetByteCount]leftover character should be high surrogate");
Debug.Assert(encoder != null,
"[DBCSCodePageEncoding.GetByteCount]Expect to have encoder if we have a charLeftOver");
// Since left over char was a surrogate, it'll have to be fallen back.
// Get Fallback
fallbackBuffer = encoder.FallbackBuffer;
fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(chars, charEnd, encoder, false);
// This will fallback a pair if *chars is a low surrogate
fallbackHelper.InternalFallback(charLeftOver, ref chars);
}
// Now we may have fallback char[] already (from the encoder)
// We have to use fallback method.
char ch;
while ((ch = (fallbackBuffer == null) ? '\0' : fallbackHelper.InternalGetNextChar()) != 0 ||
chars < charEnd)
{
// First unwind any fallback
if (ch == 0)
{
// No fallback, just get next char
ch = *chars;
chars++;
}
// get byte for this char
ushort sTemp = mapUnicodeToBytes[ch];
// Check for fallback, this'll catch surrogate pairs too.
if (sTemp == 0 && ch != (char)0)
{
if (fallbackBuffer == null)
{
// Initialize the buffer
if (encoder == null)
fallbackBuffer = EncoderFallback.CreateFallbackBuffer();
else
fallbackBuffer = encoder.FallbackBuffer;
fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(charEnd - count, charEnd, encoder, false);
}
// Get Fallback
fallbackHelper.InternalFallback(ch, ref chars);
continue;
}
// We'll use this one
byteCount++;
if (sTemp >= 0x100)
byteCount++;
}
return (int)byteCount;
}
public override unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, EncoderNLS encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetBytes]bytes is null");
Debug.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetBytes]byteCount is negative");
Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetBytes]chars is null");
Debug.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetBytes]charCount is negative");
// Assert because we shouldn't be able to have a null encoder.
Debug.Assert(EncoderFallback != null, "[DBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback");
CheckMemorySection();
// For fallback we will need a fallback buffer
EncoderFallbackBuffer fallbackBuffer = null;
// prepare our end
char* charEnd = chars + charCount;
char* charStart = chars;
byte* byteStart = bytes;
byte* byteEnd = bytes + byteCount;
EncoderFallbackBufferHelper fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer);
// Get any left over characters
char charLeftOver = (char)0;
if (encoder != null)
{
charLeftOver = encoder.charLeftOver;
Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
"[DBCSCodePageEncoding.GetBytes]leftover character should be high surrogate");
// Go ahead and get the fallback buffer (need leftover fallback if converting)
fallbackBuffer = encoder.FallbackBuffer;
fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(chars, charEnd, encoder, true);
// If we're not converting we must not have a fallback buffer
if (encoder.m_throwOnOverflow && fallbackBuffer.Remaining > 0)
throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, EncodingName, encoder.Fallback.GetType()));
// We may have a left over character from last time, try and process it.
if (charLeftOver > 0)
{
Debug.Assert(encoder != null,
"[DBCSCodePageEncoding.GetBytes]Expect to have encoder if we have a charLeftOver");
// Since left over char was a surrogate, it'll have to be fallen back.
// Get Fallback
fallbackHelper.InternalFallback(charLeftOver, ref chars);
}
}
// Now we may have fallback char[] already from the encoder
// Go ahead and do it, including the fallback.
char ch;
while ((ch = (fallbackBuffer == null) ? '\0' : fallbackHelper.InternalGetNextChar()) != 0 ||
chars < charEnd)
{
// First unwind any fallback
if (ch == 0)
{
// No fallback, just get next char
ch = *chars;
chars++;
}
// get byte for this char
ushort sTemp = mapUnicodeToBytes[ch];
// Check for fallback, this'll catch surrogate pairs too.
if (sTemp == 0 && ch != (char)0)
{
if (fallbackBuffer == null)
{
// Initialize the buffer
Debug.Assert(encoder == null,
"[DBCSCodePageEncoding.GetBytes]Expected delayed create fallback only if no encoder.");
fallbackBuffer = EncoderFallback.CreateFallbackBuffer();
fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(charEnd - charCount, charEnd, encoder, true);
}
// Get Fallback
fallbackHelper.InternalFallback(ch, ref chars);
continue;
}
// We'll use this one (or two)
// Bounds check
// Go ahead and add it, lead byte 1st if necessary
if (sTemp >= 0x100)
{
if (bytes + 1 >= byteEnd)
{
// didn't use this char, we'll throw or use buffer
if (fallbackBuffer == null || fallbackHelper.bFallingBack == false)
{
Debug.Assert(chars > charStart,
"[DBCSCodePageEncoding.GetBytes]Expected chars to have advanced (double byte case)");
chars--; // don't use last char
}
else
fallbackBuffer.MovePrevious(); // don't use last fallback
ThrowBytesOverflow(encoder, chars == charStart); // throw ?
break; // don't throw, stop
}
*bytes = unchecked((byte)(sTemp >> 8));
bytes++;
}
// Single byte
else if (bytes >= byteEnd)
{
// didn't use this char, we'll throw or use buffer
if (fallbackBuffer == null || fallbackHelper.bFallingBack == false)
{
Debug.Assert(chars > charStart,
"[DBCSCodePageEncoding.GetBytes]Expected chars to have advanced (single byte case)");
chars--; // don't use last char
}
else
fallbackBuffer.MovePrevious(); // don't use last fallback
ThrowBytesOverflow(encoder, chars == charStart); // throw ?
break; // don't throw, stop
}
*bytes = unchecked((byte)(sTemp & 0xff));
bytes++;
}
// encoder stuff if we have one
if (encoder != null)
{
// Fallback stuck it in encoder if necessary, but we have to clear MustFlush cases
if (fallbackBuffer != null && !fallbackHelper.bUsedEncoder)
// Clear it in case of MustFlush
encoder.charLeftOver = (char)0;
// Set our chars used count
encoder.m_charsUsed = (int)(chars - charStart);
}
return (int)(bytes - byteStart);
}
// This is internal and called by something else,
public override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
{
// Just assert, we're called internally so these should be safe, checked already
Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetCharCount]bytes is null");
Debug.Assert(count >= 0, "[DBCSCodePageEncoding.GetCharCount]byteCount is negative");
CheckMemorySection();
// Fix our decoder
DBCSDecoder decoder = (DBCSDecoder)baseDecoder;
// Get our fallback
DecoderFallbackBuffer fallbackBuffer = null;
// We'll need to know where the end is
byte* byteEnd = bytes + count;
int charCount = count; // Assume 1 char / byte
// Shouldn't have anything in fallback buffer for GetCharCount
// (don't have to check m_throwOnOverflow for count)
Debug.Assert(decoder == null ||
!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
"[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer at start");
DecoderFallbackBufferHelper fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer);
// If we have a left over byte, use it
if (decoder != null && decoder.bLeftOver > 0)
{
// We have a left over byte?
if (count == 0)
{
// No input though
if (!decoder.MustFlush)
{
// Don't have to flush
return 0;
}
Debug.Assert(fallbackBuffer == null,
"[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer");
fallbackBuffer = decoder.FallbackBuffer;
fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(bytes, null);
byte[] byteBuffer = new byte[] { unchecked((byte)decoder.bLeftOver) };
return fallbackHelper.InternalFallback(byteBuffer, bytes);
}
// Get our full info
int iBytes = decoder.bLeftOver << 8;
iBytes |= (*bytes);
bytes++;
// This is either 1 known char or fallback
// Already counted 1 char
// Look up our bytes
char cDecoder = mapBytesToUnicode[iBytes];
if (cDecoder == 0 && iBytes != 0)
{
// Deallocate preallocated one
charCount--;
// We'll need a fallback
Debug.Assert(fallbackBuffer == null,
"[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer for unknown pair");
fallbackBuffer = decoder.FallbackBuffer;
fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(byteEnd - count, null);
// Do fallback, we know there are 2 bytes
byte[] byteBuffer = new byte[] { unchecked((byte)(iBytes >> 8)), unchecked((byte)iBytes) };
charCount += fallbackHelper.InternalFallback(byteBuffer, bytes);
}
// else we already reserved space for this one.
}
// Loop, watch out for fallbacks
while (bytes < byteEnd)
{
// Faster if don't use *bytes++;
int iBytes = *bytes;
bytes++;
char c = mapBytesToUnicode[iBytes];
// See if it was a double byte character
if (c == LEAD_BYTE_CHAR)
{
// It's a lead byte
charCount--; // deallocate preallocated lead byte
if (bytes < byteEnd)
{
// Have another to use, so use it
iBytes <<= 8;
iBytes |= *bytes;
bytes++;
c = mapBytesToUnicode[iBytes];
}
else
{
// No input left
if (decoder == null || decoder.MustFlush)
{
// have to flush anyway, set to unknown so we use fallback
charCount++; // reallocate deallocated lead byte
c = UNKNOWN_CHAR_FLAG;
}
else
{
// We'll stick it in decoder
break;
}
}
}
// See if it was unknown.
// Unknown and known chars already allocated, but fallbacks aren't
if (c == UNKNOWN_CHAR_FLAG && iBytes != 0)
{
if (fallbackBuffer == null)
{
if (decoder == null)
fallbackBuffer = DecoderFallback.CreateFallbackBuffer();
else
fallbackBuffer = decoder.FallbackBuffer;
fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(byteEnd - count, null);
}
// Do fallback
charCount--; // Get rid of preallocated extra char
byte[] byteBuffer = null;
if (iBytes < 0x100)
byteBuffer = new byte[] { unchecked((byte)iBytes) };
else
byteBuffer = new byte[] { unchecked((byte)(iBytes >> 8)), unchecked((byte)iBytes) };
charCount += fallbackHelper.InternalFallback(byteBuffer, bytes);
}
}
// Shouldn't have anything in fallback buffer for GetChars
Debug.Assert(decoder == null || !decoder.m_throwOnOverflow ||
!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
"[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer at end");
// Return our count
return charCount;
}
public override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS baseDecoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetChars]bytes is null");
Debug.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetChars]byteCount is negative");
Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetChars]chars is null");
Debug.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetChars]charCount is negative");
CheckMemorySection();
// Fix our decoder
DBCSDecoder decoder = (DBCSDecoder)baseDecoder;
// We'll need to know where the end is
byte* byteStart = bytes;
byte* byteEnd = bytes + byteCount;
char* charStart = chars;
char* charEnd = chars + charCount;
bool bUsedDecoder = false;
// Get our fallback
DecoderFallbackBuffer fallbackBuffer = null;
// Shouldn't have anything in fallback buffer for GetChars
Debug.Assert(decoder == null || !decoder.m_throwOnOverflow ||
!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
"[DBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start");
DecoderFallbackBufferHelper fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer);
// If we have a left over byte, use it
if (decoder != null && decoder.bLeftOver > 0)
{
// We have a left over byte?
if (byteCount == 0)
{
// No input though
if (!decoder.MustFlush)
{
// Don't have to flush
return 0;
}
// Well, we're flushing, so use '?' or fallback
// fallback leftover byte
Debug.Assert(fallbackBuffer == null,
"[DBCSCodePageEncoding.GetChars]Expected empty fallback");
fallbackBuffer = decoder.FallbackBuffer;
fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(bytes, charEnd);
// If no room, it's hopeless, this was 1st fallback
byte[] byteBuffer = new byte[] { unchecked((byte)decoder.bLeftOver) };
if (!fallbackHelper.InternalFallback(byteBuffer, bytes, ref chars))
ThrowCharsOverflow(decoder, true);
decoder.bLeftOver = 0;
// Done, return it
return (int)(chars - charStart);
}
// Get our full info
int iBytes = decoder.bLeftOver << 8;
iBytes |= (*bytes);
bytes++;
// Look up our bytes
char cDecoder = mapBytesToUnicode[iBytes];
if (cDecoder == UNKNOWN_CHAR_FLAG && iBytes != 0)
{
Debug.Assert(fallbackBuffer == null,
"[DBCSCodePageEncoding.GetChars]Expected empty fallback for two bytes");
fallbackBuffer = decoder.FallbackBuffer;
fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(byteEnd - byteCount, charEnd);
byte[] byteBuffer = new byte[] { unchecked((byte)(iBytes >> 8)), unchecked((byte)iBytes) };
if (!fallbackHelper.InternalFallback(byteBuffer, bytes, ref chars))
ThrowCharsOverflow(decoder, true);
}
else
{
// Do we have output room?, hopeless if not, this is first char
if (chars >= charEnd)
ThrowCharsOverflow(decoder, true);
*(chars++) = cDecoder;
}
}
// Loop, paying attention to our fallbacks.
while (bytes < byteEnd)
{
// Faster if don't use *bytes++;
int iBytes = *bytes;
bytes++;
char c = mapBytesToUnicode[iBytes];
// See if it was a double byte character
if (c == LEAD_BYTE_CHAR)
{
// Its a lead byte
if (bytes < byteEnd)
{
// Have another to use, so use it
iBytes <<= 8;
iBytes |= *bytes;
bytes++;
c = mapBytesToUnicode[iBytes];
}
else
{
// No input left
if (decoder == null || decoder.MustFlush)
{
// have to flush anyway, set to unknown so we use fallback
c = UNKNOWN_CHAR_FLAG;
}
else
{
// Stick it in decoder
bUsedDecoder = true;
decoder.bLeftOver = (byte)iBytes;
break;
}
}
}
// See if it was unknown
if (c == UNKNOWN_CHAR_FLAG && iBytes != 0)
{
if (fallbackBuffer == null)
{
if (decoder == null)
fallbackBuffer = DecoderFallback.CreateFallbackBuffer();
else
fallbackBuffer = decoder.FallbackBuffer;
fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(byteEnd - byteCount, charEnd);
}
// Do fallback
byte[] byteBuffer = null;
if (iBytes < 0x100)
byteBuffer = new byte[] { unchecked((byte)iBytes) };
else
byteBuffer = new byte[] { unchecked((byte)(iBytes >> 8)), unchecked((byte)iBytes) };
if (!fallbackHelper.InternalFallback(byteBuffer, bytes, ref chars))
{
// May or may not throw, but we didn't get these byte(s)
Debug.Assert(bytes >= byteStart + byteBuffer.Length,
"[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for fallback");
bytes -= byteBuffer.Length; // didn't use these byte(s)
fallbackHelper.InternalReset(); // Didn't fall this back
ThrowCharsOverflow(decoder, bytes == byteStart); // throw?
break; // don't throw, but stop loop
}
}
else
{
// Do we have buffer room?
if (chars >= charEnd)
{
// May or may not throw, but we didn't get these byte(s)
Debug.Assert(bytes > byteStart,
"[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for lead byte");
bytes--; // unused byte
if (iBytes >= 0x100)
{
Debug.Assert(bytes > byteStart,
"[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for trail byte");
bytes--; // 2nd unused byte
}
ThrowCharsOverflow(decoder, bytes == byteStart); // throw?
break; // don't throw, but stop loop
}
*(chars++) = c;
}
}
// We already stuck it in encoder if necessary, but we have to clear cases where nothing new got into decoder
if (decoder != null)
{
// Clear it in case of MustFlush
if (bUsedDecoder == false)
{
decoder.bLeftOver = 0;
}
// Remember our count
decoder.m_bytesUsed = (int)(bytes - byteStart);
}
// Shouldn't have anything in fallback buffer for GetChars
Debug.Assert(decoder == null || !decoder.m_throwOnOverflow ||
!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
"[DBCSCodePageEncoding.GetChars]Expected empty fallback buffer at end");
// Return length of our output
return (int)(chars - charStart);
}
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum);
// Characters would be # of characters + 1 in case high surrogate is ? * max fallback
long byteCount = (long)charCount + 1;
if (EncoderFallback.MaxCharCount > 1)
byteCount *= EncoderFallback.MaxCharCount;
// 2 to 1 is worst case. Already considered surrogate fallback
byteCount *= 2;
if (byteCount > 0x7fffffff)
throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GetByteCountOverflow);
return (int)byteCount;
}
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum);
// DBCS is pretty much the same, but could have hanging high byte making extra ? and fallback for unknown
long charCount = ((long)byteCount + 1);
// 1 to 1 for most characters. Only surrogates with fallbacks have less, unknown fallbacks could be longer.
if (DecoderFallback.MaxCharCount > 1)
charCount *= DecoderFallback.MaxCharCount;
if (charCount > 0x7fffffff)
throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_GetCharCountOverflow);
return (int)charCount;
}
public override Decoder GetDecoder()
{
return new DBCSDecoder(this);
}
internal class DBCSDecoder : DecoderNLS
{
// Need a place for the last left over byte
internal byte bLeftOver = 0;
public DBCSDecoder(DBCSCodePageEncoding encoding) : base(encoding)
{
// Base calls reset
}
public override void Reset()
{
bLeftOver = 0;
if (m_fallbackBuffer != null)
m_fallbackBuffer.Reset();
}
// Anything left in our decoder?
internal override bool HasState
{
get
{
return (bLeftOver != 0);
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace GarageKept.WebConsole.Server.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using NBitcoin;
using NBitcoin.Payment;
using System.Linq;
using System.Net;
using WalletWasabi.Userfacing;
using Xunit;
namespace WalletWasabi.Tests.UnitTests
{
public class ParserTests
{
[Theory]
[InlineData("localhost")]
[InlineData("127.0.0.1")]
[InlineData("192.168.56.1")]
[InlineData("foo.com")]
[InlineData("foo.onion")]
public void EndPointParserTests(string host)
{
var inputsWithoutPorts = new[]
{
host,
$"{host} ",
$"bitcoin-p2p://{host}",
$"Bitcoin-P2P://{host}",
$"tcp://{host}",
$"TCP://{host}",
$" {host}",
$" {host} ",
$"{host}:",
$"{host}: ",
$"{host} :",
$"{host} : ",
$" {host} : ",
$"{host}/",
$"{host}/ ",
$" {host}/ ",
};
var inputsWithPorts = new[]
{
$"{host}:5000",
$"bitcoin-p2p://{host}:5000",
$"BITCOIN-P2P://{host}:5000",
$"tcp://{host}:5000",
$"TCP://{host}:5000",
$" {host}:5000",
$"{host} :5000",
$" {host}:5000",
$"{host}: 5000",
$" {host} : 5000 ",
$"{host}/:5000",
$"{host}/:5000/",
$"{host}/:5000/ ",
$"{host}/: 5000/",
$"{host}/ :5000/ ",
$"{host}/ : 5000/",
$"{host}/ : 5000/ ",
$" {host}/ : 5000/ "
};
var invalidPortStrings = new[]
{
"-1",
"-5000",
"999999999999999999999",
"foo",
"-999999999999999999999",
int.MaxValue.ToString(),
uint.MaxValue.ToString(),
long.MaxValue.ToString(),
"0.1",
int.MinValue.ToString(),
long.MinValue.ToString(),
(ushort.MinValue - 1).ToString(),
(ushort.MaxValue + 1).ToString()
};
var validPorts = new[]
{
0,
5000,
9999,
ushort.MinValue,
ushort.MaxValue
};
var inputsWithInvalidPorts = invalidPortStrings.Select(x => $"{host}:{x}").ToArray();
// Default port is used.
foreach (var inputString in inputsWithoutPorts)
{
foreach (var defaultPort in validPorts)
{
var success = EndPointParser.TryParse(inputString, defaultPort, out EndPoint? ep);
AssertEndPointParserOutputs(success, ep, host, defaultPort);
}
}
// Default port is not used.
foreach (var inputString in inputsWithPorts)
{
var success = EndPointParser.TryParse(inputString, 12345, out EndPoint? ep);
AssertEndPointParserOutputs(success, ep, host, 5000);
}
// Default port is invalid, string port is not provided.
foreach (var inputString in inputsWithoutPorts)
{
Assert.False(EndPointParser.TryParse(inputString, -1, out EndPoint? ep));
}
// Defaultport doesn't correct invalid port input.
foreach (var inputString in inputsWithInvalidPorts)
{
foreach (var defaultPort in validPorts)
{
Assert.False(EndPointParser.TryParse(inputString, defaultPort, out EndPoint? ep));
}
}
// Both default and string ports are invalid.
foreach (var inputString in inputsWithInvalidPorts)
{
Assert.False(EndPointParser.TryParse(inputString, -1, out EndPoint? ep));
}
}
private static void AssertEndPointParserOutputs(bool isSuccess, EndPoint endPoint, string expectedHost, int expectedPort)
{
Assert.True(isSuccess);
Assert.True(endPoint.TryGetHostAndPort(out string? actualHost, out int? actualPort));
expectedHost = (expectedHost == "localhost") ? "127.0.0.1" : expectedHost;
Assert.Equal(expectedHost, actualHost);
Assert.Equal(expectedPort, actualPort);
Assert.Equal($"{actualHost}:{actualPort}", endPoint.ToString(expectedPort));
}
[Fact]
public void BitcoinAddressParserTests()
{
(string address, Network network)[] tests = new[]
{
("18cBEMRxXHqzWWCxZNtU91F5sbUNKhL5PX", Network.Main),
("17VZNX1SN5NtKa8UQFxwQbFeFc3iqRYhem", Network.Main),
("3EktnHQD7RiAE6uzMj2ZifT9YgRrkSgzQX", Network.Main),
("bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4", Network.Main),
("mipcBbFg9gMiCh81Kj8tqqdgoZub1ZJRfn", Network.TestNet),
("2MzQwSSnBHWHqSAqtTVQ6v47XtaisrJa1Vc", Network.TestNet),
("tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx", Network.TestNet),
};
foreach (var test in tests)
{
Assert.False(AddressStringParser.TryParseBitcoinAddress(test.address.Remove(0, 1), test.network, out _));
Assert.False(AddressStringParser.TryParseBitcoinAddress(test.address.Remove(5, 1), test.network, out _));
Assert.False(AddressStringParser.TryParseBitcoinAddress(test.address.Insert(4, "b"), test.network, out _));
Assert.False(AddressStringParser.TryParseBitcoinAddress(test.address, null, out _));
Assert.False(AddressStringParser.TryParseBitcoinAddress(null, test.network, out _));
Assert.True(AddressStringParser.TryParseBitcoinAddress(test.address, test.network, out BitcoinUrlBuilder? result));
Assert.Equal(test.address, result.Address.ToString());
Assert.True(AddressStringParser.TryParseBitcoinAddress(test.address.Insert(0, " "), test.network, out result));
Assert.Equal(test.address.Trim(), result.Address.ToString());
}
}
[Fact]
public void BitcoinUrlParserTests()
{
(string url, Network network)[] tests = new[]
{
("bitcoin:18cBEMRxXHqzWWCxZNtU91F5sbUNKhL5PX?amount=50&label=Luke-Jr&message=Donation%20for%20project%20xyz", Network.Main),
("bitcoin:17VZNX1SN5NtKa8UQFxwQbFeFc3iqRYhem?amount=50&label=Luke-Jr&message=Donation%20for%20project%20xyz", Network.Main),
("bitcoin:3EktnHQD7RiAE6uzMj2ZifT9YgRrkSgzQX?amount=50&label=Luke-Jr&message=Donation%20for%20project%20xyz", Network.Main),
("bitcoin:bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4?amount=50&label=Luke-Jr&message=Donation%20for%20project%20xyz", Network.Main),
("bitcoin:mipcBbFg9gMiCh81Kj8tqqdgoZub1ZJRfn?amount=50&label=Luke-Jr&message=Donation%20for%20project%20xyz", Network.TestNet),
("bitcoin:2MzQwSSnBHWHqSAqtTVQ6v47XtaisrJa1Vc?amount=50&label=Luke-Jr&message=Donation%20for%20project%20xyz", Network.TestNet),
("bitcoin:tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx?amount=50&label=Luke-Jr&message=Donation%20for%20project%20xyz", Network.TestNet),
};
foreach (var test in tests)
{
Assert.False(AddressStringParser.TryParseBitcoinUrl(test.url[1..], test.network, out _));
Assert.False(AddressStringParser.TryParseBitcoinUrl(test.url.Remove(5, 4), test.network, out _));
Assert.False(AddressStringParser.TryParseBitcoinUrl(test.url.Insert(1, "b"), test.network, out _));
Assert.False(AddressStringParser.TryParseBitcoinUrl(test.url, null, out _));
Assert.False(AddressStringParser.TryParseBitcoinUrl(null, test.network, out _));
Assert.True(AddressStringParser.TryParseBitcoinUrl(test.url, test.network, out BitcoinUrlBuilder? result));
Assert.Equal(test.url.Split(new[] { ':', '?' })[1], result.Address.ToString());
Assert.True(AddressStringParser.TryParseBitcoinUrl(test.url.Insert(0, " "), test.network, out result));
Assert.Equal(test.url.Split(new[] { ':', '?' })[1], result.Address.ToString());
Assert.Equal("Luke-Jr", result.Label);
Assert.Equal(Money.Coins(50m), result.Amount);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using SharpEssentials.Testing;
using Xunit;
using Xunit.Sdk;
namespace SharpEssentials.Tests.Unit
{
/// <summary>
/// Contains tests for custom assertions.
/// </summary>
public class AssertThatTests
{
[Fact]
public void Test_SequenceEqual_ShorterThanExpected()
{
// Arrange.
var expected = new List<int> { 1, 2, 3 };
var actual = new List<int> { 1, 2 };
// Act/Assert.
var exception = Assert.Throws<SequenceEqualException>(() =>
AssertThat.SequenceEqual(expected, actual));
Assert.Equal("1,2,3", exception.Expected);
Assert.Equal("1,2", exception.Actual);
Assert.Equal("SequenceEqualException : SequenceEqual Assertion Failure\r\nExpected: 1,2,3\r\nActual: 1,2", exception.Message);
}
[Fact]
public void Test_SequenceEqual_LongerThanExpected()
{
// Arrange.
var expected = new List<int> { 1, 2 };
var actual = new List<int> { 1, 2, 3 };
// Act/Assert.
var exception = Assert.Throws<SequenceEqualException>(() =>
AssertThat.SequenceEqual(expected, actual));
Assert.Equal("1,2", exception.Expected);
Assert.Equal("1,2,3", exception.Actual);
Assert.Equal("SequenceEqualException : SequenceEqual Assertion Failure\r\nExpected: 1,2\r\nActual: 1,2,3", exception.Message);
}
[Fact]
public void Test_SequenceEqual_ElementDifference()
{
// Arrange.
var expected = new List<int> { 1, 4, 3 };
var actual = new List<int> { 1, 2, 3 };
// Act/Assert.
var exception = Assert.Throws<SequenceEqualException>(() =>
AssertThat.SequenceEqual(expected, actual));
Assert.Equal("1,4", exception.Expected);
Assert.Equal("1,2", exception.Actual);
Assert.Equal("SequenceEqualException : SequenceEqual Assertion Failure\r\nExpected: 1,4,...\r\nActual: 1,2,...", exception.Message);
}
[Fact]
public void Test_SequenceEqual_EqualLists()
{
// Arrange.
var expected = new List<int> { 1, 2, 3 };
var actual = new List<int> { 1, 2, 3 };
// Act/Assert.
AssertThat.SequenceEqual(expected, actual);
}
[Fact]
public void Test_SequenceEqual_EqualSequences()
{
// Arrange.
var expected = new List<int> { 1, 2, 3 };
var actual = Enumerable.Range(1, 3);
// Act/Assert.
AssertThat.SequenceEqual(expected, actual);
}
[Fact]
public void Test_SequenceEqual_EmptyExpected()
{
// Arrange.
var expected = Enumerable.Empty<int>();
var actual = new List<int> { 1, 2, 3 };
// Act/Assert.
var exception = Assert.Throws<SequenceEqualException>(() =>
AssertThat.SequenceEqual(expected, actual));
Assert.Equal(string.Empty, exception.Expected);
Assert.Equal("1", exception.Actual);
Assert.Equal("SequenceEqualException : SequenceEqual Assertion Failure\r\nExpected: Empty Sequence\r\nActual: 1,...", exception.Message);
}
[Fact]
public void Test_SequenceEqual_EmptyActual()
{
// Arrange.
var expected = new List<int> { 1, 2, 3 };
var actual = Enumerable.Empty<int>();
// Act/Assert.
var exception = Assert.Throws<SequenceEqualException>(() =>
AssertThat.SequenceEqual(expected, actual));
Assert.Equal("1", exception.Expected);
Assert.Equal(string.Empty, exception.Actual);
Assert.Equal("SequenceEqualException : SequenceEqual Assertion Failure\r\nExpected: 1,...\r\nActual: Empty Sequence", exception.Message);
}
[Fact]
public void Test_Raises_WithEventName_Success()
{
// Arrange.
IEventTest test = new EventTest();
// Act/Assert.
AssertThat.Raises(test, "TestEvent", () => test.OnTestEvent(4));
Assert.True(test.EventRaised);
}
[Fact]
public void Test_Raises_WithEventName_Failure()
{
// Arrange.
IEventTest test = new EventTest();
// Act/Assert.
Assert.Throws<Testing.RaisesException>(() =>
AssertThat.Raises(test, "TestEvent", () => test.ToString()));
Assert.False(test.EventRaised);
}
[Fact]
public void Test_Raises_WithEventSubscriber_Success()
{
// Arrange.
IEventTest test = new EventTest();
// Act/Assert.
AssertThat.Raises(test, t => t.TestEvent += null, () => test.OnTestEvent(4));
Assert.True(test.EventRaised);
}
[Fact]
public void Test_Raises_WithEventSubscriber_Failure()
{
// Arrange.
IEventTest test = new EventTest();
// Act/Assert.
Assert.Throws<Testing.RaisesException>(() =>
AssertThat.Raises(test, t => t.TestEvent += null, () => test.ToString()));
Assert.False(test.EventRaised);
}
[Fact]
public void Test_DoesNotRaise_WithEventName_Success()
{
// Arrange.
IEventTest test = new EventTest();
// Act/Assert.
Assert.Throws<Testing.RaisesException>(() =>
AssertThat.DoesNotRaise(test, "TestEvent", () => test.OnTestEvent(4)));
Assert.True(test.EventRaised);
}
[Fact]
public void Test_DoesNotRaise_WithEventName_Failure()
{
// Arrange.
IEventTest test = new EventTest();
// Act/Assert.
AssertThat.DoesNotRaise(test, "TestEvent", () => test.ToString());
Assert.False(test.EventRaised);
}
[Fact]
public void Test_DoesNotRaise_WithEventSubscriber_Success()
{
// Arrange.
IEventTest test = new EventTest();
// Act/Assert.
Assert.Throws<Testing.RaisesException>(() =>
AssertThat.DoesNotRaise(test, t => t.TestEvent += null, () => test.OnTestEvent(4)));
Assert.True(test.EventRaised);
}
[Fact]
public void Test_DoesNotRaise_WithEventSubscriber_Failure()
{
// Arrange.
IEventTest test = new EventTest();
// Act/Assert.
AssertThat.DoesNotRaise(test, t => t.TestEvent += null, () => test.ToString());
Assert.False(test.EventRaised);
}
[Fact]
public void Test_RaisesWithEventArgs_WithEventName_Success()
{
// Arrange.
IEventTest test = new EventTest();
// Act/Assert.
var args = AssertThat.RaisesWithEventArgs<TestEventArgs>(test,
"TestEvent",
() => test.OnTestEvent(4));
Assert.Equal(4, args.Value);
Assert.True(test.EventRaised);
}
[Fact]
public void Test_RaisesWithEventArgs_WithEventName_EventNotRaised()
{
// Arrange.
IEventTest test = new EventTest();
// Act/Assert.
Assert.Throws<Testing.RaisesException>(() =>
AssertThat.RaisesWithEventArgs<TestEventArgs>(test, "TestEvent", () => test.ToString()));
Assert.False(test.EventRaised);
}
[Fact]
public void Test_RaisesWithEventArgs_WithEventSubscriber_Success()
{
// Arrange.
IEventTest test = new EventTest();
// Act/Assert.
var args = AssertThat.RaisesWithEventArgs<IEventTest, TestEventArgs>(test,
t => t.TestEvent += null,
() => test.OnTestEvent(4));
Assert.Equal(4, args.Value);
Assert.True(test.EventRaised);
}
[Fact]
public void Test_RaisesWithEventArgs_WithEventSubscriber_Failure_EventNotRaised()
{
// Arrange.
IEventTest test = new EventTest();
// Act/Assert.
Assert.Throws<Testing.RaisesException>(() =>
AssertThat.RaisesWithEventArgs<IEventTest, TestEventArgs>(test, t => t.TestEvent += null, () => test.ToString()));
Assert.False(test.EventRaised);
}
[Fact]
public void Test_PropertyChanged_EventNotRaised()
{
// Arrange.
var test = new EventTest { IntProperty = 3 };
// Act/Assert.
Assert.Throws<PropertyChangedException>(() =>
AssertThat.PropertyChanged(test, t => t.IntProperty, () => test.IntProperty = 3));
}
[Fact]
public void Test_PropertyChanged_EventRaised_WrongProperty()
{
// Arrange.
var test = new EventTest();
// Act/Assert.
Assert.Throws<PropertyChangedException>(() =>
AssertThat.PropertyChanged(test, t => t.IntProperty, () => test.StringProperty = "value"));
}
[Fact]
public void Test_PropertyChanged_EventRaised()
{
// Arrange.
var test = new EventTest();
// Act/Assert.
AssertThat.PropertyChanged(test, t => t.IntProperty, () => test.IntProperty = 3);
}
[Fact]
public void Test_PropertyDoesNotChange_EventNotRaised()
{
// Arrange.
var test = new EventTest { IntProperty = 3 };
// Act/Assert.
AssertThat.PropertyDoesNotChange(test, t => t.IntProperty, () => test.IntProperty = 3);
}
[Fact]
public void Test_PropertyDoesNotChange_EventRaised_WrongProperty()
{
// Arrange.
var test = new EventTest();
// Act/Assert.
AssertThat.PropertyDoesNotChange(test, t => t.IntProperty, () => test.StringProperty = "value");
}
[Fact]
public void Test_PropertyDoesNotChange_EventRaised()
{
// Arrange.
var test = new EventTest();
// Act/Assert.
Assert.Throws<PropertyDoesNotChangeException>(() =>
AssertThat.PropertyDoesNotChange(test, t => t.IntProperty, () => test.IntProperty = 3));
}
public interface IEventTest
{
event EventHandler<TestEventArgs> TestEvent;
void OnTestEvent(int value);
bool EventRaised { get; }
}
private class EventTest : IEventTest, INotifyPropertyChanged
{
public event EventHandler<TestEventArgs> TestEvent;
public void OnTestEvent(int value)
{
if (TestEvent != null)
{
TestEvent(this, new TestEventArgs(value));
EventRaised = true;
}
}
public bool EventRaised { get; private set; }
public int IntProperty
{
get { return _intProperty; }
set
{
if (_intProperty != value)
{
_intProperty = value;
OnPropertyChanged();
}
}
}
private int _intProperty;
public string StringProperty
{
get { return _stringProperty; }
set
{
if (_stringProperty != value)
{
_stringProperty = value;
OnPropertyChanged();
}
}
}
private string _stringProperty;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class TestEventArgs : EventArgs
{
public TestEventArgs(int value)
{
Value = value;
}
public int Value { get; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
/// <summary>
/// Dictionary.KeyCollection.CopyTo(TKey[],Int32)
/// </summary>
public class KeyCollectionCopyTo
{
private const int SIZE = 10;
public static int Main()
{
KeyCollectionCopyTo keycollectCopyTo = new KeyCollectionCopyTo();
TestLibrary.TestFramework.BeginTestCase("KeyCollectionCopyTo");
if (keycollectCopyTo.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
return retVal;
}
#region PositiveTest
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1:Invoke the method CopyTo in the KeyCollection 1");
try
{
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("str1", "Test1");
dic.Add("str2", "Test2");
Dictionary<string, string>.KeyCollection keys = new Dictionary<string, string>.KeyCollection(dic);
string[] TKeys = new string[SIZE];
keys.CopyTo(TKeys, 0);
string strKeys = null;
for (int i = 0; i < TKeys.Length; i++)
{
if (TKeys[i] != null)
{
strKeys += TKeys[i].ToString();
}
}
if (TKeys[0].ToString() != "str1" || TKeys[1].ToString() != "str2" || strKeys != "str1str2")
{
TestLibrary.TestFramework.LogError("001", "the ExpecResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2:Invoke the method CopyTo in the KeyCollection 2");
try
{
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("str1", "Test1");
dic.Add("str2", "Test2");
Dictionary<string, string>.KeyCollection keys = new Dictionary<string, string>.KeyCollection(dic);
string[] TKeys = new string[SIZE];
keys.CopyTo(TKeys, 5);
string strKeys = null;
for (int i = 0; i < TKeys.Length; i++)
{
if (TKeys[i] != null)
{
strKeys += TKeys[i].ToString();
}
}
if (TKeys[5].ToString() != "str1" || TKeys[6].ToString() != "str2" || strKeys != "str1str2")
{
TestLibrary.TestFramework.LogError("003", "the ExpecResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3:Invoke the method CopyTo in the KeyCollection 3");
try
{
Dictionary<string, string> dic = new Dictionary<string, string>();
Dictionary<string, string>.KeyCollection keys = new Dictionary<string, string>.KeyCollection(dic);
string[] TKeys = new string[SIZE];
keys.CopyTo(TKeys, 0);
for (int i = 0; i < TKeys.Length; i++)
{
if (TKeys[i] != null)
{
TestLibrary.TestFramework.LogError("005", "the ExpecResult is not the ActualResult");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region NegativeTest
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1:The argument array is null");
try
{
Dictionary<string, string> dic = new Dictionary<string, string>();
Dictionary<string, string>.KeyCollection keys = new Dictionary<string, string>.KeyCollection(dic);
string[] TKeys = null;
keys.CopyTo(TKeys, 0);
TestLibrary.TestFramework.LogError("N001", "The argument array is null but not throw exception");
retVal = false;
}
catch (ArgumentNullException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N002", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2:The argument index is less than zero");
try
{
Dictionary<string, string> dic = new Dictionary<string, string>();
Dictionary<string, string>.KeyCollection keys = new Dictionary<string, string>.KeyCollection(dic);
string[] TKeys = new string[SIZE];
int index = -1;
keys.CopyTo(TKeys, index);
TestLibrary.TestFramework.LogError("N003", "The argument index is less than zero but not throw exception");
retVal = false;
}
catch (ArgumentOutOfRangeException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N004", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3:The argument index is larger than array length");
try
{
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("str1", "Test1");
Dictionary<string, string>.KeyCollection keys = new Dictionary<string, string>.KeyCollection(dic);
string[] TKeys = new string[SIZE];
int index = SIZE + 1;
keys.CopyTo(TKeys, index);
TestLibrary.TestFramework.LogError("N005", "The argument index is larger than array length but not throw exception");
retVal = false;
}
catch (ArgumentException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N006", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4:The number of elements in the source Dictionary.KeyCollection is greater than the available space from index to the end of the destination array");
try
{
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("str1", "Test1");
dic.Add("str1", "Test1");
Dictionary<string, string>.KeyCollection keys = new Dictionary<string, string>.KeyCollection(dic);
string[] TKeys = new string[SIZE];
int index = SIZE - 1;
keys.CopyTo(TKeys, index);
TestLibrary.TestFramework.LogError("N007", "The ExpectResult should throw exception but the ActualResult not throw exception");
retVal = false;
}
catch (ArgumentException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N008", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
}
| |
/*
* Copyright (c) 2006-2014 Michal Kuncl <michal.kuncl@gmail.com> http://www.pavucina.info
* 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.
*
*
* Uses some parts from GitRevision program by Yves Goergen
* http://dev.unclassified.de/en/apps/gitrevisiontool
* https://github.com/dg9ngf/GitRevisionTool
*/
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace GitVersioner
{
internal static class GitHandler
{
/// <summary>
/// The git executable name
/// </summary>
private static readonly string GitExeName = Environment.OSVersion.Platform == PlatformID.Unix
? "git"
: "git.exe";
/// <summary>
/// Gets a value indicating whether OS is 64bit.
/// </summary>
/// <value>
/// <c>true</c> if [is64 bit]; otherwise, <c>false</c>.
/// </value>
private static bool Is64Bit => IntPtr.Size == 8 ||
!string.IsNullOrEmpty(
Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432"));
/// <summary>
/// Gets Program Files directory
/// </summary>
/// <returns>Program Files or Program Files (x86) directory</returns>
private static string ProgramFilesX86()
{
var result = Environment.GetEnvironmentVariable(Is64Bit ? "ProgramFiles(x86)" : "ProgramFiles");
if (string.IsNullOrEmpty(result)) result = @"C:\Program Files\";
return result;
}
/// <summary>
/// Finds the git binary.
/// </summary>
/// <returns></returns>
/// <exception cref="IOException">
/// The <see cref="T:Microsoft.Win32.RegistryKey" /> that contains the specified value has
/// been marked for deletion.
/// </exception>
/// <exception cref="UnauthorizedAccessException">The user does not have the necessary registry rights.</exception>
/// <exception cref="DirectoryNotFoundException">The specified path is invalid (for example, it is on an unmapped drive). </exception>
public static string FindGitBinary()
{
string git = null;
// Try the PATH environment variable
var pathEnv = Environment.GetEnvironmentVariable("PATH");
if (pathEnv != null)
foreach (var dir in pathEnv.Split(Path.PathSeparator))
{
var sdir = dir;
if (sdir.StartsWith("\"") && sdir.EndsWith("\""))
sdir = sdir.Substring(1, sdir.Length - 2);
git = Path.Combine(sdir, GitExeName);
if (File.Exists(git)) break;
}
if (!File.Exists(git)) git = null;
// Search program files directory
if (git == null)
foreach (
var dir in
Directory.GetDirectories(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),
"git*"))
{
git = Path.Combine(dir, Path.Combine("bin", GitExeName));
if (!File.Exists(git)) git = null;
}
// Try 32-bit program files directory
if (git != null || !Is64Bit) return git;
foreach (var dir in Directory.GetDirectories(ProgramFilesX86(), "git*"))
{
git = Path.Combine(dir, Path.Combine("bin", GitExeName));
if (!File.Exists(git)) git = null;
}
return git;
}
/// <summary>
/// Gets the version information.
/// </summary>
/// <param name="workDir">The work dir.</param>
/// <returns></returns>
public static GitResult GetVersionInfo(string workDir)
{
Console.WriteLine("Getting version info for {0}", workDir);
var lines = ExecGit(workDir, "describe --long --tags --always");
GitResult r;
r.MajorVersion = "0";
r.MinorVersion = "0";
r.Revision = "0";
r.Commit = "0";
r.TotalCommits = "0";
r.CommitsInCurrentBranch = "0";
r.ShortHash = "";
// ocekavany retezec ve formatu: 1.7.6-235-g0a52e4b
var part1 = lines.Split('-');
if (part1.Length >= 3)
{
// druhou cast rozdelit po teckach
var part2 = part1[0].Split('.');
if (part2.Length > 1)
{
// delsi nez 1: mame major a minor verzi
if (part2.Length > 2) r.Revision = part2[2];
r.MinorVersion = part2[1];
}
// mame jen major verzi
var s = part2[0].ToLowerInvariant();
// kdyby nahodou nekdo chtel pojmenovavat git tagy v1.0.0 atd (tj zacinajci ne cislem ale v)
if (s[0] == 'v') s = s.Remove(0, 1);
r.MajorVersion = s;
}
// if commit parsing fails default to zero, we'll count commits later
r.Commit = part1.Length < 2 ? "0" : part1[1].Trim();
// just shorthash is remaining. it's either part 2 of part1 or everything
r.ShortHash = part1.Length > 2 ? part1[2].Trim() : lines.Trim();
// get total commits
r.TotalCommits = ExecGit(workDir, "rev-list --count --all").Trim();
//
// if no tags are present we'll get 0.0.0-0-abcdefg
// give total commit count at least
if (r.MajorVersion.TryToInt32() == 0 && r.MinorVersion.TryToInt32() == 0 && r.Revision.TryToInt32() == 0 &&
r.Commit.TryToInt32() == 0)
r.Commit = r.TotalCommits;
r.Branch = ExecGit(workDir, "rev-parse --abbrev-ref HEAD").Trim();
// we don't want branches to be called HEAD...
if (r.Branch == "HEAD")
r.Branch = ExecGit(workDir, "describe --all").Trim();
// get commits in current branch before cleaning branch name
r.CommitsInCurrentBranch = ExecGit(workDir, $"rev-list --count {r.Branch}").Trim();
r.Branch = CleanBranchName(r.Branch);
r.LongHash = ExecGit(workDir, "rev-parse HEAD").Trim();
Console.WriteLine("Version info: {0}", GitResultToString(r));
if (string.IsNullOrEmpty(lines))
Console.WriteLine("Possible error, git output follows:\n {0}", lines);
return r;
}
/// <summary>
/// Cleans the name of the branch.
/// </summary>
/// <param name="branch">The branch.</param>
/// <returns></returns>
public static string CleanBranchName(string branch)
{
var s = branch;
s = s.Replace("refs", string.Empty);
s = s.Replace("remotes", string.Empty);
s = s.Replace("remote", string.Empty);
s = s.Replace("origin", string.Empty);
s = s.Replace("heads", string.Empty);
s = s.Replace("heads/", string.Empty);
// get rid of all slashes
while (s.Contains("//"))
s = s.Replace("//", "/");
s = s.Replace("/", "-");
s = s.TrimStart('-');
return s;
}
/// <summary>
/// Converts git results to string
/// </summary>
/// <param name="gr">GitResult.</param>
/// <returns></returns>
public static string GitResultToString(GitResult gr)
{
return $"{gr.MajorVersion}.{gr.MinorVersion}.{gr.Revision}-{gr.Commit}-{gr.ShortHash}";
}
/// <summary>
/// Executes the git program.
/// </summary>
/// <param name="workDir">The work dir.</param>
/// <param name="parameters">The parameters.</param>
/// <returns></returns>
private static string ExecGit(string workDir, string parameters)
{
var psi = new ProcessStartInfo(FindGitBinary(), parameters)
{
WorkingDirectory = workDir,
RedirectStandardOutput = true,
UseShellExecute = false
};
var p = Process.Start(psi);
var r = new StringBuilder();
while (p != null && !p.StandardOutput.EndOfStream)
r.AppendLine(p.StandardOutput.ReadLine());
if (p != null && !p.WaitForExit(1000))
p.Kill();
return r.ToString();
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: health.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.Health.V1 {
/// <summary>Holder for reflection information generated from health.proto</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class HealthReflection {
#region Descriptor
/// <summary>File descriptor for health.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static HealthReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CgxoZWFsdGgucHJvdG8SDmdycGMuaGVhbHRoLnYxIiUKEkhlYWx0aENoZWNr",
"UmVxdWVzdBIPCgdzZXJ2aWNlGAEgASgJIpQBChNIZWFsdGhDaGVja1Jlc3Bv",
"bnNlEkEKBnN0YXR1cxgBIAEoDjIxLmdycGMuaGVhbHRoLnYxLkhlYWx0aENo",
"ZWNrUmVzcG9uc2UuU2VydmluZ1N0YXR1cyI6Cg1TZXJ2aW5nU3RhdHVzEgsK",
"B1VOS05PV04QABILCgdTRVJWSU5HEAESDwoLTk9UX1NFUlZJTkcQAjJaCgZI",
"ZWFsdGgSUAoFQ2hlY2sSIi5ncnBjLmhlYWx0aC52MS5IZWFsdGhDaGVja1Jl",
"cXVlc3QaIy5ncnBjLmhlYWx0aC52MS5IZWFsdGhDaGVja1Jlc3BvbnNlQhGq",
"Ag5HcnBjLkhlYWx0aC5WMWIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Grpc.Health.V1.HealthCheckRequest), global::Grpc.Health.V1.HealthCheckRequest.Parser, new[]{ "Service" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Grpc.Health.V1.HealthCheckResponse), global::Grpc.Health.V1.HealthCheckResponse.Parser, new[]{ "Status" }, null, new[]{ typeof(global::Grpc.Health.V1.HealthCheckResponse.Types.ServingStatus) }, null)
}));
}
#endregion
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class HealthCheckRequest : pb::IMessage<HealthCheckRequest> {
private static readonly pb::MessageParser<HealthCheckRequest> _parser = new pb::MessageParser<HealthCheckRequest>(() => new HealthCheckRequest());
public static pb::MessageParser<HealthCheckRequest> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Grpc.Health.V1.HealthReflection.Descriptor.MessageTypes[0]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public HealthCheckRequest() {
OnConstruction();
}
partial void OnConstruction();
public HealthCheckRequest(HealthCheckRequest other) : this() {
service_ = other.service_;
}
public HealthCheckRequest Clone() {
return new HealthCheckRequest(this);
}
/// <summary>Field number for the "service" field.</summary>
public const int ServiceFieldNumber = 1;
private string service_ = "";
public string Service {
get { return service_; }
set {
service_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
public override bool Equals(object other) {
return Equals(other as HealthCheckRequest);
}
public bool Equals(HealthCheckRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Service != other.Service) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Service.Length != 0) hash ^= Service.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Service.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Service);
}
}
public int CalculateSize() {
int size = 0;
if (Service.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Service);
}
return size;
}
public void MergeFrom(HealthCheckRequest other) {
if (other == null) {
return;
}
if (other.Service.Length != 0) {
Service = other.Service;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Service = input.ReadString();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class HealthCheckResponse : pb::IMessage<HealthCheckResponse> {
private static readonly pb::MessageParser<HealthCheckResponse> _parser = new pb::MessageParser<HealthCheckResponse>(() => new HealthCheckResponse());
public static pb::MessageParser<HealthCheckResponse> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Grpc.Health.V1.HealthReflection.Descriptor.MessageTypes[1]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public HealthCheckResponse() {
OnConstruction();
}
partial void OnConstruction();
public HealthCheckResponse(HealthCheckResponse other) : this() {
status_ = other.status_;
}
public HealthCheckResponse Clone() {
return new HealthCheckResponse(this);
}
/// <summary>Field number for the "status" field.</summary>
public const int StatusFieldNumber = 1;
private global::Grpc.Health.V1.HealthCheckResponse.Types.ServingStatus status_ = 0;
public global::Grpc.Health.V1.HealthCheckResponse.Types.ServingStatus Status {
get { return status_; }
set {
status_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as HealthCheckResponse);
}
public bool Equals(HealthCheckResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Status != other.Status) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Status != 0) hash ^= Status.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Status != 0) {
output.WriteRawTag(8);
output.WriteEnum((int) Status);
}
}
public int CalculateSize() {
int size = 0;
if (Status != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Status);
}
return size;
}
public void MergeFrom(HealthCheckResponse other) {
if (other == null) {
return;
}
if (other.Status != 0) {
Status = other.Status;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
status_ = (global::Grpc.Health.V1.HealthCheckResponse.Types.ServingStatus) input.ReadEnum();
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the HealthCheckResponse message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Types {
public enum ServingStatus {
[pbr::OriginalName("UNKNOWN")] Unknown = 0,
[pbr::OriginalName("SERVING")] Serving = 1,
[pbr::OriginalName("NOT_SERVING")] NotServing = 2,
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| |
//******************************
// Written by Peter Golde
// Copyright (c) 2004-2005, Wintellect
//
// Use and restribution of this code is subject to the license agreement
// contained in the file "License.txt" accompanying this file.
//******************************
using System;
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
namespace Wintellect.PowerCollections.Tests
{
/// <summary>
/// Tests for the Pair struct.
/// </summary>
[TestFixture]
public class PairTests
{
/// <summary>
/// Class that doesn't implement any IComparable.
/// </summary>
class Unorderable
{
public override bool Equals(object obj)
{
return obj is Unorderable;
}
public override int GetHashCode()
{
return 42;
}
}
/// <summary>
/// Comparable that compares ints, sorting odds before evens.
/// </summary>
class OddEvenComparable : System.IComparable
{
public int val;
public OddEvenComparable(int v)
{
val = v;
}
public int CompareTo(object other)
{
int e1 = val;
int e2 = ((OddEvenComparable)other).val;
if ((e1 & 1) == 1 && (e2 & 1) == 0)
return -1;
else if ((e1 & 1) == 0 && (e2 & 1) == 1)
return 1;
else if (e1 < e2)
return -1;
else if (e1 > e2)
return 1;
else
return 0;
}
public override bool Equals(object obj)
{
if (obj is OddEvenComparable)
return CompareTo((OddEvenComparable)obj) == 0;
else
return false;
}
public override int GetHashCode()
{
return val.GetHashCode();
}
}
/// <summary>
/// Comparable that compares ints, sorting odds before evens.
/// </summary>
class GOddEvenComparable : System.IComparable<GOddEvenComparable>
{
public int val;
public GOddEvenComparable(int v)
{
val = v;
}
public int CompareTo(GOddEvenComparable other)
{
int e1 = val;
int e2 = other.val;
if ((e1 & 1) == 1 && (e2 & 1) == 0)
return -1;
else if ((e1 & 1) == 0 && (e2 & 1) == 1)
return 1;
else if (e1 < e2)
return -1;
else if (e1 > e2)
return 1;
else
return 0;
}
public override bool Equals(object other)
{
return (other is GOddEvenComparable) && CompareTo((GOddEvenComparable)other) == 0;
}
public override int GetHashCode()
{
return val.GetHashCode();
}
}
/// <summary>
/// Test basic Pair creation.
/// </summary>
[Test]
public void Creation()
{
Pair<int,double> p1 = new Pair<int,double>();
Assert.AreEqual(0, p1.First);
Assert.AreEqual(0.0, p1.Second);
Pair<int,string> p2 = new Pair<int,string>(42, "hello");
Assert.AreEqual(42, p2.First);
Assert.AreEqual("hello", p2.Second);
Pair<string,object> p3 = new Pair<string,object>();
Assert.IsNull(p3.First);
Assert.IsNull(p3.Second);
object o = new object();
Pair<Pair<string,int>,object> p4 = new Pair<Pair<string,int>,object>(new Pair<string,int>("foo", 12), o);
Pair<string,int> p5 = p4.First;
Assert.AreEqual("foo", p5.First);
Assert.AreEqual(12, p5.Second);
Assert.AreSame(o, p4.Second);
}
/// <summary>
/// Test get and set of First and Second.
/// </summary>
[Test]
public void Elements()
{
Pair<int,string> p1 = new Pair<int,string>();
string s = new string('z', 3);
p1.First = 217;
p1.Second = s;
Assert.AreEqual(217, p1.First);
Assert.AreSame(s, p1.Second);
Pair<string,int> p2 = new Pair<string,int>("hello", 1);
p2.Second = 212;
p2.First = s;
Assert.AreEqual(212, p2.Second);
Assert.AreSame(s, p2.First);
p2.First = null;
Assert.IsNull(p2.First);
}
[Test]
public void Equals()
{
Pair<int,string> p1 = new Pair<int,string>(42, new string('z', 3));
Pair<int,string> p2 = new Pair<int,string>(53, new string('z', 3));
Pair<int,string> p3 = new Pair<int,string>(42, new string('z', 4));
Pair<int,string> p4 = new Pair<int,string>(42, new string('z', 3));
Pair<int,string> p5 = new Pair<int,string>(122, new string('y', 3));
Pair<int,string> p6 = new Pair<int,string>(122, null);
Pair<int,string> p7 = new Pair<int,string>(122, null);
bool f;
f = p1.Equals(p2); Assert.IsFalse(f);
f = p1.Equals(p3); Assert.IsFalse(f);
f = p1.Equals(p4); Assert.IsTrue(f);
f = p1.Equals(p5); Assert.IsFalse(f);
f = p1.Equals("hi"); Assert.IsFalse(f);
f = p6.Equals(p7); Assert.IsTrue(f);
f = p1 == p2; Assert.IsFalse(f);
f = p1 == p3; Assert.IsFalse(f);
f = p1 == p4; Assert.IsTrue(f);
f = p1 == p5; Assert.IsFalse(f);
f = p6 == p7; Assert.IsTrue(f);
f = p1 != p2; Assert.IsTrue(f);
f = p1 != p3; Assert.IsTrue(f);
f = p1 != p4; Assert.IsFalse(f);
f = p1 != p5; Assert.IsTrue(f);
f = p6 != p7; Assert.IsFalse(f);
}
[Test]
public void HashCode()
{
Pair<int,string> p1 = new Pair<int,string>(42, new string('z', 3));
Pair<int,string> p2 = new Pair<int,string>(53, new string('z', 3));
Pair<int,string> p3 = new Pair<int,string>(42, new string('z', 4));
Pair<int,string> p4 = new Pair<int,string>(42, new string('z', 3));
Pair<int,string> p5 = new Pair<int,string>(122, new string('y', 3));
Pair<int,string> p6 = new Pair<int,string>(122, null);
Pair<int,string> p7 = new Pair<int,string>(122, null);
int h1 = p1.GetHashCode();
int h2 = p2.GetHashCode();
int h3 = p3.GetHashCode();
int h4 = p4.GetHashCode();
int h5 = p5.GetHashCode();
int h6 = p6.GetHashCode();
int h7 = p7.GetHashCode();
bool f;
f = h1 == h2; Assert.IsFalse(f);
f = h1 == h3; Assert.IsFalse(f);
f = h1 == h4; Assert.IsTrue(f);
f = h1 == h5; Assert.IsFalse(f);
f = h6 == h7; Assert.IsTrue(f);
}
[Test]
public void Stringize()
{
Pair<int,string> p1 = new Pair<int,string>(42, new string('z', 3));
Pair<int,string> p2 = new Pair<int,string>(0, "hello");
Pair<int,string> p3 = new Pair<int,string>(-122, null);
Pair<string,int> p4 = new Pair<string,int>(null, 11);
Assert.AreEqual("First: 42, Second: zzz", p1.ToString());
Assert.AreEqual("First: 0, Second: hello", p2.ToString());
Assert.AreEqual("First: -122, Second: null", p3.ToString());
Assert.AreEqual("First: null, Second: 11", p4.ToString());
}
[Test]
[ExpectedException(typeof(NotSupportedException), "Type \"Wintellect.PowerCollections.Tests.PairTests+Unorderable\" does not implement IComparable<Wintellect.PowerCollections.Tests.PairTests+Unorderable> or IComparable.")]
public void UncomparableFirst()
{
Pair<Unorderable, int> pair1, pair2;
pair1 = new Pair<Unorderable, int>(new Unorderable(), 5);
pair2 = new Pair<Unorderable, int>(new Unorderable(), 7);
int compare = pair1.CompareTo(pair2);
}
[Test]
[ExpectedException(typeof(NotSupportedException), "Type \"Wintellect.PowerCollections.Tests.PairTests+Unorderable\" does not implement IComparable<Wintellect.PowerCollections.Tests.PairTests+Unorderable> or IComparable.")]
public void UncomparableSecond()
{
Pair<int, Unorderable> pair1, pair2;
pair1 = new Pair<int, Unorderable>(3, new Unorderable());
pair2 = new Pair<int, Unorderable>(3, new Unorderable());
int compare = pair1.CompareTo(pair2);
}
[Test]
public void EqualUncomparable()
{
Pair<Unorderable, string> pair1, pair2, pair3;
pair1 = new Pair<Unorderable, string>(new Unorderable(), "hello");
pair2 = new Pair<Unorderable, string>(new Unorderable(), "world");
pair3 = new Pair<Unorderable, string>(new Unorderable(), "hello");
Assert.IsFalse(pair1.Equals(pair2));
Assert.IsTrue(pair1.Equals(pair3));
Assert.IsFalse(pair1 == pair2);
Assert.IsTrue(pair1 == pair3);
Assert.IsFalse(pair1.GetHashCode() == pair2.GetHashCode());
Assert.IsTrue(pair1.GetHashCode() == pair3.GetHashCode());
}
[Test]
public void NongenericComparable()
{
Pair<int, OddEvenComparable> pair1, pair2;
pair1 = new Pair<int, OddEvenComparable>(4, new OddEvenComparable(7));
pair2 = new Pair<int, OddEvenComparable>(7, new OddEvenComparable(3));
Assert.IsTrue(pair1.CompareTo(pair2) < 0);
Assert.IsFalse(pair1.Equals(pair2));
Assert.IsFalse(pair1.GetHashCode() == pair2.GetHashCode());
pair1 = new Pair<int, OddEvenComparable>(4, new OddEvenComparable(7));
pair2 = new Pair<int, OddEvenComparable>(4, new OddEvenComparable(2));
Assert.IsTrue(pair1.CompareTo(pair2) < 0);
Assert.IsFalse(pair1.Equals(pair2));
Assert.IsFalse(pair1.GetHashCode() == pair2.GetHashCode());
pair1 = new Pair<int, OddEvenComparable>(4, new OddEvenComparable(7));
pair2 = new Pair<int, OddEvenComparable>(4, new OddEvenComparable(7));
Assert.IsTrue(pair1.CompareTo(pair2) == 0);
Assert.IsTrue(pair1.Equals(pair2));
Assert.IsTrue(pair1.GetHashCode() == pair2.GetHashCode());
pair1 = new Pair<int, OddEvenComparable>(7, new OddEvenComparable(7));
pair2 = new Pair<int, OddEvenComparable>(4, new OddEvenComparable(2));
Assert.IsTrue(pair1.CompareTo(pair2) > 0);
Assert.IsFalse(pair1.Equals(pair2));
Assert.IsFalse(pair1.GetHashCode() == pair2.GetHashCode());
pair1 = new Pair<int, OddEvenComparable>(0, new OddEvenComparable(8));
pair2 = new Pair<int, OddEvenComparable>(0, new OddEvenComparable(2));
Assert.IsTrue(pair1.CompareTo(pair2) > 0);
Assert.IsFalse(pair1.Equals(pair2));
Assert.IsFalse(pair1.GetHashCode() == pair2.GetHashCode());
Pair<OddEvenComparable, int> pair3, pair4;
pair3 = new Pair<OddEvenComparable, int>(new OddEvenComparable(7), 4);
pair4 = new Pair<OddEvenComparable, int>(new OddEvenComparable(3), 7);
Assert.IsTrue(pair3.CompareTo(pair4) > 0);
Assert.IsFalse(pair3.Equals(pair4));
Assert.IsFalse(pair3.GetHashCode() == pair4.GetHashCode());
pair3 = new Pair<OddEvenComparable, int>(new OddEvenComparable(7), 4);
pair4 = new Pair<OddEvenComparable, int>(new OddEvenComparable(2), 4);
Assert.IsTrue(pair3.CompareTo(pair4) < 0);
Assert.IsFalse(pair3.Equals(pair4));
Assert.IsFalse(pair3.GetHashCode() == pair4.GetHashCode());
pair3 = new Pair<OddEvenComparable, int>(new OddEvenComparable(7), 4);
pair4 = new Pair<OddEvenComparable, int>(new OddEvenComparable(7), 4);
Assert.IsTrue(pair3.CompareTo(pair4) == 0);
Assert.IsTrue(pair3.Equals(pair4));
Assert.IsTrue(pair3.GetHashCode() == pair4.GetHashCode());
pair3 = new Pair<OddEvenComparable, int>(new OddEvenComparable(2), 7);
pair4 = new Pair<OddEvenComparable, int>(new OddEvenComparable(7), 4);
Assert.IsTrue(pair3.CompareTo(pair4) > 0);
Assert.IsFalse(pair3.Equals(pair4));
Assert.IsFalse(pair3.GetHashCode() == pair4.GetHashCode());
pair3 = new Pair<OddEvenComparable, int>(new OddEvenComparable(8), 0);
pair4 = new Pair<OddEvenComparable, int>(new OddEvenComparable(2), 0);
Assert.IsTrue(pair3.CompareTo(pair4) > 0);
Assert.IsFalse(pair3.Equals(pair4));
Assert.IsFalse(pair3.GetHashCode() == pair4.GetHashCode());
pair3 = new Pair<OddEvenComparable, int>(new OddEvenComparable(2), 4);
pair4 = new Pair<OddEvenComparable, int>(new OddEvenComparable(2), 3);
Assert.IsTrue(pair3.CompareTo(pair4) > 0);
Assert.IsFalse(pair3.Equals(pair4));
Assert.IsFalse(pair3.GetHashCode() == pair4.GetHashCode());
}
[Test]
public void GenericComparable()
{
Pair<int, GOddEvenComparable> pair1, pair2;
pair1 = new Pair<int, GOddEvenComparable>(4, new GOddEvenComparable(7));
pair2 = new Pair<int, GOddEvenComparable>(7, new GOddEvenComparable(3));
Assert.IsTrue(pair1.CompareTo(pair2) < 0);
Assert.IsFalse(pair1.Equals(pair2));
Assert.IsFalse(pair1.GetHashCode() == pair2.GetHashCode());
pair1 = new Pair<int, GOddEvenComparable>(4, new GOddEvenComparable(7));
pair2 = new Pair<int, GOddEvenComparable>(4, new GOddEvenComparable(2));
Assert.IsTrue(pair1.CompareTo(pair2) < 0);
Assert.IsFalse(pair1.Equals(pair2));
Assert.IsFalse(pair1.GetHashCode() == pair2.GetHashCode());
pair1 = new Pair<int, GOddEvenComparable>(4, new GOddEvenComparable(7));
pair2 = new Pair<int, GOddEvenComparable>(4, new GOddEvenComparable(7));
Assert.IsTrue(pair1.CompareTo(pair2) == 0);
Assert.IsTrue(pair1.Equals(pair2));
Assert.IsTrue(pair1.GetHashCode() == pair2.GetHashCode());
pair1 = new Pair<int, GOddEvenComparable>(7, new GOddEvenComparable(7));
pair2 = new Pair<int, GOddEvenComparable>(4, new GOddEvenComparable(2));
Assert.IsTrue(pair1.CompareTo(pair2) > 0);
Assert.IsFalse(pair1.Equals(pair2));
Assert.IsFalse(pair1.GetHashCode() == pair2.GetHashCode());
pair1 = new Pair<int, GOddEvenComparable>(0, new GOddEvenComparable(8));
pair2 = new Pair<int, GOddEvenComparable>(0, new GOddEvenComparable(2));
Assert.IsTrue(pair1.CompareTo(pair2) > 0);
Assert.IsFalse(pair1.Equals(pair2));
Assert.IsFalse(pair1.GetHashCode() == pair2.GetHashCode());
Pair<GOddEvenComparable, int> pair3, pair4;
pair3 = new Pair<GOddEvenComparable, int>(new GOddEvenComparable(7), 4);
pair4 = new Pair<GOddEvenComparable, int>(new GOddEvenComparable(3), 7);
Assert.IsTrue(pair3.CompareTo(pair4) > 0);
Assert.IsFalse(pair3.Equals(pair4));
Assert.IsFalse(pair3.GetHashCode() == pair4.GetHashCode());
pair3 = new Pair<GOddEvenComparable, int>(new GOddEvenComparable(7), 4);
pair4 = new Pair<GOddEvenComparable, int>(new GOddEvenComparable(2), 4);
Assert.IsTrue(pair3.CompareTo(pair4) < 0);
Assert.IsFalse(pair3.Equals(pair4));
Assert.IsFalse(pair3.GetHashCode() == pair4.GetHashCode());
pair3 = new Pair<GOddEvenComparable, int>(new GOddEvenComparable(7), 4);
pair4 = new Pair<GOddEvenComparable, int>(new GOddEvenComparable(7), 4);
Assert.IsTrue(pair3.CompareTo(pair4) == 0);
Assert.IsTrue(pair3.Equals(pair4));
Assert.IsTrue(pair3.GetHashCode() == pair4.GetHashCode());
pair3 = new Pair<GOddEvenComparable, int>(new GOddEvenComparable(2), 7);
pair4 = new Pair<GOddEvenComparable, int>(new GOddEvenComparable(7), 4);
Assert.IsTrue(pair3.CompareTo(pair4) > 0);
Assert.IsFalse(pair3.Equals(pair4));
Assert.IsFalse(pair3.GetHashCode() == pair4.GetHashCode());
pair3 = new Pair<GOddEvenComparable, int>(new GOddEvenComparable(8), 0);
pair4 = new Pair<GOddEvenComparable, int>(new GOddEvenComparable(2), 0);
Assert.IsTrue(pair3.CompareTo(pair4) > 0);
Assert.IsFalse(pair3.Equals(pair4));
Assert.IsFalse(pair3.GetHashCode() == pair4.GetHashCode());
pair3 = new Pair<GOddEvenComparable, int>(new GOddEvenComparable(2), 4);
pair4 = new Pair<GOddEvenComparable, int>(new GOddEvenComparable(2), 3);
Assert.IsTrue(pair3.CompareTo(pair4) > 0);
Assert.IsFalse(pair3.Equals(pair4));
Assert.IsFalse(pair3.GetHashCode() == pair4.GetHashCode());
}
[Test]
public void DictionaryKey()
{
OrderedDictionary<Pair<string, int>, string> dict1 = new OrderedDictionary<Pair<string, int>, string>();
dict1[new Pair<string, int>("foo", 12)] = "hello";
dict1[new Pair<string, int>("zebra", 1)] = "long";
dict1[new Pair<string, int>("zebra", 17)] = "strange";
dict1[new Pair<string, int>("zzz", 14)] = "trip";
dict1[new Pair<string, int>("foo", 16)] = "goodbye";
dict1[new Pair<string, int>("foo", 12)] = "another";
string[] s_array = { "another", "goodbye", "long", "strange", "trip" };
Assert.AreEqual(5, dict1.Count);
int i = 0;
foreach (string s in dict1.Values) {
Assert.AreEqual(s_array[i], s);
++i;
}
}
[Test]
public void IComparable()
{
Pair<int, OddEvenComparable> pair1, pair2;
IComparable comp;
object o;
pair1 = new Pair<int, OddEvenComparable>(4, new OddEvenComparable(7));
pair2 = new Pair<int, OddEvenComparable>(7, new OddEvenComparable(3));
comp = pair1;
o = pair2;
Assert.IsTrue(comp.CompareTo(o) < 0);
pair1 = new Pair<int, OddEvenComparable>(4, new OddEvenComparable(7));
pair2 = new Pair<int, OddEvenComparable>(4, new OddEvenComparable(2));
comp = pair1;
o = pair2;
Assert.IsTrue(comp.CompareTo(o) < 0);
pair1 = new Pair<int, OddEvenComparable>(4, new OddEvenComparable(7));
pair2 = new Pair<int, OddEvenComparable>(4, new OddEvenComparable(7));
comp = pair1;
o = pair2;
Assert.IsTrue(comp.CompareTo(o) == 0);
pair1 = new Pair<int, OddEvenComparable>(7, new OddEvenComparable(7));
pair2 = new Pair<int, OddEvenComparable>(4, new OddEvenComparable(2));
comp = pair1;
o = pair2;
Assert.IsTrue(comp.CompareTo(o) > 0);
try {
int i = comp.CompareTo("foo");
Assert.Fail("should throw");
}
catch (Exception e) {
Assert.IsTrue(e is ArgumentException);
}
}
[Test]
public void FromKeyValuePair()
{
KeyValuePair<int, string> kvp1 = new KeyValuePair<int, string>(-13, "hello");
Pair<int, string> p1 = (Pair<int, string>)kvp1;
Assert.AreEqual(-13, p1.First);
Assert.AreEqual("hello", p1.Second);
Pair<int, string> q1 = new Pair<int, string>(kvp1);
Assert.AreEqual(-13, q1.First);
Assert.AreEqual("hello", q1.Second);
KeyValuePair<string, object> kvp2 = new KeyValuePair<string, object>();
Pair<string, object> p2 = (Pair<string, object>)kvp2;
Assert.IsNull(p2.First);
Assert.IsNull(p2.Second);
Pair<string, object> q2 = new Pair<string,object>(kvp2);
Assert.IsNull(q2.First);
Assert.IsNull(q2.Second);
object x = new Hashtable();
KeyValuePair<object, double> kvp3 = new KeyValuePair<object, double>(x, 6.7);
Pair<object, double> p3 = (Pair<object, double>)kvp3;
Assert.AreSame(x, p3.First);
Assert.AreEqual(6.7, p3.Second);
Pair<object, double> q3 = new Pair<object, double>(kvp3);
Assert.AreSame(x, q3.First);
Assert.AreEqual(6.7, q3.Second);
}
[Test]
public void ToKeyValuePair()
{
Pair<int, string> p1 = new Pair<int, string>(-13, "hello");
KeyValuePair<int, string> kvp1 = (KeyValuePair<int, string>)p1;
Assert.AreEqual(-13, kvp1.Key);
Assert.AreEqual("hello", kvp1.Value);
KeyValuePair<int, string> kv1 = p1.ToKeyValuePair();
Assert.AreEqual(-13, kv1.Key);
Assert.AreEqual("hello", kv1.Value);
Pair<string, object> p2 = new Pair<string, object>();
KeyValuePair<string, object> kvp2 = (KeyValuePair<string, object>)p2;
Assert.IsNull(kvp2.Key);
Assert.IsNull(kvp2.Value);
KeyValuePair<string, object> kv2 = p2.ToKeyValuePair();
Assert.IsNull(kv2.Key);
Assert.IsNull(kv2.Value);
object x = new Hashtable();
Pair<object, double> p3 = new Pair<object, double>(x, 6.7);
KeyValuePair<object, double> kvp3 = (KeyValuePair<object, double>)p3;
Assert.AreSame(x, kvp3.Key);
Assert.AreEqual(6.7, kvp3.Value);
KeyValuePair<object, double> kv3 = p3.ToKeyValuePair();
Assert.AreSame(x, kv3.Key);
Assert.AreEqual(6.7, kv3.Value);
}
[Test]
public void Serialize()
{
Pair<int, string> p1 = new Pair<int, string>(-12, "hello");
Pair<string, double> p2 = new Pair<string, double>("hi", 11);
Pair<int, string> s1 = (Pair<int, string>)InterfaceTests.SerializeRoundTrip(p1);
Pair<string,double> s2 = (Pair<string, double>)InterfaceTests.SerializeRoundTrip(p2);
Assert.AreEqual(p1, s1);
Assert.AreEqual(p2, s2);
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
#region license
/*
DirectShowLib - Provide access to DirectShow interfaces via .NET
Copyright (C) 2006
http://sourceforge.net/projects/directshownet/
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 2.1 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; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#endregion
using System;
using System.Drawing;
using System.Runtime.InteropServices;
namespace DirectShowLib
{
#region Declarations
#if ALLOW_UNTESTED_INTERFACES
/// <summary>
/// From AMDDS_* defines
/// </summary>
[Flags]
public enum DirectDrawSwitches
{
None = 0x00,
DCIPS = 0x01,
PS = 0x02,
RGBOVR = 0x04,
YUVOVR = 0x08,
RGBOFF = 0x10,
YUVOFF = 0x20,
RGBFLP = 0x40,
YUVFLP = 0x80,
All = 0xFF,
YUV = (YUVOFF | YUVOVR | YUVFLP),
RGB = (RGBOFF | RGBOVR | RGBFLP),
Primary = (DCIPS | PS)
}
/// <summary>
/// From AM_PROPERTY_FRAMESTEP
/// </summary>
public enum PropertyFrameStep
{
Step = 0x01,
Cancel = 0x02,
CanStep = 0x03,
CanStepMultiple = 0x04
}
/// <summary>
/// From AM_FRAMESTEP_STEP
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct FrameStepStep
{
public int dwFramesToStep;
}
/// <summary>
/// From MPEG1VIDEOINFO
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct MPEG1VideoInfo
{
public VideoInfoHeader hdr;
public int dwStartTimeCode;
public int cbSequenceHeader;
public byte bSequenceHeader;
}
/// <summary>
/// From ANALOGVIDEOINFO
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct AnalogVideoInfo
{
public Rectangle rcSource;
public Rectangle rcTarget;
public int dwActiveWidth;
public int dwActiveHeight;
public long AvgTimePerFrame;
}
#endif
#endregion
#region Interfaces
#if ALLOW_UNTESTED_INTERFACES
[ComImport,
Guid("36d39eb0-dd75-11ce-bf0e-00aa0055595a"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IDirectDrawVideo
{
[PreserveSig]
int GetSwitches(out int pSwitches);
[PreserveSig]
int SetSwitches(int Switches);
[PreserveSig]
int GetCaps(out IntPtr pCaps); // DDCAPS
[PreserveSig]
int GetEmulatedCaps(out IntPtr pCaps); // DDCAPS
[PreserveSig]
int GetSurfaceDesc(out IntPtr pSurfaceDesc); // DDSURFACEDESC
[PreserveSig]
int GetFourCCCodes(out int pCount,out int pCodes);
[PreserveSig]
int SetDirectDraw(IntPtr pDirectDraw); // LPDIRECTDRAW
[PreserveSig]
int GetDirectDraw(out IntPtr ppDirectDraw); // LPDIRECTDRAW
[PreserveSig]
int GetSurfaceType(out DirectDrawSwitches pSurfaceType);
[PreserveSig]
int SetDefault();
[PreserveSig]
int UseScanLine(int UseScanLine);
[PreserveSig]
int CanUseScanLine(out int UseScanLine);
[PreserveSig]
int UseOverlayStretch(int UseOverlayStretch);
[PreserveSig]
int CanUseOverlayStretch(out int UseOverlayStretch);
[PreserveSig]
int UseWhenFullScreen(int UseWhenFullScreen);
[PreserveSig]
int WillUseFullScreen(out int UseWhenFullScreen);
}
[ComImport,
Guid("dd1d7110-7836-11cf-bf47-00aa0055595a"),
Obsolete("This interface has been deprecated.", false),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IFullScreenVideo
{
[PreserveSig]
int CountModes(out int pModes);
[PreserveSig]
int GetModeInfo(int Mode,out int pWidth,out int pHeight,out int pDepth);
[PreserveSig]
int GetCurrentMode(out int pMode);
[PreserveSig]
int IsModeAvailable(int Mode);
[PreserveSig]
int IsModeEnabled(int Mode);
[PreserveSig]
int SetEnabled(int Mode,int bEnabled);
[PreserveSig]
int GetClipFactor(out int pClipFactor);
[PreserveSig]
int SetClipFactor(int ClipFactor);
[PreserveSig]
int SetMessageDrain(IntPtr hwnd);
[PreserveSig]
int GetMessageDrain(out IntPtr hwnd);
[PreserveSig]
int SetMonitor(int Monitor);
[PreserveSig]
int GetMonitor(out int Monitor);
[PreserveSig]
int HideOnDeactivate(int Hide);
[PreserveSig]
int IsHideOnDeactivate();
[PreserveSig]
int SetCaption([MarshalAs(UnmanagedType.BStr)] string strCaption);
[PreserveSig]
int GetCaption([MarshalAs(UnmanagedType.BStr)] out string pstrCaption);
[PreserveSig]
int SetDefault();
}
[ComImport,
Guid("53479470-f1dd-11cf-bc42-00aa00ac74f6"),
Obsolete("This interface has been deprecated.", false),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IFullScreenVideoEx : IFullScreenVideo
{
#region IFullScreenVideo methods
[PreserveSig]
new int CountModes(out int pModes);
[PreserveSig]
new int GetModeInfo(int Mode, out int pWidth, out int pHeight, out int pDepth);
[PreserveSig]
new int GetCurrentMode(out int pMode);
[PreserveSig]
new int IsModeAvailable(int Mode);
[PreserveSig]
new int IsModeEnabled(int Mode);
[PreserveSig]
new int SetEnabled(int Mode, int bEnabled);
[PreserveSig]
new int GetClipFactor(out int pClipFactor);
[PreserveSig]
new int SetClipFactor(int ClipFactor);
[PreserveSig]
new int SetMessageDrain(IntPtr hwnd);
[PreserveSig]
new int GetMessageDrain(out IntPtr hwnd);
[PreserveSig]
new int SetMonitor(int Monitor);
[PreserveSig]
new int GetMonitor(out int Monitor);
[PreserveSig]
new int HideOnDeactivate(int Hide);
[PreserveSig]
new int IsHideOnDeactivate();
[PreserveSig]
new int SetCaption([MarshalAs(UnmanagedType.BStr)] string strCaption);
[PreserveSig]
new int GetCaption([MarshalAs(UnmanagedType.BStr)] out string pstrCaption);
[PreserveSig]
new int SetDefault();
#endregion
[PreserveSig]
int SetAcceleratorTable(IntPtr hwnd, IntPtr hAccel); // HACCEL
[PreserveSig]
int GetAcceleratorTable(out IntPtr phwnd, out IntPtr phAccel); // HACCEL
[PreserveSig]
int KeepPixelAspectRatio(int KeepAspect);
[PreserveSig]
int IsKeepPixelAspectRatio(out int pKeepAspect);
}
[ComImport,
Guid("61ded640-e912-11ce-a099-00aa00479a58"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IBaseVideoMixer
{
[PreserveSig]
int SetLeadPin(int iPin);
[PreserveSig]
int GetLeadPin(out int piPin);
[PreserveSig]
int GetInputPinCount(out int piPinCount);
[PreserveSig]
int IsUsingClock(out int pbValue);
[PreserveSig]
int SetUsingClock(int bValue);
[PreserveSig]
int GetClockPeriod(out int pbValue);
[PreserveSig]
int SetClockPeriod(int bValue);
}
#endif
[ComImport,
Guid("1bd0ecb0-f8e2-11ce-aac6-0020af0b99a3"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IQualProp
{
[PreserveSig]
int get_FramesDroppedInRenderer(out int pcFrames);
[PreserveSig]
int get_FramesDrawn(out int pcFramesDrawn);
[PreserveSig]
int get_AvgFrameRate(out int piAvgFrameRate);
[PreserveSig]
int get_Jitter(out int iJitter);
[PreserveSig]
int get_AvgSyncOffset(out int piAvg);
[PreserveSig]
int get_DevSyncOffset(out int piDev);
}
#endregion
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoad.Business.ERCLevel
{
/// <summary>
/// D02_Continent (editable child object).<br/>
/// This is a generated base class of <see cref="D02_Continent"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="D03_SubContinentObjects"/> of type <see cref="D03_SubContinentColl"/> (1:M relation to <see cref="D04_SubContinent"/>)<br/>
/// This class is an item of <see cref="D01_ContinentColl"/> collection.
/// </remarks>
[Serializable]
public partial class D02_Continent : BusinessBase<D02_Continent>
{
#region Static Fields
private static int _lastID;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Continent_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> Continent_IDProperty = RegisterProperty<int>(p => p.Continent_ID, "Continents ID");
/// <summary>
/// Gets the Continents ID.
/// </summary>
/// <value>The Continents ID.</value>
public int Continent_ID
{
get { return GetProperty(Continent_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Continent_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Continent_NameProperty = RegisterProperty<string>(p => p.Continent_Name, "Continents Name");
/// <summary>
/// Gets or sets the Continents Name.
/// </summary>
/// <value>The Continents Name.</value>
public string Continent_Name
{
get { return GetProperty(Continent_NameProperty); }
set { SetProperty(Continent_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="D03_Continent_SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<D03_Continent_Child> D03_Continent_SingleObjectProperty = RegisterProperty<D03_Continent_Child>(p => p.D03_Continent_SingleObject, "D03 Continent Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the D03 Continent Single Object ("self load" child property).
/// </summary>
/// <value>The D03 Continent Single Object.</value>
public D03_Continent_Child D03_Continent_SingleObject
{
get { return GetProperty(D03_Continent_SingleObjectProperty); }
private set { LoadProperty(D03_Continent_SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="D03_Continent_ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<D03_Continent_ReChild> D03_Continent_ASingleObjectProperty = RegisterProperty<D03_Continent_ReChild>(p => p.D03_Continent_ASingleObject, "D03 Continent ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the D03 Continent ASingle Object ("self load" child property).
/// </summary>
/// <value>The D03 Continent ASingle Object.</value>
public D03_Continent_ReChild D03_Continent_ASingleObject
{
get { return GetProperty(D03_Continent_ASingleObjectProperty); }
private set { LoadProperty(D03_Continent_ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="D03_SubContinentObjects"/> property.
/// </summary>
public static readonly PropertyInfo<D03_SubContinentColl> D03_SubContinentObjectsProperty = RegisterProperty<D03_SubContinentColl>(p => p.D03_SubContinentObjects, "D03 SubContinent Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the D03 Sub Continent Objects ("self load" child property).
/// </summary>
/// <value>The D03 Sub Continent Objects.</value>
public D03_SubContinentColl D03_SubContinentObjects
{
get { return GetProperty(D03_SubContinentObjectsProperty); }
private set { LoadProperty(D03_SubContinentObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="D02_Continent"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="D02_Continent"/> object.</returns>
internal static D02_Continent NewD02_Continent()
{
return DataPortal.CreateChild<D02_Continent>();
}
/// <summary>
/// Factory method. Loads a <see cref="D02_Continent"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="D02_Continent"/> object.</returns>
internal static D02_Continent GetD02_Continent(SafeDataReader dr)
{
D02_Continent obj = new D02_Continent();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="D02_Continent"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public D02_Continent()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="D02_Continent"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(Continent_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(D03_Continent_SingleObjectProperty, DataPortal.CreateChild<D03_Continent_Child>());
LoadProperty(D03_Continent_ASingleObjectProperty, DataPortal.CreateChild<D03_Continent_ReChild>());
LoadProperty(D03_SubContinentObjectsProperty, DataPortal.CreateChild<D03_SubContinentColl>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="D02_Continent"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Continent_IDProperty, dr.GetInt32("Continent_ID"));
LoadProperty(Continent_NameProperty, dr.GetString("Continent_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Loads child objects.
/// </summary>
internal void FetchChildren()
{
LoadProperty(D03_Continent_SingleObjectProperty, D03_Continent_Child.GetD03_Continent_Child(Continent_ID));
LoadProperty(D03_Continent_ASingleObjectProperty, D03_Continent_ReChild.GetD03_Continent_ReChild(Continent_ID));
LoadProperty(D03_SubContinentObjectsProperty, D03_SubContinentColl.GetD03_SubContinentColl(Continent_ID));
}
/// <summary>
/// Inserts a new <see cref="D02_Continent"/> object in the database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddD02_Continent", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Continent_ID", ReadProperty(Continent_IDProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@Continent_Name", ReadProperty(Continent_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(Continent_IDProperty, (int) cmd.Parameters["@Continent_ID"].Value);
}
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="D02_Continent"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
if (!IsDirty)
return;
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateD02_Continent", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Continent_ID", ReadProperty(Continent_IDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Continent_Name", ReadProperty(Continent_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="D02_Continent"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
// flushes all pending data operations
FieldManager.UpdateChildren(this);
using (var cmd = new SqlCommand("DeleteD02_Continent", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Continent_ID", ReadProperty(Continent_IDProperty)).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
// removes all previous references to children
LoadProperty(D03_Continent_SingleObjectProperty, DataPortal.CreateChild<D03_Continent_Child>());
LoadProperty(D03_Continent_ASingleObjectProperty, DataPortal.CreateChild<D03_Continent_ReChild>());
LoadProperty(D03_SubContinentObjectsProperty, DataPortal.CreateChild<D03_SubContinentColl>());
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
/*
* 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;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using Mono.Addins;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
using OpenSim.Services.Interfaces;
using OpenSim.Services.Connectors.InstantMessage;
using OpenSim.Services.Connectors.Hypergrid;
using OpenSim.Server.Handlers.Hypergrid;
namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HGMessageTransferModule")]
public class HGMessageTransferModule : ISharedRegionModule, IMessageTransferModule, IInstantMessageSimConnector
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected bool m_Enabled = false;
protected List<Scene> m_Scenes = new List<Scene>();
protected IInstantMessage m_IMService;
protected Dictionary<UUID, object> m_UserLocationMap = new Dictionary<UUID, object>();
public event UndeliveredMessage OnUndeliveredMessage;
IUserManagement m_uMan;
IUserManagement UserManagementModule
{
get
{
if (m_uMan == null)
m_uMan = m_Scenes[0].RequestModuleInterface<IUserManagement>();
return m_uMan;
}
}
public virtual void Initialise(IConfigSource config)
{
IConfig cnf = config.Configs["Messaging"];
if (cnf != null && cnf.GetString(
"MessageTransferModule", "MessageTransferModule") != Name)
{
m_log.Debug("[HG MESSAGE TRANSFER]: Disabled by configuration");
return;
}
InstantMessageServerConnector imServer = new InstantMessageServerConnector(config, MainServer.Instance, this);
m_IMService = imServer.GetService();
m_Enabled = true;
}
public virtual void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
lock (m_Scenes)
{
m_log.DebugFormat("[HG MESSAGE TRANSFER]: Message transfer module {0} active", Name);
scene.RegisterModuleInterface<IMessageTransferModule>(this);
m_Scenes.Add(scene);
}
}
public virtual void PostInitialise()
{
if (!m_Enabled)
return;
}
public virtual void RegionLoaded(Scene scene)
{
}
public virtual void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
lock (m_Scenes)
{
m_Scenes.Remove(scene);
}
}
public virtual void Close()
{
}
public virtual string Name
{
get { return "HGMessageTransferModule"; }
}
public virtual Type ReplaceableInterface
{
get { return null; }
}
public void SendInstantMessage(GridInstantMessage im, MessageResultNotification result)
{
UUID toAgentID = new UUID(im.toAgentID);
// Try root avatar only first
foreach (Scene scene in m_Scenes)
{
// m_log.DebugFormat(
// "[HG INSTANT MESSAGE]: Looking for root agent {0} in {1}",
// toAgentID.ToString(), scene.RegionInfo.RegionName);
ScenePresence sp = scene.GetScenePresence(toAgentID);
if (sp != null && !sp.IsChildAgent)
{
// Local message
// m_log.DebugFormat("[HG INSTANT MESSAGE]: Delivering IM to root agent {0} {1}", user.Name, toAgentID);
sp.ControllingClient.SendInstantMessage(im);
// Message sent
result(true);
return;
}
}
// try child avatar second
foreach (Scene scene in m_Scenes)
{
// m_log.DebugFormat(
// "[HG INSTANT MESSAGE]: Looking for child of {0} in {1}",
// toAgentID, scene.RegionInfo.RegionName);
ScenePresence sp = scene.GetScenePresence(toAgentID);
if (sp != null)
{
// Local message
// m_log.DebugFormat("[HG INSTANT MESSAGE]: Delivering IM to child agent {0} {1}", user.Name, toAgentID);
sp.ControllingClient.SendInstantMessage(im);
// Message sent
result(true);
return;
}
}
// m_log.DebugFormat("[HG INSTANT MESSAGE]: Delivering IM to {0} via XMLRPC", im.toAgentID);
// Is the user a local user?
string url = string.Empty;
bool foreigner = false;
if (UserManagementModule != null && !UserManagementModule.IsLocalGridUser(toAgentID)) // foreign user
{
url = UserManagementModule.GetUserServerURL(toAgentID, "IMServerURI");
foreigner = true;
}
Util.FireAndForget(delegate
{
bool success = false;
if (foreigner && url == string.Empty) // we don't know about this user
{
string recipientUUI = TryGetRecipientUUI(new UUID(im.fromAgentID), toAgentID);
m_log.DebugFormat("[HG MESSAGE TRANSFER]: Got UUI {0}", recipientUUI);
if (recipientUUI != string.Empty)
{
UUID id; string u = string.Empty, first = string.Empty, last = string.Empty, secret = string.Empty;
if (Util.ParseUniversalUserIdentifier(recipientUUI, out id, out u, out first, out last, out secret))
{
success = m_IMService.OutgoingInstantMessage(im, u, true);
if (success)
UserManagementModule.AddUser(toAgentID, u + ";" + first + " " + last);
}
}
}
else
success = m_IMService.OutgoingInstantMessage(im, url, foreigner);
if (!success && !foreigner)
HandleUndeliverableMessage(im, result);
else
result(success);
}, null, "HGMessageTransferModule.SendInstantMessage");
return;
}
protected bool SendIMToScene(GridInstantMessage gim, UUID toAgentID)
{
bool successful = false;
foreach (Scene scene in m_Scenes)
{
ScenePresence sp = scene.GetScenePresence(toAgentID);
if(sp != null && !sp.IsChildAgent)
{
scene.EventManager.TriggerIncomingInstantMessage(gim);
successful = true;
}
}
if (!successful)
{
// If the message can't be delivered to an agent, it
// is likely to be a group IM. On a group IM, the
// imSessionID = toAgentID = group id. Raise the
// unhandled IM event to give the groups module
// a chance to pick it up. We raise that in a random
// scene, since the groups module is shared.
//
m_Scenes[0].EventManager.TriggerUnhandledInstantMessage(gim);
}
return successful;
}
public void HandleUndeliverableMessage(GridInstantMessage im, MessageResultNotification result)
{
UndeliveredMessage handlerUndeliveredMessage = OnUndeliveredMessage;
// If this event has handlers, then an IM from an agent will be
// considered delivered. This will suppress the error message.
//
if (handlerUndeliveredMessage != null)
{
handlerUndeliveredMessage(im);
if (im.dialog == (byte)InstantMessageDialog.MessageFromAgent)
result(true);
else
result(false);
return;
}
//m_log.DebugFormat("[INSTANT MESSAGE]: Undeliverable");
result(false);
}
private string TryGetRecipientUUI(UUID fromAgent, UUID toAgent)
{
// Let's call back the fromAgent's user agent service
// Maybe that service knows about the toAgent
IClientAPI client = LocateClientObject(fromAgent);
if (client != null)
{
AgentCircuitData circuit = m_Scenes[0].AuthenticateHandler.GetAgentCircuitData(client.AgentId);
if (circuit != null)
{
if (circuit.ServiceURLs.ContainsKey("HomeURI"))
{
string uasURL = circuit.ServiceURLs["HomeURI"].ToString();
m_log.DebugFormat("[HG MESSAGE TRANSFER]: getting UUI of user {0} from {1}", toAgent, uasURL);
UserAgentServiceConnector uasConn = new UserAgentServiceConnector(uasURL);
string agentUUI = string.Empty;
try
{
agentUUI = uasConn.GetUUI(fromAgent, toAgent);
}
catch (Exception e) {
m_log.Debug("[HG MESSAGE TRANSFER]: GetUUI call failed ", e);
}
return agentUUI;
}
}
}
return string.Empty;
}
/// <summary>
/// Find the root client for a ID
/// </summary>
public IClientAPI LocateClientObject(UUID agentID)
{
lock (m_Scenes)
{
foreach (Scene scene in m_Scenes)
{
ScenePresence presence = scene.GetScenePresence(agentID);
if (presence != null && !presence.IsChildAgent)
return presence.ControllingClient;
}
}
return null;
}
#region IInstantMessageSimConnector
public bool SendInstantMessage(GridInstantMessage im)
{
//m_log.DebugFormat("[XXX] Hook SendInstantMessage {0}", im.message);
UUID agentID = new UUID(im.toAgentID);
return SendIMToScene(im, agentID);
}
#endregion
}
}
| |
//-----------------------------------------------------------------------
//
// Microsoft Windows Client Platform
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// File: Classification.cs
//
// Contents: Unicode classification entry point
//
// Created: 7-14-2002 Tarek Mahmoud Sayed ([....])
//
//------------------------------------------------------------------------
using System;
using System.Diagnostics;
using MS.Internal;
using System.Windows;
using System.Security;
using System.Collections;
using System.Runtime.InteropServices;
using System.Windows.Media.TextFormatting;
using MS.Internal.PresentationCore;
namespace MS.Internal
{
/// <summary>
/// This class is used as a level on indirection for classes in managed c++ to be able to utilize methods
/// from the static class Classification.
/// We cannot make MC++ reference PresentationCore.dll since this will result in cirular reference.
/// </summary>
internal class ClassificationUtility : MS.Internal.Text.TextInterface.IClassification
{
// We have restored this list from WPF 3.x.
// The original list can be found under
// $/Dev10/pu/WPF/wpf/src/Core/CSharp/MS/Internal/Shaping/Script.cs
internal static readonly bool[] ScriptCaretInfo = new bool[]
{
/* Default */ false,
/* Arabic */ false,
/* Armenian */ false,
/* Bengali */ true,
/* Bopomofo */ false,
/* Braille */ false,
/* Buginese */ true,
/* Buhid */ false,
/* CanadianSyllabics */ false,
/* Cherokee */ false,
/* CJKIdeographic */ false,
/* Coptic */ false,
/* CypriotSyllabary */ false,
/* Cyrillic */ false,
/* Deseret */ false,
/* Devanagari */ true,
/* Ethiopic */ false,
/* Georgian */ false,
/* Glagolitic */ false,
/* Gothic */ false,
/* Greek */ false,
/* Gujarati */ true,
/* Gurmukhi */ true,
/* Hangul */ true,
/* Hanunoo */ false,
/* Hebrew */ true,
/* Kannada */ true,
/* Kana */ false,
/* Kharoshthi */ true,
/* Khmer */ true,
/* Lao */ true,
/* Latin */ false,
/* Limbu */ true,
/* LinearB */ false,
/* Malayalam */ true,
/* MathematicalAlphanumericSymbols */ false,
/* Mongolian */ true,
/* MusicalSymbols */ false,
/* Myanmar */ true,
/* NewTaiLue */ true,
/* Ogham */ false,
/* OldItalic */ false,
/* OldPersianCuneiform */ false,
/* Oriya */ true,
/* Osmanya */ false,
/* Runic */ false,
/* Shavian */ false,
/* Sinhala */ true,
/* SylotiNagri */ true,
/* Syriac */ false,
/* Tagalog */ false,
/* Tagbanwa */ false,
/* TaiLe */ false,
/* Tamil */ true,
/* Telugu */ true,
/* Thaana */ true,
/* Thai */ true,
/* Tibetan */ true,
/* Tifinagh */ false,
/* UgariticCuneiform */ false,
/* Yi */ false,
/* Digit */ false,
/* Control */ false,
/* Mirror */ false,
};
static private ClassificationUtility _classificationUtilityInstance = new ClassificationUtility();
static internal ClassificationUtility Instance
{
get
{
return _classificationUtilityInstance;
}
}
public void GetCharAttribute(
int unicodeScalar,
out bool isCombining,
out bool needsCaretInfo,
out bool isIndic,
out bool isDigit,
out bool isLatin,
out bool isStrong
)
{
CharacterAttribute charAttribute = Classification.CharAttributeOf((int)Classification.GetUnicodeClass(unicodeScalar));
byte itemClass = charAttribute.ItemClass;
isCombining = (itemClass == (byte)ItemClass.SimpleMarkClass
|| itemClass == (byte)ItemClass.ComplexMarkClass
|| Classification.IsIVS(unicodeScalar));
isStrong = (itemClass == (byte)ItemClass.StrongClass);
int script = charAttribute.Script;
needsCaretInfo = ScriptCaretInfo[script];
ScriptID scriptId = (ScriptID)script;
isDigit = scriptId == ScriptID.Digit;
isLatin = scriptId == ScriptID.Latin;
if (isLatin)
{
isIndic = false;
}
else
{
isIndic = IsScriptIndic(scriptId);
}
}
/// <summary>
/// Returns true if specified script is Indic.
/// </summary>
private static bool IsScriptIndic(ScriptID scriptId)
{
if (scriptId == ScriptID.Bengali
|| scriptId == ScriptID.Devanagari
|| scriptId == ScriptID.Gurmukhi
|| scriptId == ScriptID.Gujarati
|| scriptId == ScriptID.Kannada
|| scriptId == ScriptID.Malayalam
|| scriptId == ScriptID.Oriya
|| scriptId == ScriptID.Tamil
|| scriptId == ScriptID.Telugu)
{
return true;
}
else
{
return false;
}
}
}
/// <summary>
/// Hold the classification table pointers.
/// </summary>
internal static class Classification
{
/// <summary>
/// This structure has a cloned one in the unmanaged side. Doing any change in this
/// structure should have the same change on unmanaged side too.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct CombiningMarksClassificationData
{
internal IntPtr CombiningCharsIndexes; // Two dimentional array of base char classes,
internal int CombiningCharsIndexesTableLength;
internal int CombiningCharsIndexesTableSegmentLength;
internal IntPtr CombiningMarkIndexes; // Combining mark classes array, with length = length
internal int CombiningMarkIndexesTableLength;
internal IntPtr CombinationChars; // Two dimentional array of combined characters
internal int CombinationCharsBaseCount;
internal int CombinationCharsMarkCount;
}
/// <summary>
/// This structure has a cloned one in the unmanaged side. doing any change in that
/// structure should have same change in the unmanaged side too.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct RawClassificationTables
{
internal IntPtr UnicodeClasses;
internal IntPtr CharacterAttributes;
internal IntPtr Mirroring;
internal CombiningMarksClassificationData CombiningMarksClassification;
};
///<SecurityNote>
/// Critical - as this code performs an elevation.
///</SecurityNote>
[SecurityCritical]
[SuppressUnmanagedCodeSecurity]
[DllImport(DllImport.PresentationNative, EntryPoint="MILGetClassificationTables")]
internal static extern void MILGetClassificationTables(out RawClassificationTables ct);
/// <SecurityNote>
/// Critical: This accesses unsafe code and retrieves pointers that it stores locally
/// The pointers retrieved are not validated for correctness and they are later dereferenced.
/// TreatAsSafe: The constructor is safe since it simply stores these pointers. The risk here
/// in the future is not of these pointers being spoofed since they are not settable from outside.
/// </SecurityNote>
[SecurityCritical,SecurityTreatAsSafe]
static Classification()
{
unsafe
{
RawClassificationTables ct = new RawClassificationTables();
MILGetClassificationTables(out ct);
_unicodeClassTable = new SecurityCriticalData<IntPtr>(ct.UnicodeClasses);
_charAttributeTable = new SecurityCriticalData<IntPtr>(ct.CharacterAttributes);
_mirroredCharTable = new SecurityCriticalData<IntPtr>(ct.Mirroring);
_combiningMarksClassification = new SecurityCriticalData<CombiningMarksClassificationData>(ct.CombiningMarksClassification);
}
}
/// <summary>
/// Lookup Unicode character class for a Unicode UTF16 value
/// </summary>
/// <SecurityNote>
/// Critical: This accesses unsafe code and dereferences a location in
/// a prepopulated Array. The risk is you might derefence a bogus memory
/// location.
/// TreatAsSafe: This code is ok since it reduces codepoint to one of 256 possible
/// values and will always succeed. Also this information is ok to expose.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
static public short GetUnicodeClassUTF16(char codepoint)
{
unsafe
{
short **plane0 = UnicodeClassTable[0];
Invariant.Assert((long)plane0 >= (long)UnicodeClass.Max);
short* pcc = plane0[codepoint >> 8];
return ((long) pcc < (long) UnicodeClass.Max ?
(short)pcc : pcc[codepoint & 0xFF]);
}
}
/// <summary>
/// Lookup Unicode character class for a Unicode scalar value
/// </summary>
/// <SecurityNote>
/// Critical: This accesses unsafe code and derefences a pointer retrieved from unmanaged code
/// TreatAsSafe: There is bounds checking in place and this dereferences a valid structure which
/// is guaranteed to be populated
/// </SecurityNote>
[SecurityCritical,SecurityTreatAsSafe]
static public short GetUnicodeClass(int unicodeScalar)
{
unsafe
{
Invariant.Assert(unicodeScalar >= 0 && unicodeScalar <= 0x10FFFF);
short **ppcc = UnicodeClassTable[((unicodeScalar >> 16) & 0xFF) % 17];
if ((long)ppcc < (long)UnicodeClass.Max)
return (short)ppcc;
short *pcc = ppcc[(unicodeScalar & 0xFFFF) >> 8];
if ((long)pcc < (long)UnicodeClass.Max)
return (short)pcc;
return pcc[unicodeScalar & 0xFF];
}
}
/// <summary>
/// Compute Unicode scalar value from unicode codepoint stream
/// </summary>
static internal int UnicodeScalar(
CharacterBufferRange unicodeString,
out int sizeofChar
)
{
Invariant.Assert(unicodeString.CharacterBuffer != null && unicodeString.Length > 0);
int ch = unicodeString[0];
sizeofChar = 1;
if ( unicodeString.Length >= 2
&& (ch & 0xFC00) == 0xD800
&& (unicodeString[1] & 0xFC00) == 0xDC00
)
{
ch = (((ch & 0x03FF) << 10) | (unicodeString[1] & 0x3FF)) + 0x10000;
sizeofChar++;
}
return ch;
}
/// <summary>
/// Check whether the character is combining mark
/// </summary>
/// <SecurityNote>
/// Critical: This code acceses a function call that returns a pointer (get_CharAttributeTable).
/// It trusts the value passed in to derfence the table with no implicit bounds or validity checks.
/// TreatAsSafe: This information is safe to expose at the same time the unicodeScalar passed in
/// is validated for bounds
/// </SecurityNote>
[SecurityCritical,SecurityTreatAsSafe]
static public bool IsCombining(int unicodeScalar)
{
unsafe
{
byte itemClass = Classification.CharAttributeTable[GetUnicodeClass(unicodeScalar)].ItemClass;
return itemClass == (byte)ItemClass.SimpleMarkClass
|| itemClass == (byte)ItemClass.ComplexMarkClass
|| IsIVS(unicodeScalar);
}
}
/// <summary>
/// Check whether the character is a joiner character
/// </summary>
/// <SecurityNote>
/// Critical: This code acceses a function call that returns a pointer (get_CharAttributeTable).
/// It trusts the value passed in to derfence the table with no implicit bounds or validity checks.
/// TreatAsSafe: This information is safe to expose at the same time the unicodeScalar passed in
/// is validated for bounds
/// </SecurityNote>
[SecurityCritical,SecurityTreatAsSafe]
static public bool IsJoiner(int unicodeScalar)
{
unsafe
{
byte itemClass = Classification.CharAttributeTable[GetUnicodeClass(unicodeScalar)].ItemClass;
return itemClass == (byte) ItemClass.JoinerClass;
}
}
/// <summary>
/// Check whether the character is an IVS selector character
/// </summary>
static public bool IsIVS(int unicodeScalar)
{
// An Ideographic Variation Sequence (IVS) is a sequence of two
// coded characters, the first being a character with the
// Unified_Ideograph property, the second being a variation
// selector character in the range U+E0100 to U+E01EF.
return unicodeScalar >= 0xE0100 && unicodeScalar <= 0xE01EF;
}
/// <summary>
/// Scan UTF16 character string until a character with specified attributes is found
/// </summary>
/// <returns>character index of first character matching the attribute.</returns>
/// <SecurityNote>
/// Critical: This code acceses a function call that returns a pointer (get_CharAttributeTable).
/// It keeps accesing a buffer with no validation in terms of the variables passed in.
/// TreatAsSafe: This information is safe to expose, as in the worst case it tells you information
/// of where the next UTF16 character is. Also the constructor for characterbuffer can be one of three
/// a string, a char array or an unmanaged char*. The third case is critical and tightly controlled
/// so the risk of bogus length is significantly mitigated.
/// </SecurityNote>
[SecurityCritical,SecurityTreatAsSafe]
static public int AdvanceUntilUTF16(
CharacterBuffer charBuffer,
int offsetToFirstChar,
int stringLength,
ushort mask,
out ushort charFlags
)
{
int i = offsetToFirstChar;
int limit = offsetToFirstChar + stringLength;
charFlags = 0;
while (i < limit)
{
unsafe
{
ushort flags = (ushort)Classification.CharAttributeTable[(int)GetUnicodeClassUTF16(charBuffer[i])].Flags;
if((flags & mask) != 0)
break;
charFlags |= flags;
}
i++;
}
return i - offsetToFirstChar;
}
/// <summary>
/// Scan character string until a character that is not the specified ItemClass is found
/// </summary>
/// <returns>character index of first character that is not the specified ItemClass</returns>
/// <SecurityNote>
/// Critical: This code acceses a function call that returns a pointer (get_CharAttributeTable). It acceses
/// elements in an array with no type checking.
/// TreatAsSafe: This code exposes the index of the next non UTF16 character in a run. This is ok to expose
/// Also the calls to CharBuffer and CahrAttribute do the requisite bounds checking.
/// </SecurityNote>
[SecurityCritical,SecurityTreatAsSafe]
static public int AdvanceWhile(
CharacterBufferRange unicodeString,
ItemClass itemClass
)
{
int i = 0;
int limit = unicodeString.Length;
int sizeofChar = 0;
while (i < limit)
{
int ch = Classification.UnicodeScalar(
new CharacterBufferRange(unicodeString, i, limit - i),
out sizeofChar
);
unsafe
{
byte currentClass = (byte) Classification.CharAttributeTable[(int)GetUnicodeClass(ch)].ItemClass;
if (currentClass != (byte) itemClass)
break;
}
i += sizeofChar;
}
return i;
}
/// <SecurityNote>
/// Critical: This accesses unsafe code and returns a pointer
/// </SecurityNote>
private static unsafe short*** UnicodeClassTable
{
[SecurityCritical]
get { return (short***)_unicodeClassTable.Value; }
}
/// <SecurityNote>
/// Critical: This accesses unsafe code and returns a pointer
/// </SecurityNote>
private static unsafe CharacterAttribute* CharAttributeTable
{
[SecurityCritical]
get { return (CharacterAttribute*)_charAttributeTable.Value; }
}
/// <SecurityNote>
/// Critical: This accesses unsafe code and indexes into an array
/// Safe : This method does bound check on the input char class.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
internal static CharacterAttribute CharAttributeOf(int charClass)
{
unsafe
{
Invariant.Assert(charClass >= 0 && charClass < (int) UnicodeClass.Max);
return CharAttributeTable[charClass];
}
}
static private readonly SecurityCriticalData<IntPtr> _unicodeClassTable;
static private readonly SecurityCriticalData<IntPtr> _charAttributeTable;
static private readonly SecurityCriticalData<IntPtr> _mirroredCharTable;
static private readonly SecurityCriticalData<CombiningMarksClassificationData> _combiningMarksClassification;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.