context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// 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 sys = System; namespace Google.Cloud.OsConfig.V1 { /// <summary>Resource name for the <c>Instance</c> resource.</summary> public sealed partial class InstanceName : gax::IResourceName, sys::IEquatable<InstanceName> { /// <summary>The possible contents of <see cref="InstanceName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/zones/{zone}/instances/{instance}</c>. /// </summary> ProjectZoneInstance = 1, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/instances/{instance}</c>. /// </summary> ProjectLocationInstance = 2, } private static gax::PathTemplate s_projectZoneInstance = new gax::PathTemplate("projects/{project}/zones/{zone}/instances/{instance}"); private static gax::PathTemplate s_projectLocationInstance = new gax::PathTemplate("projects/{project}/locations/{location}/instances/{instance}"); /// <summary>Creates a <see cref="InstanceName"/> 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="InstanceName"/> containing the provided <paramref name="unparsedResourceName"/> /// . /// </returns> public static InstanceName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new InstanceName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="InstanceName"/> with the pattern /// <c>projects/{project}/zones/{zone}/instances/{instance}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="zoneId">The <c>Zone</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="InstanceName"/> constructed from the provided ids.</returns> public static InstanceName FromProjectZoneInstance(string projectId, string zoneId, string instanceId) => new InstanceName(ResourceNameType.ProjectZoneInstance, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), zoneId: gax::GaxPreconditions.CheckNotNullOrEmpty(zoneId, nameof(zoneId)), instanceId: gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId))); /// <summary> /// Creates a <see cref="InstanceName"/> with the pattern /// <c>projects/{project}/locations/{location}/instances/{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="InstanceName"/> constructed from the provided ids.</returns> public static InstanceName FromProjectLocationInstance(string projectId, string locationId, string instanceId) => new InstanceName(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="InstanceName"/> with pattern /// <c>projects/{project}/zones/{zone}/instances/{instance}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="zoneId">The <c>Zone</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="InstanceName"/> with pattern /// <c>projects/{project}/zones/{zone}/instances/{instance}</c>. /// </returns> public static string Format(string projectId, string zoneId, string instanceId) => FormatProjectZoneInstance(projectId, zoneId, instanceId); /// <summary> /// Formats the IDs into the string representation of this <see cref="InstanceName"/> with pattern /// <c>projects/{project}/zones/{zone}/instances/{instance}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="zoneId">The <c>Zone</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="InstanceName"/> with pattern /// <c>projects/{project}/zones/{zone}/instances/{instance}</c>. /// </returns> public static string FormatProjectZoneInstance(string projectId, string zoneId, string instanceId) => s_projectZoneInstance.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(zoneId, nameof(zoneId)), gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="InstanceName"/> with pattern /// <c>projects/{project}/locations/{location}/instances/{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="InstanceName"/> with pattern /// <c>projects/{project}/locations/{location}/instances/{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="InstanceName"/> 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}/zones/{zone}/instances/{instance}</c></description></item> /// <item><description><c>projects/{project}/locations/{location}/instances/{instance}</c></description></item> /// </list> /// </remarks> /// <param name="instanceName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="InstanceName"/> if successful.</returns> public static InstanceName Parse(string instanceName) => Parse(instanceName, false); /// <summary> /// Parses the given resource name string into a new <see cref="InstanceName"/> 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}/zones/{zone}/instances/{instance}</c></description></item> /// <item><description><c>projects/{project}/locations/{location}/instances/{instance}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="instanceName">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="InstanceName"/> if successful.</returns> public static InstanceName Parse(string instanceName, bool allowUnparsed) => TryParse(instanceName, allowUnparsed, out InstanceName 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="InstanceName"/> 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}/zones/{zone}/instances/{instance}</c></description></item> /// <item><description><c>projects/{project}/locations/{location}/instances/{instance}</c></description></item> /// </list> /// </remarks> /// <param name="instanceName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="InstanceName"/>, 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 instanceName, out InstanceName result) => TryParse(instanceName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="InstanceName"/> 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}/zones/{zone}/instances/{instance}</c></description></item> /// <item><description><c>projects/{project}/locations/{location}/instances/{instance}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="instanceName">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="InstanceName"/>, 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 instanceName, bool allowUnparsed, out InstanceName result) { gax::GaxPreconditions.CheckNotNull(instanceName, nameof(instanceName)); gax::TemplatedResourceName resourceName; if (s_projectZoneInstance.TryParseName(instanceName, out resourceName)) { result = FromProjectZoneInstance(resourceName[0], resourceName[1], resourceName[2]); return true; } if (s_projectLocationInstance.TryParseName(instanceName, out resourceName)) { result = FromProjectLocationInstance(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(instanceName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private InstanceName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string instanceId = null, string locationId = null, string projectId = null, string zoneId = null) { Type = type; UnparsedResource = unparsedResourceName; InstanceId = instanceId; LocationId = locationId; ProjectId = projectId; ZoneId = zoneId; } /// <summary> /// Constructs a new instance of a <see cref="InstanceName"/> class from the component parts of pattern /// <c>projects/{project}/zones/{zone}/instances/{instance}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="zoneId">The <c>Zone</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 InstanceName(string projectId, string zoneId, string instanceId) : this(ResourceNameType.ProjectZoneInstance, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), zoneId: gax::GaxPreconditions.CheckNotNullOrEmpty(zoneId, nameof(zoneId)), 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. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string InstanceId { get; } /// <summary> /// The <c>Location</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Zone</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string ZoneId { 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.ProjectZoneInstance: return s_projectZoneInstance.Expand(ProjectId, ZoneId, InstanceId); 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 InstanceName); /// <inheritdoc/> public bool Equals(InstanceName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(InstanceName a, InstanceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(InstanceName a, InstanceName b) => !(a == b); } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Data; using System.Configuration; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using WebsitePanel.EnterpriseServer; namespace WebsitePanel.Portal { public partial class ServersEditService : WebsitePanelModuleBase { ServiceInfo service = null; ProviderInfo provider = null; ResourceGroupInfo resourceGroup = null; protected void Page_Load(object sender, EventArgs e) { try { // load service settings control LoadService(); LoadSettingsControl(); rowInstallResults.Visible = false; if (!IsPostBack) { BindClusters(); BindService(); BindServiceProperties(); BindServiceQuota(); ToggleGlobalDNS(); } } catch (Exception ex) { ShowErrorMessage("SERVER_GET_SERVICE", ex); return; } } private void LoadService() { service = ES.Services.Servers.GetServiceInfo(PanelRequest.ServiceId); if (service == null) // return RedirectBack(); // load provider details provider = ES.Services.Servers.GetProvider(service.ProviderId); // load resource group details resourceGroup = ES.Services.Servers.GetResourceGroup(provider.GroupId); } private void BindService() { litGroup.Text = PanelFormatter.GetLocalizedResourceGroupName(resourceGroup.GroupName); litProvider.Text = provider.DisplayName; txtServiceName.Text = service.ServiceName; txtQuotaValue.Text = service.ServiceQuotaValue.ToString(); Utils.SelectListItem(ddlClusters, service.ClusterId); txtComments.Text = service.Comments; } private void BindServiceQuota() { QuotaInfo quota = ES.Services.Servers.GetProviderServiceQuota(provider.ProviderId); if (quota != null) { lblQuotaName.Text = GetSharedLocalizedString(Utils.ModuleName, "Quota." + quota.QuotaName); } else { pnlQuota.Visible = false; } } private void LoadSettingsControl() { try { // try to locate suitable control string currPath = this.AppRelativeVirtualPath; currPath = currPath.Substring(0, currPath.LastIndexOf("/")); string ctrlPath = currPath + "/ProviderControls/" + provider.EditorControl + "_Settings.ascx"; IHostingServiceProviderSettings ctrl = (IHostingServiceProviderSettings)Page.LoadControl(ctrlPath); // add control to the placeholder serviceProps.Controls.Add((Control)ctrl); } catch (Exception ex) { ShowErrorMessage("SERVER_LOAD_SERVICE_CONTROL", ex); return; } } private void BindServiceProperties() { // find control IHostingServiceProviderSettings ctrl = serviceProps.Controls[0] as IHostingServiceProviderSettings; if (ctrl == null) return; // load service properties and bind them string[] settings = ES.Services.Servers.GetServiceSettings(PanelRequest.ServiceId); // bind ctrl.BindSettings(ConvertArrayToDictionary(settings)); } private void ToggleGlobalDNS() { DnsRecrodsPanel.Visible = DnsRecrodsHeader.Visible = ((resourceGroup.GroupName == ResourceGroups.BlackBerry) | (resourceGroup.GroupName == ResourceGroups.OCS)| (resourceGroup.GroupName == ResourceGroups.HostedCRM)| (resourceGroup.GroupName == ResourceGroups.Os)| (resourceGroup.GroupName == ResourceGroups.HostedOrganizations) | (resourceGroup.GroupName == ResourceGroups.SharepointFoundationServer) | (resourceGroup.GroupName == ResourceGroups.SharepointEnterpriseServer) | (resourceGroup.GroupName == ResourceGroups.Mail)| (resourceGroup.GroupName == ResourceGroups.Lync)| (resourceGroup.GroupName == ResourceGroups.Exchange)| (resourceGroup.GroupName == ResourceGroups.Web)| (resourceGroup.GroupName == ResourceGroups.Dns)| (resourceGroup.GroupName == ResourceGroups.Ftp)| (resourceGroup.GroupName == ResourceGroups.MsSql2000)| (resourceGroup.GroupName == ResourceGroups.MsSql2005)| (resourceGroup.GroupName == ResourceGroups.MsSql2008)| (resourceGroup.GroupName == ResourceGroups.MsSql2012) | (resourceGroup.GroupName == ResourceGroups.MsSql2014) | (resourceGroup.GroupName == ResourceGroups.MySql4)| (resourceGroup.GroupName == ResourceGroups.MySql5)| (resourceGroup.GroupName == ResourceGroups.Statistics)| (resourceGroup.GroupName == ResourceGroups.VPS)| (resourceGroup.GroupName == ResourceGroups.VPS2012)| (resourceGroup.GroupName == ResourceGroups.VPSForPC)); } private void SaveServiceProperties() { // find control try { IHostingServiceProviderSettings ctrl = serviceProps.Controls[0] as IHostingServiceProviderSettings; if (ctrl == null) return; // grab settings StringDictionary settings = new StringDictionary(); ctrl.SaveSettings(settings); // save settings int result = ES.Services.Servers.UpdateServiceSettings(PanelRequest.ServiceId, ConvertDictionaryToArray(settings)); if (result < 0) { ShowResultMessage(result); return; } } catch (Exception ex) { ShowErrorMessage("SERVER_UPDATE_SERVICE_PROPS", ex); return; } } protected void btnUpdate_Click(object sender, EventArgs e) { // validate input if (!Page.IsValid) return; service = new ServiceInfo(); service.ServiceId = PanelRequest.ServiceId; service.ServiceName = txtServiceName.Text.Trim(); service.ServiceQuotaValue = Utils.ParseInt(txtQuotaValue.Text, 0); service.ClusterId = Utils.ParseInt(ddlClusters.SelectedValue, 0); service.Comments = txtComments.Text; // update service try { int result = ES.Services.Servers.UpdateService(service); if (result < 0) { ShowResultMessage(result); return; } } catch (Exception ex) { ShowErrorMessage("SERVER_UPDATE_SERVICE", ex); return; } // save properties SaveServiceProperties(); // install service string[] installResults = null; try { installResults = ES.Services.Servers.InstallService(PanelRequest.ServiceId); } catch (Exception ex) { ShowErrorMessage("SERVER_INSTALL_SERVICE", ex); return; } // check results if (installResults != null && installResults.Length > 0) { rowInstallResults.Visible = true; blInstallResults.Items.Clear(); foreach (string installResult in installResults) blInstallResults.Items.Add(installResult); return; } // save quotas //SaveServiceQuotas(); // return RedirectBack(); } protected void btnCancel_Click(object sender, EventArgs e) { // return RedirectBack(); } protected void btnDelete_Click(object sender, EventArgs e) { if (PanelRequest.ServiceId != 0) { // delete service try { int result = ES.Services.Servers.DeleteService(PanelRequest.ServiceId); if (result < 0) { ShowResultMessage(result); return; } } catch (Exception ex) { ShowErrorMessage("SERVER_DELETE_SERVICE", ex); return; } } // return RedirectBack(); } private void RedirectBack() { // redirect to the previous page Response.Redirect(EditUrl("ServerID", PanelRequest.ServerId.ToString(), "edit_server")); } #region Cluster methods private void BindClusters() { try { ddlClusters.DataSource = ES.Services.Servers.GetClusters(); ddlClusters.DataBind(); ddlClusters.Items.Insert(0, new ListItem("<Not Included>", "")); } catch (Exception ex) { ShowErrorMessage("SERVER_GET_CLUSTER", ex); return; } } protected void cmdAddCluster_Click(object sender, EventArgs e) { ClusterInfo cluster = new ClusterInfo(); cluster.ClusterName = txtClusterName.Text.Trim(); try { int result = ES.Services.Servers.AddCluster(cluster); if (result < 0) { ShowResultMessage(result); return; } } catch (Exception ex) { ShowErrorMessage("SERVER_ADD_CLUSTER", ex); return; } // rebind BindClusters(); txtClusterName.Text = ""; } protected void cmdDeleteCluster_Click(object sender, EventArgs e) { try { int result = ES.Services.Servers.DeleteCluster(Utils.ParseInt(ddlClusters.SelectedValue, 0)); if (result < 0) { ShowResultMessage(result); return; } } catch (Exception ex) { ShowErrorMessage("SERVER_DELETE_CLUSTER", ex); return; } // rebind BindClusters(); } #endregion #region Helper methods private string[] ConvertDictionaryToArray(StringDictionary settings) { List<string> r = new List<string>(); foreach (string key in settings.Keys) r.Add(key + "=" + settings[key]); return r.ToArray(); } private StringDictionary ConvertArrayToDictionary(string[] settings) { StringDictionary r = new StringDictionary(); foreach (string setting in settings) { int idx = setting.IndexOf('='); r.Add(setting.Substring(0, idx), setting.Substring(idx + 1)); } return r; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.ApplicationParts; using Microsoft.AspNetCore.Mvc.Razor.Compilation; using Microsoft.AspNetCore.Mvc.Razor.Extensions; using Microsoft.AspNetCore.Razor.Hosting; using Microsoft.AspNetCore.Razor.Language; using Microsoft.CodeAnalysis.Emit; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Moq; using Xunit; using static Microsoft.AspNetCore.Razor.Hosting.TestRazorCompiledItem; namespace Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation { public class RuntimeViewCompilerTest { [Fact] public async Task CompileAsync_ReturnsResultWithNullAttribute_IfFileIsNotFoundInFileSystem() { // Arrange var path = "/file/does-not-exist"; var fileProvider = new TestFileProvider(); var viewCompiler = GetViewCompiler(fileProvider); // Act var result1 = await viewCompiler.CompileAsync(path); var result2 = await viewCompiler.CompileAsync(path); // Assert Assert.Same(result1, result2); Assert.Null(result1.Item); var token = Assert.Single(result1.ExpirationTokens); Assert.Same(fileProvider.GetChangeToken(path), token); } [Fact] public async Task CompileAsync_ReturnsResultWithExpirationToken() { // Arrange var path = "/file/does-not-exist"; var fileProvider = new TestFileProvider(); var viewCompiler = GetViewCompiler(fileProvider); // Act var result1 = await viewCompiler.CompileAsync(path); var result2 = await viewCompiler.CompileAsync(path); // Assert Assert.Same(result1, result2); Assert.Null(result1.Item); Assert.Collection( result1.ExpirationTokens, token => Assert.Equal(fileProvider.GetChangeToken(path), token)); } [Fact] public async Task CompileAsync_AddsChangeTokensForViewStartsIfFileExists() { // Arrange var path = "/file/exists/FilePath.cshtml"; var fileProvider = new TestFileProvider(); fileProvider.AddFile(path, "some content"); var viewCompiler = GetViewCompiler(fileProvider); // Act var result = await viewCompiler.CompileAsync(path); // Assert Assert.NotNull(result.Item); Assert.Collection( result.ExpirationTokens, token => Assert.Same(fileProvider.GetChangeToken(path), token), token => Assert.Same(fileProvider.GetChangeToken("/_ViewImports.cshtml"), token), token => Assert.Same(fileProvider.GetChangeToken("/file/_ViewImports.cshtml"), token), token => Assert.Same(fileProvider.GetChangeToken("/file/exists/_ViewImports.cshtml"), token)); } [Theory] [InlineData("/Areas/Finances/Views/Home/Index.cshtml")] [InlineData(@"Areas\Finances\Views\Home\Index.cshtml")] [InlineData(@"\Areas\Finances\Views\Home\Index.cshtml")] [InlineData(@"\Areas\Finances\Views/Home\Index.cshtml")] public async Task CompileAsync_NormalizesPathSeparatorForPaths(string relativePath) { // Arrange var viewPath = "/Areas/Finances/Views/Home/Index.cshtml"; var fileProvider = new TestFileProvider(); fileProvider.AddFile(viewPath, "some content"); var viewCompiler = GetViewCompiler(fileProvider); // Act - 1 var result1 = await viewCompiler.CompileAsync(@"Areas\Finances\Views\Home\Index.cshtml"); // Act - 2 viewCompiler.Compile = _ => throw new Exception("Can't call me"); var result2 = await viewCompiler.CompileAsync(relativePath); // Assert - 2 Assert.Same(result1, result2); } [Fact] public async Task CompileAsync_InvalidatesCache_IfChangeTokenExpires() { // Arrange var path = "/Views/Home/Index.cshtml"; var fileProvider = new TestFileProvider(); var fileNode = fileProvider.AddFile(path, "some content"); var viewCompiler = GetViewCompiler(fileProvider); // Act 1 var result1 = await viewCompiler.CompileAsync(path); // Assert 1 Assert.NotNull(result1.Item); // Act 2 // Simulate deleting the file fileProvider.GetChangeToken(path).HasChanged = true; fileProvider.DeleteFile(path); viewCompiler.Compile = _ => throw new Exception("Can't call me"); var result2 = await viewCompiler.CompileAsync(path); // Assert 2 Assert.NotSame(result1, result2); Assert.Null(result2.Item); } [Fact] public async Task CompileAsync_ReturnsNewResultIfFileWasModified() { // Arrange var path = "/Views/Home/Index.cshtml"; var fileProvider = new TestFileProvider(); fileProvider.AddFile(path, "some content"); var viewCompiler = GetViewCompiler(fileProvider); var expected2 = new CompiledViewDescriptor(); // Act 1 var result1 = await viewCompiler.CompileAsync(path); // Assert 1 Assert.NotNull(result1.Item); // Act 2 fileProvider.GetChangeToken(path).HasChanged = true; viewCompiler.Compile = _ => expected2; var result2 = await viewCompiler.CompileAsync(path); // Assert 2 Assert.NotSame(result1, result2); Assert.Same(expected2, result2); } [Fact] public async Task CompileAsync_ReturnsNewResult_IfAncestorViewImportsWereModified() { // Arrange var path = "/Views/Home/Index.cshtml"; var fileProvider = new TestFileProvider(); fileProvider.AddFile(path, "some content"); var viewCompiler = GetViewCompiler(fileProvider); var expected2 = new CompiledViewDescriptor(); // Act 1 var result1 = await viewCompiler.CompileAsync(path); // Assert 1 Assert.NotNull(result1.Item); // Act 2 fileProvider.GetChangeToken("/Views/_ViewImports.cshtml").HasChanged = true; viewCompiler.Compile = _ => expected2; var result2 = await viewCompiler.CompileAsync(path); // Assert 2 Assert.NotSame(result1, result2); Assert.Same(expected2, result2); } [Fact] public async Task CompileAsync_ReturnsPrecompiledViews() { // Arrange var path = "/Views/Home/Index.cshtml"; var fileProvider = new TestFileProvider(); fileProvider.AddFile(path, "some content"); var precompiledView = new CompiledViewDescriptor { RelativePath = path, }; var viewCompiler = GetViewCompiler(fileProvider, precompiledViews: new[] { precompiledView }); // Act var result = await viewCompiler.CompileAsync(path); // Assert Assert.Same(precompiledView, result); // This view doesn't have checksums so it can't be recompiled. Assert.Null(precompiledView.ExpirationTokens); } [Theory] [InlineData("/views/home/index.cshtml")] [InlineData("/VIEWS/HOME/INDEX.CSHTML")] [InlineData("/viEws/HoME/inDex.cshtml")] public async Task CompileAsync_PerformsCaseInsensitiveLookupsForPrecompiledViews(string lookupPath) { // Arrange var path = "/Views/Home/Index.cshtml"; var fileProvider = new TestFileProvider(); fileProvider.AddFile(path, "some content"); var precompiledView = new CompiledViewDescriptor { RelativePath = path, }; var viewCompiler = GetViewCompiler(fileProvider, precompiledViews: new[] { precompiledView }); // Act var result = await viewCompiler.CompileAsync(lookupPath); // Assert Assert.Same(precompiledView, result); } [Fact] public async Task CompileAsync_PerformsCaseInsensitiveLookupsForPrecompiledViews_WithNonNormalizedPaths() { // Arrange var path = "/Views/Home/Index.cshtml"; var fileProvider = new TestFileProvider(); fileProvider.AddFile(path, "some content"); var precompiledView = new CompiledViewDescriptor { RelativePath = path, }; var viewCompiler = GetViewCompiler(fileProvider, precompiledViews: new[] { precompiledView }); // Act var result = await viewCompiler.CompileAsync("Views\\Home\\Index.cshtml"); // Assert Assert.Same(precompiledView, result); } [Fact] public async Task CompileAsync_PrecompiledViewWithoutChecksumForMainSource_DoesNotSupportRecompilation() { // Arrange var path = "/Views/Home/Index.cshtml"; var fileProvider = new TestFileProvider(); fileProvider.AddFile(path, "some content"); var precompiledView = new CompiledViewDescriptor { RelativePath = path, Item = new TestRazorCompiledItem(typeof(string), "mvc.1.0.view", path, new object[] { new RazorSourceChecksumAttribute("sha1", GetChecksum("some content"), "/Views/Some-Other-View"), }), }; var viewCompiler = GetViewCompiler(fileProvider, precompiledViews: new[] { precompiledView }); // Act - 1 var result = await viewCompiler.CompileAsync(path); // Assert - 1 Assert.Same(precompiledView.Item, result.Item); // Act - 2 fileProvider.Watch(path); fileProvider.GetChangeToken(path).HasChanged = true; result = await viewCompiler.CompileAsync(path); // Assert - 2 Assert.Same(precompiledView.Item, result.Item); // This view doesn't have checksums so it can't be recompiled. Assert.Null(result.ExpirationTokens); } [Fact] public async Task CompileAsync_PrecompiledViewWithoutAnyChecksum_DoesNotSupportRecompilation() { // Arrange var path = "/Views/Home/Index.cshtml"; var fileProvider = new TestFileProvider(); fileProvider.AddFile(path, "some content"); var precompiledView = new CompiledViewDescriptor { RelativePath = path, Item = new TestRazorCompiledItem(typeof(string), "mvc.1.0.view", path, new object[] { }), }; var viewCompiler = GetViewCompiler(fileProvider, precompiledViews: new[] { precompiledView }); // Act - 1 var result = await viewCompiler.CompileAsync(path); // Assert - 1 Assert.Same(precompiledView, result); // Act - 2 fileProvider.Watch(path); fileProvider.GetChangeToken(path).HasChanged = true; result = await viewCompiler.CompileAsync(path); // Assert - 2 Assert.Same(precompiledView, result); // This view doesn't have checksums so it can't be recompiled. Assert.Null(result.ExpirationTokens); } [Fact] public async Task CompileAsync_PrecompiledViewWithChecksum_UsesPrecompiledViewWhenChecksumIsMatch() { // Arrange var path = "/Views/Home/Index.cshtml"; var fileProvider = new TestFileProvider(); fileProvider.AddFile(path, "some content"); var precompiledView = new CompiledViewDescriptor { RelativePath = path, Item = new TestRazorCompiledItem(typeof(string), "mvc.1.0.view", path, new object[] { new RazorSourceChecksumAttribute("SHA1", GetChecksum("some content"), path), }), }; var viewCompiler = GetViewCompiler(fileProvider, precompiledViews: new[] { precompiledView }); // Act var result = await viewCompiler.CompileAsync(path); // Assert Assert.Same(precompiledView.Item, result.Item); // This view has checksums so it should also have tokens Assert.Collection( result.ExpirationTokens, token => Assert.Same(fileProvider.GetChangeToken(path), token)); } [Fact] public async Task CompileAsync_PrecompiledViewWithChecksum_CanRejectWhenChecksumFails() { // Arrange var path = "/Views/Home/Index.cshtml"; var fileProvider = new TestFileProvider(); fileProvider.AddFile(path, "some content"); var expected = new CompiledViewDescriptor(); var precompiledView = new CompiledViewDescriptor { RelativePath = path, Item = new TestRazorCompiledItem(typeof(string), "mvc.1.0.view", path, new object[] { new RazorSourceChecksumAttribute("SHA1", GetChecksum("some other content"), path), }), }; var viewCompiler = GetViewCompiler(fileProvider, precompiledViews: new[] { precompiledView }); viewCompiler.Compile = _ => expected; // Act var result = await viewCompiler.CompileAsync(path); // Assert Assert.Same(expected, result); } [Fact] public async Task CompileAsync_PrecompiledViewWithChecksum_AddsExpirationTokensForFilesInChecksumAttributes() { // Arrange var path = "/Views/Home/Index.cshtml"; var fileProvider = new TestFileProvider(); fileProvider.AddFile(path, "some content"); var precompiledView = new CompiledViewDescriptor { RelativePath = path, Item = new TestRazorCompiledItem(typeof(string), "mvc.1.0.view", path, new object[] { new RazorSourceChecksumAttribute("SHA1", GetChecksum("some content"), path), }), }; var viewCompiler = GetViewCompiler(fileProvider, precompiledViews: new[] { precompiledView }); // Act var result = await viewCompiler.CompileAsync(path); // Assert Assert.Same(precompiledView.Item, result.Item); var token = Assert.Single(result.ExpirationTokens); Assert.Same(fileProvider.GetChangeToken(path), token); } [Fact] public async Task CompileAsync_PrecompiledViewWithChecksum_CanRecompile() { // Arrange var path = "/Views/Home/Index.cshtml"; var fileProvider = new TestFileProvider(); var file = fileProvider.AddFile(path, "some content"); var expected2 = new CompiledViewDescriptor(); var precompiledView = new CompiledViewDescriptor { RelativePath = path, Item = new TestRazorCompiledItem(typeof(string), "mvc.1.0.view", path, new object[] { new RazorSourceChecksumAttribute("SHA1", GetChecksum("some content"), path), }), }; var viewCompiler = GetViewCompiler(fileProvider, precompiledViews: new[] { precompiledView }); // Act - 1 var result = await viewCompiler.CompileAsync(path); // Assert - 1 Assert.Same(precompiledView.Item, result.Item); Assert.NotEmpty(result.ExpirationTokens); // Act - 2 file.Content = "different"; fileProvider.GetChangeToken(path).HasChanged = true; viewCompiler.Compile = _ => expected2; result = await viewCompiler.CompileAsync(path); // Assert - 2 Assert.Same(expected2, result); } [Fact] public async Task CompileAsync_PrecompiledViewWithChecksum_DoesNotRecompiledWithoutContentChange() { // Arrange var path = "/Views/Home/Index.cshtml"; var fileProvider = new TestFileProvider(); fileProvider.AddFile(path, "some content"); var precompiledView = new CompiledViewDescriptor { RelativePath = path, Item = new TestRazorCompiledItem(typeof(string), "mvc.1.0.view", path, new object[] { new RazorSourceChecksumAttribute("SHA1", GetChecksum("some content"), path), }), }; var viewCompiler = GetViewCompiler(fileProvider, precompiledViews: new[] { precompiledView }); // Act - 1 var result = await viewCompiler.CompileAsync(path); // Assert - 1 Assert.Same(precompiledView.Item, result.Item); // Act - 2 fileProvider.GetChangeToken(path).HasChanged = true; result = await viewCompiler.CompileAsync(path); // Assert - 2 Assert.Same(precompiledView.Item, result.Item); } [Fact] public async Task CompileAsync_PrecompiledViewWithChecksum_CanReusePrecompiledViewIfContentChangesToMatch() { // Arrange var path = "/Views/Home/Index.cshtml"; var fileProvider = new TestFileProvider(); var file = fileProvider.AddFile(path, "different content"); var expected1 = new CompiledViewDescriptor(); var precompiledView = new CompiledViewDescriptor { RelativePath = path, Item = new TestRazorCompiledItem(typeof(string), "mvc.1.0.view", path, new object[] { new RazorSourceChecksumAttribute("SHA1", GetChecksum("some content"), path), }), }; var viewCompiler = GetViewCompiler(fileProvider, precompiledViews: new[] { precompiledView }); viewCompiler.Compile = _ => expected1; // Act - 1 var result = await viewCompiler.CompileAsync(path); // Assert - 1 Assert.Same(expected1, result); // Act - 2 file.Content = "some content"; fileProvider.GetChangeToken(path).HasChanged = true; result = await viewCompiler.CompileAsync(path); // Assert - 2 Assert.Same(precompiledView.Item, result.Item); } [Fact] public async Task CompileAsync_PrecompiledViewWithChecksum_CanRecompileWhenViewImportChanges() { // Arrange var path = "/Views/Home/Index.cshtml"; var importPath = "/Views/_ViewImports.cshtml"; var fileProvider = new TestFileProvider(); fileProvider.AddFile(path, "some content"); var importFile = fileProvider.AddFile(importPath, "some import"); var expected2 = new CompiledViewDescriptor(); var precompiledView = new CompiledViewDescriptor { RelativePath = path, Item = new TestRazorCompiledItem(typeof(string), "mvc.1.0.view", path, new object[] { new RazorSourceChecksumAttribute("SHA1", GetChecksum("some content"), path), new RazorSourceChecksumAttribute("SHA1", GetChecksum("some import"), importPath), }), }; var viewCompiler = GetViewCompiler(fileProvider, precompiledViews: new[] { precompiledView }); // Act - 1 var result = await viewCompiler.CompileAsync(path); // Assert - 1 Assert.Same(precompiledView.Item, result.Item); // Act - 2 importFile.Content = "different content"; fileProvider.GetChangeToken(importPath).HasChanged = true; viewCompiler.Compile = _ => expected2; result = await viewCompiler.CompileAsync(path); // Assert - 2 Assert.Same(expected2, result); } [Fact] public async Task GetOrAdd_AllowsConcurrentCompilationOfMultipleRazorPages() { // Arrange var path1 = "/Views/Home/Index.cshtml"; var path2 = "/Views/Home/About.cshtml"; var waitDuration = TimeSpan.FromSeconds(20); var fileProvider = new TestFileProvider(); fileProvider.AddFile(path1, "some content"); fileProvider.AddFile(path2, "some content"); var resetEvent1 = new AutoResetEvent(initialState: false); var resetEvent2 = new ManualResetEvent(initialState: false); var compilingOne = false; var compilingTwo = false; var result1 = new CompiledViewDescriptor(); var result2 = new CompiledViewDescriptor(); var compiler = GetViewCompiler(fileProvider); compiler.Compile = path => { if (path == path1) { compilingOne = true; // Event 2 Assert.True(resetEvent1.WaitOne(waitDuration)); // Event 3 Assert.True(resetEvent2.Set()); // Event 6 Assert.True(resetEvent1.WaitOne(waitDuration)); Assert.True(compilingTwo); return result1; } else if (path == path2) { compilingTwo = true; // Event 4 Assert.True(resetEvent2.WaitOne(waitDuration)); // Event 5 Assert.True(resetEvent1.Set()); Assert.True(compilingOne); return result2; } else { throw new Exception(); } }; // Act var task1 = Task.Run(() => compiler.CompileAsync(path1)); var task2 = Task.Run(() => compiler.CompileAsync(path2)); // Event 1 resetEvent1.Set(); await Task.WhenAll(task1, task2); // Assert Assert.True(compilingOne); Assert.True(compilingTwo); Assert.Same(result1, task1.Result); Assert.Same(result2, task2.Result); } [Fact] public async Task CompileAsync_DoesNotCreateMultipleCompilationResults_ForConcurrentInvocations() { // Arrange var path = "/Views/Home/Index.cshtml"; var waitDuration = TimeSpan.FromSeconds(20); var fileProvider = new TestFileProvider(); fileProvider.AddFile(path, "some content"); var resetEvent1 = new ManualResetEvent(initialState: false); var resetEvent2 = new ManualResetEvent(initialState: false); var compiler = GetViewCompiler(fileProvider); compiler.Compile = _ => { // Event 2 resetEvent1.WaitOne(waitDuration); // Event 3 resetEvent2.Set(); return new CompiledViewDescriptor(); }; // Act var task1 = Task.Run(() => compiler.CompileAsync(path)); var task2 = Task.Run(() => { // Event 4 Assert.True(resetEvent2.WaitOne(waitDuration)); return compiler.CompileAsync(path); }); // Event 1 resetEvent1.Set(); await Task.WhenAll(task1, task2); // Assert var result1 = task1.Result; var result2 = task2.Result; Assert.Same(result1, result2); } [Fact] public async Task GetOrAdd_CachesCompilationExceptions() { // Arrange var path = "/Views/Home/Index.cshtml"; var fileProvider = new TestFileProvider(); fileProvider.AddFile(path, "some content"); var exception = new InvalidTimeZoneException(); var compiler = GetViewCompiler(fileProvider); compiler.Compile = _ => throw exception; // Act and Assert - 1 var actual = await Assert.ThrowsAsync<InvalidTimeZoneException>( () => compiler.CompileAsync(path)); Assert.Same(exception, actual); // Act and Assert - 2 compiler.Compile = _ => throw new Exception("Shouldn't be called"); actual = await Assert.ThrowsAsync<InvalidTimeZoneException>( () => compiler.CompileAsync(path)); Assert.Same(exception, actual); } [Fact] public void Compile_SucceedsForCSharp7() { // Arrange var content = @" public class MyTestType { private string _name; public string Name { get => _name; set => _name = value ?? throw new System.ArgumentNullException(nameof(value)); } }"; var compiler = GetViewCompiler(new TestFileProvider()); var codeDocument = RazorCodeDocument.Create(RazorSourceDocument.Create("razor-content", "filename")); // Act var result = compiler.CompileAndEmit(codeDocument, content); // Assert var exportedType = Assert.Single(result.ExportedTypes); Assert.Equal("MyTestType", exportedType.Name); } [Fact] public void Compile_ReturnsCompilationFailureWithPathsFromLinePragmas() { // Arrange var viewPath = "some-relative-path"; var fileContent = "test file content"; var content = $@" #line 1 ""{viewPath}"" this should fail"; var compiler = GetViewCompiler(new TestFileProvider()); var codeDocument = RazorCodeDocument.Create(RazorSourceDocument.Create(fileContent, viewPath)); // Act & Assert var ex = Assert.Throws<CompilationFailedException>(() => compiler.CompileAndEmit(codeDocument, content)); var compilationFailure = Assert.Single(ex.CompilationFailures); Assert.Equal(viewPath, compilationFailure.SourceFilePath); Assert.Equal(fileContent, compilationFailure.SourceFileContent); } [Fact] public void Compile_ReturnsGeneratedCodePath_IfLinePragmaIsNotAvailable() { // Arrange var viewPath = "some-relative-path"; var fileContent = "file content"; var content = "public class Bad { this should fail }"; var compiler = GetViewCompiler(new TestFileProvider()); var codeDocument = RazorCodeDocument.Create(RazorSourceDocument.Create(fileContent, viewPath)); // Act & Assert var ex = Assert.Throws<CompilationFailedException>(() => compiler.CompileAndEmit(codeDocument, content)); var compilationFailure = Assert.Single(ex.CompilationFailures); Assert.Equal("Generated Code", compilationFailure.SourceFilePath); Assert.Equal(content, compilationFailure.SourceFileContent); } [Fact] public void CompileAndEmit_DoesNotThrowIfDebugTypeIsEmbedded() { // Arrange var referenceManager = CreateReferenceManager(); var csharpCompiler = new TestCSharpCompiler(referenceManager, Mock.Of<IWebHostEnvironment>()) { EmitOptionsSettable = new EmitOptions(debugInformationFormat: DebugInformationFormat.Embedded), }; var compiler = GetViewCompiler(csharpCompiler: csharpCompiler); var codeDocument = RazorCodeDocument.Create(RazorSourceDocument.Create("Hello world", "some-relative-path.cshtml")); // Act var result = compiler.CompileAndEmit(codeDocument, "public class Test{}"); // Assert Assert.NotNull(result); } [Fact] public void CompileAndEmit_WorksIfEmitPdbIsNotSet() { // Arrange var referenceManager = CreateReferenceManager(); var csharpCompiler = new TestCSharpCompiler(referenceManager, Mock.Of<IWebHostEnvironment>()) { EmitPdbSettable = false, }; var compiler = GetViewCompiler(csharpCompiler: csharpCompiler); var codeDocument = RazorCodeDocument.Create(RazorSourceDocument.Create("Hello world", "some-relative-path.cshtml")); // Act var result = compiler.CompileAndEmit(codeDocument, "public class Test{}"); // Assert Assert.NotNull(result); } private static TestRazorViewCompiler GetViewCompiler( TestFileProvider fileProvider = null, RazorReferenceManager referenceManager = null, IList<CompiledViewDescriptor> precompiledViews = null, CSharpCompiler csharpCompiler = null) { fileProvider = fileProvider ?? new TestFileProvider(); var options = Options.Create(new MvcRazorRuntimeCompilationOptions { FileProviders = { fileProvider } }); var compilationFileProvider = new RuntimeCompilationFileProvider(options); referenceManager = referenceManager ?? CreateReferenceManager(); precompiledViews = precompiledViews ?? Array.Empty<CompiledViewDescriptor>(); var hostingEnvironment = Mock.Of<IWebHostEnvironment>(e => e.ContentRootPath == "BasePath"); var fileSystem = new FileProviderRazorProjectFileSystem(compilationFileProvider, hostingEnvironment); var projectEngine = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem, builder => { RazorExtensions.Register(builder); }); csharpCompiler = csharpCompiler ?? new CSharpCompiler(referenceManager, hostingEnvironment); return new TestRazorViewCompiler( fileProvider, projectEngine, csharpCompiler, precompiledViews); } private static RazorReferenceManager CreateReferenceManager() { var applicationPartManager = new ApplicationPartManager(); var assembly = typeof(RuntimeViewCompilerTest).Assembly; applicationPartManager.ApplicationParts.Add(new AssemblyPart(assembly)); return new RazorReferenceManager(applicationPartManager, Options.Create(new MvcRazorRuntimeCompilationOptions())); } private class TestRazorViewCompiler : RuntimeViewCompiler { public TestRazorViewCompiler( TestFileProvider fileProvider, RazorProjectEngine projectEngine, CSharpCompiler csharpCompiler, IList<CompiledViewDescriptor> precompiledViews, Func<string, CompiledViewDescriptor> compile = null) : base(fileProvider, projectEngine, csharpCompiler, precompiledViews, NullLogger.Instance) { Compile = compile; if (Compile == null) { Compile = path => new CompiledViewDescriptor { RelativePath = path, Item = CreateForView(path), }; } } public Func<string, CompiledViewDescriptor> Compile { get; set; } protected override CompiledViewDescriptor CompileAndEmit(string relativePath) { return Compile(relativePath); } } private class TestCSharpCompiler : CSharpCompiler { public TestCSharpCompiler(RazorReferenceManager manager, IWebHostEnvironment hostingEnvironment) : base(manager, hostingEnvironment) { } public EmitOptions EmitOptionsSettable { get; set; } public bool EmitPdbSettable { get; set; } public override EmitOptions EmitOptions => EmitOptionsSettable; public override bool EmitPdb => EmitPdbSettable; } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // A barrier allows multiple tasks to cooperatively work on some algorithm in parallel. // A group of tasks cooperate by moving through a series of phases, where each in the group signals it has arrived at // the barrier in a given phase and implicitly waits for all others to arrive. // The same barrier can be used for multiple phases. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Diagnostics; using System.Runtime.Serialization; using System.Security; namespace System.Threading { /// <summary> /// The exception that is thrown when the post-phase action of a <see cref="Barrier"/> fails. /// </summary> [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class BarrierPostPhaseException : Exception { /// <summary> /// Initializes a new instance of the <see cref="BarrierPostPhaseException"/> class. /// </summary> public BarrierPostPhaseException() : this((string)null) { } /// <summary> /// Initializes a new instance of the <see cref="BarrierPostPhaseException"/> class with the specified inner exception. /// </summary> /// <param name="innerException">The exception that is the cause of the current exception.</param> public BarrierPostPhaseException(Exception innerException) : this(null, innerException) { } /// <summary> /// Initializes a new instance of the <see cref="BarrierPostPhaseException"/> class with a specified error message. /// </summary> /// <param name="message">A string that describes the exception.</param> public BarrierPostPhaseException(string message) : this(message, null) { } /// <summary> /// Initializes a new instance of the <see cref="BarrierPostPhaseException"/> class with a specified error message and inner exception. /// </summary> /// <param name="message">A string that describes the exception.</param> /// <param name="innerException">The exception that is the cause of the current exception.</param> public BarrierPostPhaseException(string message, Exception innerException) : base(message == null ? SR.BarrierPostPhaseException : message, innerException) { } /// <summary> /// Initializes a new instance of the BarrierPostPhaseException class with serialized data. /// </summary> /// <param name="info">The object that holds the serialized object data.</param> /// <param name="context">The contextual information about the source or destination.</param> protected BarrierPostPhaseException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// Enables multiple tasks to cooperatively work on an algorithm in parallel through multiple phases. /// </summary> /// <remarks> /// <para> /// A group of tasks cooperate by moving through a series of phases, where each in the group signals it /// has arrived at the <see cref="Barrier"/> in a given phase and implicitly waits for all others to /// arrive. The same <see cref="Barrier"/> can be used for multiple phases. /// </para> /// <para> /// All public and protected members of <see cref="Barrier"/> are thread-safe and may be used /// concurrently from multiple threads, with the exception of Dispose, which /// must only be used when all other operations on the <see cref="Barrier"/> have /// completed. /// </para> /// </remarks> [DebuggerDisplay("Participant Count={ParticipantCount},Participants Remaining={ParticipantsRemaining}")] public class Barrier : IDisposable { //This variable holds the basic barrier variables: // 1- The current participants count // 2- The total participants count // 3- The sense flag (true if the current phase is even, false otherwise) // The first 15 bits are for the total count which means the maximum participants for the barrier is about 32K // The 16th bit is dummy // The next 15th bit for the current // And the last highest bit is for the sense private volatile int _currentTotalCount; // Bitmask to extract the current count private const int CURRENT_MASK = 0x7FFF0000; // Bitmask to extract the total count private const int TOTAL_MASK = 0x00007FFF; // Bitmask to extract the sense flag private const int SENSE_MASK = unchecked((int)0x80000000); // The maximum participants the barrier can operate = 32767 ( 2 power 15 - 1 ) private const int MAX_PARTICIPANTS = TOTAL_MASK; // The current barrier phase // We don't need to worry about overflow, the max value is 2^63-1; If it starts from 0 at a // rate of 4 billion increments per second, it will takes about 64 years to overflow. private long _currentPhase; // dispose flag private bool _disposed; // Odd phases event private ManualResetEventSlim _oddEvent; // Even phases event private ManualResetEventSlim _evenEvent; // The execution context of the creator thread private ExecutionContext _ownerThreadContext; // The EC callback that invokes the post phase action [SecurityCritical] private static ContextCallback s_invokePostPhaseAction; // Post phase action after each phase private Action<Barrier> _postPhaseAction; // In case the post phase action throws an exception, wraps it in BarrierPostPhaseException private Exception _exception; // This is the ManagedThreadID of the postPhaseAction caller thread, this is used to determine if the SignalAndWait, Dispose or Add/RemoveParticipant caller thread is // the same thread as the postPhaseAction thread which means this method was called from the postPhaseAction which is illegal. // This value is captured before calling the action and reset back to zero after it. private int _actionCallerID; #region Properties /// <summary> /// Gets the number of participants in the barrier that haven't yet signaled /// in the current phase. /// </summary> /// <remarks> /// This could be 0 during a post-phase action delegate execution or if the /// ParticipantCount is 0. /// </remarks> public int ParticipantsRemaining { get { int currentTotal = _currentTotalCount; int total = (int)(currentTotal & TOTAL_MASK); int current = (int)((currentTotal & CURRENT_MASK) >> 16); return total - current; } } /// <summary> /// Gets the total number of participants in the barrier. /// </summary> public int ParticipantCount { get { return (int)(_currentTotalCount & TOTAL_MASK); } } /// <summary> /// Gets the number of the barrier's current phase. /// </summary> public long CurrentPhaseNumber { // use the new Volatile.Read/Write method because it is cheaper than Interlocked.Read on AMD64 architecture get { return Volatile.Read(ref _currentPhase); } internal set { Volatile.Write(ref _currentPhase, value); } } #endregion /// <summary> /// Initializes a new instance of the <see cref="Barrier"/> class. /// </summary> /// <param name="participantCount">The number of participating threads.</param> /// <exception cref="ArgumentOutOfRangeException"> <paramref name="participantCount"/> is less than 0 /// or greater than <see cref="T:System.Int16.MaxValue"/>.</exception> public Barrier(int participantCount) : this(participantCount, null) { } /// <summary> /// Initializes a new instance of the <see cref="Barrier"/> class. /// </summary> /// <param name="participantCount">The number of participating threads.</param> /// <param name="postPhaseAction">The <see cref="T:System.Action`1"/> to be executed after each /// phase.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"> <paramref name="participantCount"/> is less than 0 /// or greater than <see cref="T:System.Int32.MaxValue"/>.</exception> /// <remarks> /// The <paramref name="postPhaseAction"/> delegate will be executed after /// all participants have arrived at the barrier in one phase. The participants /// will not be released to the next phase until the postPhaseAction delegate /// has completed execution. /// </remarks> public Barrier(int participantCount, Action<Barrier> postPhaseAction) { // the count must be non negative value if (participantCount < 0 || participantCount > MAX_PARTICIPANTS) { throw new ArgumentOutOfRangeException(nameof(participantCount), participantCount, SR.Barrier_ctor_ArgumentOutOfRange); } _currentTotalCount = (int)participantCount; _postPhaseAction = postPhaseAction; //Lazily initialize the events _oddEvent = new ManualResetEventSlim(true); _evenEvent = new ManualResetEventSlim(false); // Capture the context if the post phase action is not null if (postPhaseAction != null) { _ownerThreadContext = ExecutionContext.Capture(); } _actionCallerID = 0; } /// <summary> /// Extract the three variables current, total and sense from a given big variable /// </summary> /// <param name="currentTotal">The integer variable that contains the other three variables</param> /// <param name="current">The current participant count</param> /// <param name="total">The total participants count</param> /// <param name="sense">The sense flag</param> private void GetCurrentTotal(int currentTotal, out int current, out int total, out bool sense) { total = (int)(currentTotal & TOTAL_MASK); current = (int)((currentTotal & CURRENT_MASK) >> 16); sense = (currentTotal & SENSE_MASK) == 0 ? true : false; } /// <summary> /// Write the three variables current. total and the sense to the m_currentTotal /// </summary> /// <param name="currentTotal">The old current total to compare</param> /// <param name="current">The current participant count</param> /// <param name="total">The total participants count</param> /// <param name="sense">The sense flag</param> /// <returns>True if the CAS succeeded, false otherwise</returns> private bool SetCurrentTotal(int currentTotal, int current, int total, bool sense) { int newCurrentTotal = (current << 16) | total; if (!sense) { newCurrentTotal |= SENSE_MASK; } #pragma warning disable 0420 return Interlocked.CompareExchange(ref _currentTotalCount, newCurrentTotal, currentTotal) == currentTotal; #pragma warning restore 0420 } /// <summary> /// Notifies the <see cref="Barrier"/> that there will be an additional participant. /// </summary> /// <returns>The phase number of the barrier in which the new participants will first /// participate.</returns> /// <exception cref="T:System.InvalidOperationException"> /// Adding a participant would cause the barrier's participant count to /// exceed <see cref="T:System.Int16.MaxValue"/>. /// </exception> /// <exception cref="T:System.InvalidOperationException"> /// The method was invoked from within a post-phase action. /// </exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public long AddParticipant() { try { return AddParticipants(1); } catch (ArgumentOutOfRangeException) { throw new InvalidOperationException(SR.Barrier_AddParticipants_Overflow_ArgumentOutOfRange); } } /// <summary> /// Notifies the <see cref="Barrier"/> that there will be additional participants. /// </summary> /// <param name="participantCount">The number of additional participants to add to the /// barrier.</param> /// <returns>The phase number of the barrier in which the new participants will first /// participate.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="participantCount"/> is less than /// 0.</exception> /// <exception cref="T:System.ArgumentOutOfRangeException">Adding <paramref name="participantCount"/> participants would cause the /// barrier's participant count to exceed <see cref="T:System.Int16.MaxValue"/>.</exception> /// <exception cref="T:System.InvalidOperationException"> /// The method was invoked from within a post-phase action. /// </exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public long AddParticipants(int participantCount) { // check dispose ThrowIfDisposed(); if (participantCount < 1) { throw new ArgumentOutOfRangeException(nameof(participantCount), participantCount, SR.Barrier_AddParticipants_NonPositive_ArgumentOutOfRange); } else if (participantCount > MAX_PARTICIPANTS) //overflow { throw new ArgumentOutOfRangeException(nameof(participantCount), SR.Barrier_AddParticipants_Overflow_ArgumentOutOfRange); } // in case of this is called from the PHA if (_actionCallerID != 0 && Environment.CurrentManagedThreadId == _actionCallerID) { throw new InvalidOperationException(SR.Barrier_InvalidOperation_CalledFromPHA); } SpinWait spinner = new SpinWait(); long newPhase = 0; while (true) { int currentTotal = _currentTotalCount; int total; int current; bool sense; GetCurrentTotal(currentTotal, out current, out total, out sense); if (participantCount + total > MAX_PARTICIPANTS) //overflow { throw new ArgumentOutOfRangeException(nameof(participantCount), SR.Barrier_AddParticipants_Overflow_ArgumentOutOfRange); } if (SetCurrentTotal(currentTotal, current, total + participantCount, sense)) { // Calculating the first phase for that participant, if the current phase already finished return the next phase else return the current phase // To know that the current phase is the sense doesn't match the // phase odd even, so that means it didn't yet change the phase count, so currentPhase +1 is returned, otherwise currentPhase is returned long currPhase = CurrentPhaseNumber; newPhase = (sense != (currPhase % 2 == 0)) ? currPhase + 1 : currPhase; // If this participant is going to join the next phase, which means the postPhaseAction is being running, this participants must wait until this done // and its event is reset. // Without that, if the postPhaseAction takes long time, this means the event that the current participant is going to wait on is still set // (FinishPhase didn't reset it yet) so it should wait until it reset if (newPhase != currPhase) { // Wait on the opposite event if (sense) { _oddEvent.Wait(); } else { _evenEvent.Wait(); } } //This else to fix the racing where the current phase has been finished, m_currentPhase has been updated but the events have not been set/reset yet // otherwise when this participant calls SignalAndWait it will wait on a set event however all other participants have not arrived yet. else { if (sense && _evenEvent.IsSet) _evenEvent.Reset(); else if (!sense && _oddEvent.IsSet) _oddEvent.Reset(); } break; } spinner.SpinOnce(); } return newPhase; } /// <summary> /// Notifies the <see cref="Barrier"/> that there will be one less participant. /// </summary> /// <exception cref="T:System.InvalidOperationException">The barrier already has 0 /// participants.</exception> /// <exception cref="T:System.InvalidOperationException"> /// The method was invoked from within a post-phase action. /// </exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public void RemoveParticipant() { RemoveParticipants(1); } /// <summary> /// Notifies the <see cref="Barrier"/> that there will be fewer participants. /// </summary> /// <param name="participantCount">The number of additional participants to remove from the barrier.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="participantCount"/> is less than /// 0.</exception> /// <exception cref="T:System.InvalidOperationException">The barrier already has 0 participants.</exception> /// <exception cref="T:System.InvalidOperationException"> /// The method was invoked from within a post-phase action. /// </exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public void RemoveParticipants(int participantCount) { // check dispose ThrowIfDisposed(); // Validate input if (participantCount < 1) { throw new ArgumentOutOfRangeException(nameof(participantCount), participantCount, SR.Barrier_RemoveParticipants_NonPositive_ArgumentOutOfRange); } // in case of this is called from the PHA if (_actionCallerID != 0 && Environment.CurrentManagedThreadId == _actionCallerID) { throw new InvalidOperationException(SR.Barrier_InvalidOperation_CalledFromPHA); } SpinWait spinner = new SpinWait(); while (true) { int currentTotal = _currentTotalCount; int total; int current; bool sense; GetCurrentTotal(currentTotal, out current, out total, out sense); if (total < participantCount) { throw new ArgumentOutOfRangeException(nameof(participantCount), SR.Barrier_RemoveParticipants_ArgumentOutOfRange); } if (total - participantCount < current) { throw new InvalidOperationException(SR.Barrier_RemoveParticipants_InvalidOperation); } // If the remaining participants = current participants, then finish the current phase int remaingParticipants = total - participantCount; if (remaingParticipants > 0 && current == remaingParticipants) { if (SetCurrentTotal(currentTotal, 0, total - participantCount, !sense)) { FinishPhase(sense); break; } } else { if (SetCurrentTotal(currentTotal, current, total - participantCount, sense)) { break; } } spinner.SpinOnce(); } } /// <summary> /// Signals that a participant has reached the <see cref="Barrier"/> and waits for all other /// participants to reach the barrier as well. /// </summary> /// <exception cref="T:System.InvalidOperationException"> /// The method was invoked from within a post-phase action, the barrier currently has 0 participants, /// or the barrier is being used by more threads than are registered as participants. /// </exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public void SignalAndWait() { SignalAndWait(new CancellationToken()); } /// <summary> /// Signals that a participant has reached the <see cref="Barrier"/> and waits for all other /// participants to reach the barrier, while observing a <see /// cref="T:System.Threading.CancellationToken"/>. /// </summary> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to /// observe.</param> /// <exception cref="T:System.InvalidOperationException"> /// The method was invoked from within a post-phase action, the barrier currently has 0 participants, /// or the barrier is being used by more threads than are registered as participants. /// </exception> /// <exception cref="T:System.OperationCanceledException"><paramref name="cancellationToken"/> has been /// canceled.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public void SignalAndWait(CancellationToken cancellationToken) { #if DEBUG bool result = #endif SignalAndWait(Timeout.Infinite, cancellationToken); #if DEBUG Debug.Assert(result); #endif } /// <summary> /// Signals that a participant has reached the <see cref="Barrier"/> and waits for all other /// participants to reach the barrier as well, using a /// <see cref="T:System.TimeSpan"/> to measure the time interval. /// </summary> /// <param name="timeout">A <see cref="T:System.TimeSpan"/> that represents the number of /// milliseconds to wait, or a <see cref="T:System.TimeSpan"/> that represents -1 milliseconds to /// wait indefinitely.</param> /// <returns>true if all other participants reached the barrier; otherwise, false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/>is a negative number /// other than -1 milliseconds, which represents an infinite time-out, or it is greater than /// <see cref="T:System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.InvalidOperationException"> /// The method was invoked from within a post-phase action, the barrier currently has 0 participants, /// or the barrier is being used by more threads than are registered as participants. /// </exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public Boolean SignalAndWait(TimeSpan timeout) { return SignalAndWait(timeout, new CancellationToken()); } /// <summary> /// Signals that a participant has reached the <see cref="Barrier"/> and waits for all other /// participants to reach the barrier as well, using a /// <see cref="T:System.TimeSpan"/> to measure the time interval, while observing a <see /// cref="T:System.Threading.CancellationToken"/>. /// </summary> /// <param name="timeout">A <see cref="T:System.TimeSpan"/> that represents the number of /// milliseconds to wait, or a <see cref="T:System.TimeSpan"/> that represents -1 milliseconds to /// wait indefinitely.</param> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to /// observe.</param> /// <returns>true if all other participants reached the barrier; otherwise, false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/>is a negative number /// other than -1 milliseconds, which represents an infinite time-out.</exception> /// <exception cref="T:System.InvalidOperationException"> /// The method was invoked from within a post-phase action, the barrier currently has 0 participants, /// or the barrier is being used by more threads than are registered as participants. /// </exception> /// <exception cref="T:System.OperationCanceledException"><paramref name="cancellationToken"/> has been /// canceled.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public Boolean SignalAndWait(TimeSpan timeout, CancellationToken cancellationToken) { Int64 totalMilliseconds = (Int64)timeout.TotalMilliseconds; if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new System.ArgumentOutOfRangeException(nameof(timeout), timeout, SR.Barrier_SignalAndWait_ArgumentOutOfRange); } return SignalAndWait((int)timeout.TotalMilliseconds, cancellationToken); } /// <summary> /// Signals that a participant has reached the <see cref="Barrier"/> and waits for all other /// participants to reach the barrier as well, using a /// 32-bit signed integer to measure the time interval. /// </summary> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see /// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param> /// <returns>true if all other participants reached the barrier; otherwise, false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a /// negative number other than -1, which represents an infinite time-out.</exception> /// <exception cref="T:System.InvalidOperationException"> /// The method was invoked from within a post-phase action, the barrier currently has 0 participants, /// or the barrier is being used by more threads than are registered as participants. /// </exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public bool SignalAndWait(int millisecondsTimeout) { return SignalAndWait(millisecondsTimeout, new CancellationToken()); } /// <summary> /// Signals that a participant has reached the barrier and waits for all other participants to reach /// the barrier as well, using a /// 32-bit signed integer to measure the time interval, while observing a <see /// cref="T:System.Threading.CancellationToken"/>. /// </summary> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see /// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to /// observe.</param> /// <returns>true if all other participants reached the barrier; otherwise, false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a /// negative number other than -1, which represents an infinite time-out.</exception> /// <exception cref="T:System.InvalidOperationException"> /// The method was invoked from within a post-phase action, the barrier currently has 0 participants, /// or the barrier is being used by more threads than are registered as participants. /// </exception> /// <exception cref="T:System.OperationCanceledException"><paramref name="cancellationToken"/> has been /// canceled.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public bool SignalAndWait(int millisecondsTimeout, CancellationToken cancellationToken) { ThrowIfDisposed(); cancellationToken.ThrowIfCancellationRequested(); if (millisecondsTimeout < -1) { throw new System.ArgumentOutOfRangeException(nameof(millisecondsTimeout), millisecondsTimeout, SR.Barrier_SignalAndWait_ArgumentOutOfRange); } // in case of this is called from the PHA if (_actionCallerID != 0 && Environment.CurrentManagedThreadId == _actionCallerID) { throw new InvalidOperationException(SR.Barrier_InvalidOperation_CalledFromPHA); } // local variables to extract the basic barrier variable and update them // The are declared here instead of inside the loop body because the will be used outside the loop bool sense; // The sense of the barrier *before* the phase associated with this SignalAndWait call completes int total; int current; int currentTotal; long phase; SpinWait spinner = new SpinWait(); while (true) { currentTotal = _currentTotalCount; GetCurrentTotal(currentTotal, out current, out total, out sense); phase = CurrentPhaseNumber; // throw if zero participants if (total == 0) { throw new InvalidOperationException(SR.Barrier_SignalAndWait_InvalidOperation_ZeroTotal); } // Try to detect if the number of threads for this phase exceeded the total number of participants or not // This can be detected if the current is zero which means all participants for that phase has arrived and the phase number is not changed yet if (current == 0 && sense != (CurrentPhaseNumber % 2 == 0)) { throw new InvalidOperationException(SR.Barrier_SignalAndWait_InvalidOperation_ThreadsExceeded); } //This is the last thread, finish the phase if (current + 1 == total) { if (SetCurrentTotal(currentTotal, 0, total, !sense)) { if (CdsSyncEtwBCLProvider.Log.IsEnabled()) { CdsSyncEtwBCLProvider.Log.Barrier_PhaseFinished(sense, CurrentPhaseNumber); } FinishPhase(sense); return true; } } else if (SetCurrentTotal(currentTotal, current + 1, total, sense)) { break; } spinner.SpinOnce(); } // ** Perform the real wait ** // select the correct event to wait on, based on the current sense. ManualResetEventSlim eventToWaitOn = (sense) ? _evenEvent : _oddEvent; bool waitWasCanceled = false; bool waitResult = false; try { waitResult = DiscontinuousWait(eventToWaitOn, millisecondsTimeout, cancellationToken, phase); } catch (OperationCanceledException) { waitWasCanceled = true; } catch (ObjectDisposedException)// in case a race happen where one of the thread returned from SignalAndWait and the current thread calls Wait on a disposed event { // make sure the current phase for this thread is already finished, otherwise propagate the exception if (phase < CurrentPhaseNumber) waitResult = true; else throw; } if (!waitResult) { //reset the spinLock to prepare it for the next loop spinner.Reset(); //If the wait timeout expired and all other thread didn't reach the barrier yet, update the current count back while (true) { bool newSense; currentTotal = _currentTotalCount; GetCurrentTotal(currentTotal, out current, out total, out newSense); // If the timeout expired and the phase has just finished, return true and this is considered as succeeded SignalAndWait //otherwise the timeout expired and the current phase has not been finished yet, return false //The phase is finished if the phase member variable is changed (incremented) or the sense has been changed // we have to use the statements in the comparison below for two cases: // 1- The sense is changed but the last thread didn't update the phase yet // 2- The phase is already incremented but the sense flipped twice due to the termination of the next phase if (phase < CurrentPhaseNumber || sense != newSense) { // The current phase has been finished, but we shouldn't return before the events are set/reset otherwise this thread could start // next phase and the appropriate event has not reset yet which could make it return immediately from the next phase SignalAndWait // before waiting other threads WaitCurrentPhase(eventToWaitOn, phase); Debug.Assert(phase < CurrentPhaseNumber); break; } //The phase has not been finished yet, try to update the current count. if (SetCurrentTotal(currentTotal, current - 1, total, sense)) { //if here, then the attempt to back out was successful. //throw (a fresh) OCE if cancellation woke the wait //or return false if it was the timeout that woke the wait. // if (waitWasCanceled) throw new OperationCanceledException(SR.Common_OperationCanceled, cancellationToken); else return false; } spinner.SpinOnce(); } } if (_exception != null) throw new BarrierPostPhaseException(_exception); return true; } /// <summary> /// Finish the phase by invoking the post phase action, and setting the event, this must be called by the /// last arrival thread /// </summary> /// <param name="observedSense">The current phase sense</param> [SecuritySafeCritical] private void FinishPhase(bool observedSense) { // Execute the PHA in try/finally block to reset the variables back in case of it threw an exception if (_postPhaseAction != null) { try { // Capture the caller thread ID to check if the Add/RemoveParticipant(s) is called from the PHA _actionCallerID = Environment.CurrentManagedThreadId; if (_ownerThreadContext != null) { var currentContext = _ownerThreadContext; ContextCallback handler = s_invokePostPhaseAction; if (handler == null) { s_invokePostPhaseAction = handler = InvokePostPhaseAction; } ExecutionContext.Run(_ownerThreadContext, handler, this); } else { _postPhaseAction(this); } _exception = null; // reset the exception if it was set previously } catch (Exception ex) { _exception = ex; } finally { _actionCallerID = 0; SetResetEvents(observedSense); if (_exception != null) throw new BarrierPostPhaseException(_exception); } } else { SetResetEvents(observedSense); } } /// <summary> /// Helper method to call the post phase action /// </summary> /// <param name="obj"></param> [SecurityCritical] private static void InvokePostPhaseAction(object obj) { var thisBarrier = (Barrier)obj; thisBarrier._postPhaseAction(thisBarrier); } /// <summary> /// Sets the current phase event and reset the next phase event /// </summary> /// <param name="observedSense">The current phase sense</param> private void SetResetEvents(bool observedSense) { // Increment the phase count using Volatile class because m_currentPhase is 64 bit long type, that could cause torn write on 32 bit machines CurrentPhaseNumber = CurrentPhaseNumber + 1; if (observedSense) { _oddEvent.Reset(); _evenEvent.Set(); } else { _evenEvent.Reset(); _oddEvent.Set(); } } /// <summary> /// Wait until the current phase finishes completely by spinning until either the event is set, /// or the phase count is incremented more than one time /// </summary> /// <param name="currentPhaseEvent">The current phase event</param> /// <param name="observedPhase">The current phase for that thread</param> private void WaitCurrentPhase(ManualResetEventSlim currentPhaseEvent, long observedPhase) { //spin until either of these two conditions succeeds //1- The event is set //2- the phase count is incremented more than one time, this means the next phase is finished as well, //but the event will be reset again, so we check the phase count instead SpinWait spinner = new SpinWait(); while (!currentPhaseEvent.IsSet && CurrentPhaseNumber - observedPhase <= 1) { spinner.SpinOnce(); } } /// <summary> /// The reason of discontinuous waiting instead of direct waiting on the event is to avoid the race where the sense is /// changed twice because the next phase is finished (due to either RemoveParticipant is called or another thread joined /// the next phase instead of the current thread) so the current thread will be stuck on the event because it is reset back /// The maxWait and the shift numbers are arbitrarily chosen, there were no references picking them /// </summary> /// <param name="currentPhaseEvent">The current phase event</param> /// <param name="totalTimeout">wait timeout in milliseconds</param> /// <param name="token">cancellation token passed to SignalAndWait</param> /// <param name="observedPhase">The current phase number for this thread</param> /// <returns>True if the event is set or the phase number changed, false if the timeout expired</returns> private bool DiscontinuousWait(ManualResetEventSlim currentPhaseEvent, int totalTimeout, CancellationToken token, long observedPhase) { int maxWait = 100; // 100 ms int waitTimeCeiling = 10000; // 10 seconds while (observedPhase == CurrentPhaseNumber) { // the next wait time, the min of the maxWait and the totalTimeout int waitTime = totalTimeout == Timeout.Infinite ? maxWait : Math.Min(maxWait, totalTimeout); if (currentPhaseEvent.Wait(waitTime, token)) return true; //update the total wait time if (totalTimeout != Timeout.Infinite) { totalTimeout -= waitTime; if (totalTimeout <= 0) return false; } //if the maxwait exceeded 10 seconds then we will stop increasing the maxWait time and keep it 10 seconds, otherwise keep doubling it maxWait = maxWait >= waitTimeCeiling ? waitTimeCeiling : Math.Min(maxWait << 1, waitTimeCeiling); } //if we exited the loop because the observed phase doesn't match the current phase, then we have to spin to make sure //the event is set or the next phase is finished WaitCurrentPhase(currentPhaseEvent, observedPhase); return true; } /// <summary> /// Releases all resources used by the current instance of <see cref="Barrier"/>. /// </summary> /// <exception cref="T:System.InvalidOperationException"> /// The method was invoked from within a post-phase action. /// </exception> /// <remarks> /// Unlike most of the members of <see cref="Barrier"/>, Dispose is not thread-safe and may not be /// used concurrently with other members of this instance. /// </remarks> public void Dispose() { // in case of this is called from the PHA if (_actionCallerID != 0 && Environment.CurrentManagedThreadId == _actionCallerID) { throw new InvalidOperationException(SR.Barrier_InvalidOperation_CalledFromPHA); } Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// When overridden in a derived class, releases the unmanaged resources used by the /// <see cref="Barrier"/>, and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release /// only unmanaged resources.</param> /// <remarks> /// Unlike most of the members of <see cref="Barrier"/>, Dispose is not thread-safe and may not be /// used concurrently with other members of this instance. /// </remarks> protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { _oddEvent.Dispose(); _evenEvent.Dispose(); } _disposed = true; } } /// <summary> /// Throw ObjectDisposedException if the barrier is disposed /// </summary> private void ThrowIfDisposed() { if (_disposed) { throw new ObjectDisposedException("Barrier", SR.Barrier_Dispose); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; using System.Reflection; using System.Security.Claims; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Routing.Constraints; using Microsoft.AspNetCore.Routing.Patterns; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; namespace Microsoft.AspNetCore.Mvc.ApiExplorer { public class EndpointMetadataApiDescriptionProviderTest { [Fact] public void MultipleApiDescriptionsCreatedForMultipleHttpMethods() { var apiDescriptions = GetApiDescriptions(() => { }, "/", new string[] { "FOO", "BAR" }); Assert.Equal(2, apiDescriptions.Count); } [Fact] public void ApiDescriptionNotCreatedIfNoHttpMethods() { var apiDescriptions = GetApiDescriptions(() => { }, "/", Array.Empty<string>()); Assert.Empty(apiDescriptions); } [Fact] public void UsesDeclaringTypeAsControllerName() { var apiDescription = GetApiDescription(TestAction); var declaringTypeName = typeof(EndpointMetadataApiDescriptionProviderTest).Name; Assert.Equal(declaringTypeName, apiDescription.ActionDescriptor.RouteValues["controller"]); } [Fact] public void UsesApplicationNameAsControllerNameIfNoDeclaringType() { var apiDescription = GetApiDescription(() => { }); Assert.Equal(nameof(EndpointMetadataApiDescriptionProviderTest), apiDescription.ActionDescriptor.RouteValues["controller"]); } [Fact] public void AddsRequestFormatFromMetadata() { static void AssertCustomRequestFormat(ApiDescription apiDescription) { var requestFormat = Assert.Single(apiDescription.SupportedRequestFormats); Assert.Equal("application/custom", requestFormat.MediaType); Assert.Null(requestFormat.Formatter); } AssertCustomRequestFormat(GetApiDescription( [Consumes("application/custom")] (InferredJsonClass fromBody) => { })); AssertCustomRequestFormat(GetApiDescription( [Consumes("application/custom")] ([FromBody] int fromBody) => { })); } [Fact] public void AddsMultipleRequestFormatsFromMetadata() { var apiDescription = GetApiDescription( [Consumes("application/custom0", "application/custom1")] (InferredJsonClass fromBody) => { }); Assert.Equal(2, apiDescription.SupportedRequestFormats.Count); var requestFormat0 = apiDescription.SupportedRequestFormats[0]; Assert.Equal("application/custom0", requestFormat0.MediaType); Assert.Null(requestFormat0.Formatter); var requestFormat1 = apiDescription.SupportedRequestFormats[1]; Assert.Equal("application/custom1", requestFormat1.MediaType); Assert.Null(requestFormat1.Formatter); } [Fact] public void AddsMultipleRequestFormatsFromMetadataWithRequestTypeAndOptionalBodyParameter() { var apiDescription = GetApiDescription( [Consumes(typeof(InferredJsonClass), "application/custom0", "application/custom1", IsOptional = true)] () => { }); Assert.Equal(2, apiDescription.SupportedRequestFormats.Count); var apiParameterDescription = apiDescription.ParameterDescriptions[0]; Assert.Equal("InferredJsonClass", apiParameterDescription.Type.Name); Assert.False(apiParameterDescription.IsRequired); } [Fact] public void AddsMultipleRequestFormatsFromMetadataWithRequiredBodyParameter() { var apiDescription = GetApiDescription( [Consumes(typeof(InferredJsonClass), "application/custom0", "application/custom1", IsOptional = false)] (InferredJsonClass fromBody) => { }); Assert.Equal(2, apiDescription.SupportedRequestFormats.Count); var apiParameterDescription = apiDescription.ParameterDescriptions[0]; Assert.Equal("InferredJsonClass", apiParameterDescription.Type.Name); Assert.True(apiParameterDescription.IsRequired); } [Fact] public void AddsJsonResponseFormatWhenFromBodyInferred() { static void AssertJsonResponse(ApiDescription apiDescription, Type expectedType) { var responseType = Assert.Single(apiDescription.SupportedResponseTypes); Assert.Equal(200, responseType.StatusCode); Assert.Equal(expectedType, responseType.Type); Assert.Equal(expectedType, responseType.ModelMetadata.ModelType); var responseFormat = Assert.Single(responseType.ApiResponseFormats); Assert.Equal("application/json", responseFormat.MediaType); Assert.Null(responseFormat.Formatter); } AssertJsonResponse(GetApiDescription(() => new InferredJsonClass()), typeof(InferredJsonClass)); AssertJsonResponse(GetApiDescription(() => (IInferredJsonInterface)null), typeof(IInferredJsonInterface)); } [Fact] public void AddsTextResponseFormatWhenFromBodyInferred() { var apiDescription = GetApiDescription(() => "foo"); var responseType = Assert.Single(apiDescription.SupportedResponseTypes); Assert.Equal(200, responseType.StatusCode); Assert.Equal(typeof(string), responseType.Type); Assert.Equal(typeof(string), responseType.ModelMetadata.ModelType); var responseFormat = Assert.Single(responseType.ApiResponseFormats); Assert.Equal("text/plain", responseFormat.MediaType); Assert.Null(responseFormat.Formatter); } [Fact] public void AddsNoResponseFormatWhenItCannotBeInferredAndTheresNoMetadata() { static void AssertVoid(ApiDescription apiDescription) { var responseType = Assert.Single(apiDescription.SupportedResponseTypes); Assert.Equal(200, responseType.StatusCode); Assert.Equal(typeof(void), responseType.Type); Assert.Equal(typeof(void), responseType.ModelMetadata.ModelType); Assert.Empty(responseType.ApiResponseFormats); } AssertVoid(GetApiDescription(() => { })); AssertVoid(GetApiDescription(() => Task.CompletedTask)); AssertVoid(GetApiDescription(() => new ValueTask())); } [Fact] public void AddsResponseFormatFromMetadata() { var apiDescription = GetApiDescription( [ProducesResponseType(typeof(TimeSpan), StatusCodes.Status201Created)] [Produces("application/custom")] () => new InferredJsonClass()); var responseType = Assert.Single(apiDescription.SupportedResponseTypes); Assert.Equal(201, responseType.StatusCode); Assert.Equal(typeof(TimeSpan), responseType.Type); Assert.Equal(typeof(TimeSpan), responseType.ModelMetadata.ModelType); var responseFormat = Assert.Single(responseType.ApiResponseFormats); Assert.Equal("application/custom", responseFormat.MediaType); } [Fact] public void AddsMultipleResponseFormatsFromMetadataWithPoco() { var apiDescription = GetApiDescription( [ProducesResponseType(typeof(TimeSpan), StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status400BadRequest)] () => new InferredJsonClass()); Assert.Equal(2, apiDescription.SupportedResponseTypes.Count); var createdResponseType = apiDescription.SupportedResponseTypes[0]; Assert.Equal(201, createdResponseType.StatusCode); Assert.Equal(typeof(TimeSpan), createdResponseType.Type); Assert.Equal(typeof(TimeSpan), createdResponseType.ModelMetadata.ModelType); var createdResponseFormat = Assert.Single(createdResponseType.ApiResponseFormats); Assert.Equal("application/json", createdResponseFormat.MediaType); var badRequestResponseType = apiDescription.SupportedResponseTypes[1]; Assert.Equal(400, badRequestResponseType.StatusCode); Assert.Equal(typeof(InferredJsonClass), badRequestResponseType.Type); Assert.Equal(typeof(InferredJsonClass), badRequestResponseType.ModelMetadata.ModelType); var badRequestResponseFormat = Assert.Single(badRequestResponseType.ApiResponseFormats); Assert.Equal("application/json", badRequestResponseFormat.MediaType); } [Fact] public void AddsMultipleResponseFormatsFromMetadataWithIResult() { var apiDescription = GetApiDescription( [ProducesResponseType(typeof(InferredJsonClass), StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status400BadRequest)] () => Results.Ok(new InferredJsonClass())); Assert.Equal(2, apiDescription.SupportedResponseTypes.Count); var createdResponseType = apiDescription.SupportedResponseTypes[0]; Assert.Equal(201, createdResponseType.StatusCode); Assert.Equal(typeof(InferredJsonClass), createdResponseType.Type); Assert.Equal(typeof(InferredJsonClass), createdResponseType.ModelMetadata.ModelType); var createdResponseFormat = Assert.Single(createdResponseType.ApiResponseFormats); Assert.Equal("application/json", createdResponseFormat.MediaType); var badRequestResponseType = apiDescription.SupportedResponseTypes[1]; Assert.Equal(400, badRequestResponseType.StatusCode); Assert.Equal(typeof(void), badRequestResponseType.Type); Assert.Equal(typeof(void), badRequestResponseType.ModelMetadata.ModelType); Assert.Empty(badRequestResponseType.ApiResponseFormats); } [Fact] public void AddsFromRouteParameterAsPath() { static void AssertPathParameter(ApiDescription apiDescription) { var param = Assert.Single(apiDescription.ParameterDescriptions); Assert.Equal(typeof(int), param.Type); Assert.Equal(typeof(int), param.ModelMetadata.ModelType); Assert.Equal(BindingSource.Path, param.Source); } AssertPathParameter(GetApiDescription((int foo) => { }, "/{foo}")); AssertPathParameter(GetApiDescription(([FromRoute] int foo) => { })); } [Fact] public void AddsFromRouteParameterAsPathWithCustomClassWithTryParse() { static void AssertPathParameter(ApiDescription apiDescription) { var param = Assert.Single(apiDescription.ParameterDescriptions); Assert.Equal(typeof(TryParseStringRecord), param.Type); Assert.Equal(typeof(string), param.ModelMetadata.ModelType); Assert.Equal(BindingSource.Path, param.Source); } AssertPathParameter(GetApiDescription((TryParseStringRecord foo) => { }, "/{foo}")); } [Fact] public void AddsFromRouteParameterAsPathWithPrimitiveType() { static void AssertPathParameter(ApiDescription apiDescription) { var param = Assert.Single(apiDescription.ParameterDescriptions); Assert.Equal(typeof(int), param.Type); Assert.Equal(typeof(int), param.ModelMetadata.ModelType); Assert.Equal(BindingSource.Path, param.Source); } AssertPathParameter(GetApiDescription((int foo) => { }, "/{foo}")); } [Fact] public void AddsFromRouteParameterAsPathWithNullablePrimitiveType() { static void AssertPathParameter(ApiDescription apiDescription) { var param = Assert.Single(apiDescription.ParameterDescriptions); Assert.Equal(typeof(int?), param.Type); Assert.Equal(typeof(int?), param.ModelMetadata.ModelType); Assert.Equal(BindingSource.Path, param.Source); } AssertPathParameter(GetApiDescription((int? foo) => { }, "/{foo}")); } [Fact] public void AddsFromRouteParameterAsPathWithStructTypeWithTryParse() { static void AssertPathParameter(ApiDescription apiDescription) { var param = Assert.Single(apiDescription.ParameterDescriptions); Assert.Equal(typeof(TryParseStringRecordStruct), param.Type); Assert.Equal(typeof(string), param.ModelMetadata.ModelType); Assert.Equal(BindingSource.Path, param.Source); } AssertPathParameter(GetApiDescription((TryParseStringRecordStruct foo) => { }, "/{foo}")); } [Fact] public void AddsFromQueryParameterAsQuery() { static void AssertQueryParameter(ApiDescription apiDescription) { var param = Assert.Single(apiDescription.ParameterDescriptions); Assert.Equal(typeof(int), param.Type); Assert.Equal(typeof(int), param.ModelMetadata.ModelType); Assert.Equal(BindingSource.Query, param.Source); } AssertQueryParameter(GetApiDescription((int foo) => { }, "/")); AssertQueryParameter(GetApiDescription(([FromQuery] int foo) => { })); } [Fact] public void AddsFromHeaderParameterAsHeader() { var apiDescription = GetApiDescription(([FromHeader] int foo) => { }); var param = Assert.Single(apiDescription.ParameterDescriptions); Assert.Equal(typeof(int), param.Type); Assert.Equal(typeof(int), param.ModelMetadata.ModelType); Assert.Equal(BindingSource.Header, param.Source); } [Fact] public void DoesNotAddFromServiceParameterAsService() { Assert.Empty(GetApiDescription((IInferredServiceInterface foo) => { }).ParameterDescriptions); Assert.Empty(GetApiDescription(([FromServices] int foo) => { }).ParameterDescriptions); Assert.Empty(GetApiDescription((HttpContext context) => { }).ParameterDescriptions); Assert.Empty(GetApiDescription((HttpRequest request) => { }).ParameterDescriptions); Assert.Empty(GetApiDescription((HttpResponse response) => { }).ParameterDescriptions); Assert.Empty(GetApiDescription((ClaimsPrincipal user) => { }).ParameterDescriptions); Assert.Empty(GetApiDescription((CancellationToken token) => { }).ParameterDescriptions); Assert.Empty(GetApiDescription((BindAsyncRecord context) => { }).ParameterDescriptions); } [Fact] public void DoesNotAddFromBodyParameterInTheParameterDescription() { static void AssertBodyParameter(ApiDescription apiDescription, Type expectedType) { Assert.Empty(apiDescription.ParameterDescriptions); } AssertBodyParameter(GetApiDescription((InferredJsonClass foo) => { }), typeof(InferredJsonClass)); AssertBodyParameter(GetApiDescription(([FromBody] int foo) => { }), typeof(int)); } [Fact] public void AddsDefaultValueFromParameters() { var apiDescription = GetApiDescription(TestActionWithDefaultValue); var param = Assert.Single(apiDescription.ParameterDescriptions); Assert.Equal(42, param.DefaultValue); } [Fact] public void AddsMultipleParameters() { var apiDescription = GetApiDescription(([FromRoute] int foo, int bar, InferredJsonClass fromBody) => { }); Assert.Equal(2, apiDescription.ParameterDescriptions.Count); var fooParam = apiDescription.ParameterDescriptions[0]; Assert.Equal(typeof(int), fooParam.Type); Assert.Equal(typeof(int), fooParam.ModelMetadata.ModelType); Assert.Equal(BindingSource.Path, fooParam.Source); Assert.True(fooParam.IsRequired); var barParam = apiDescription.ParameterDescriptions[1]; Assert.Equal(typeof(int), barParam.Type); Assert.Equal(typeof(int), barParam.ModelMetadata.ModelType); Assert.Equal(BindingSource.Query, barParam.Source); Assert.True(barParam.IsRequired); } [Fact] public void TestParameterIsRequired() { var apiDescription = GetApiDescription(([FromRoute] int foo, int? bar) => { }); Assert.Equal(2, apiDescription.ParameterDescriptions.Count); var fooParam = apiDescription.ParameterDescriptions[0]; Assert.Equal(typeof(int), fooParam.Type); Assert.Equal(typeof(int), fooParam.ModelMetadata.ModelType); Assert.Equal(BindingSource.Path, fooParam.Source); Assert.True(fooParam.IsRequired); var barParam = apiDescription.ParameterDescriptions[1]; Assert.Equal(typeof(int?), barParam.Type); Assert.Equal(typeof(int?), barParam.ModelMetadata.ModelType); Assert.Equal(BindingSource.Query, barParam.Source); Assert.False(barParam.IsRequired); } [Fact] public void AddsDisplayNameFromRouteEndpoint() { var apiDescription = GetApiDescription(() => "foo", displayName: "FOO"); Assert.Equal("FOO", apiDescription.ActionDescriptor.DisplayName); } [Fact] public void AddsMetadataFromRouteEndpoint() { var apiDescription = GetApiDescription([ApiExplorerSettings(IgnoreApi = true)]() => { }); Assert.NotEmpty(apiDescription.ActionDescriptor.EndpointMetadata); var apiExplorerSettings = apiDescription.ActionDescriptor.EndpointMetadata .OfType<ApiExplorerSettingsAttribute>() .FirstOrDefault(); Assert.NotNull(apiExplorerSettings); Assert.True(apiExplorerSettings.IgnoreApi); } [Fact] public void TestParameterIsRequiredForObliviousNullabilityContext() { // In an oblivious nullability context, reference type parameters without // annotations are optional. Value type parameters are always required. var apiDescription = GetApiDescription((string foo, int bar) => { }); Assert.Equal(2, apiDescription.ParameterDescriptions.Count); var fooParam = apiDescription.ParameterDescriptions[0]; Assert.Equal(typeof(string), fooParam.Type); Assert.Equal(typeof(string), fooParam.ModelMetadata.ModelType); Assert.Equal(BindingSource.Query, fooParam.Source); Assert.False(fooParam.IsRequired); var barParam = apiDescription.ParameterDescriptions[1]; Assert.Equal(typeof(int), barParam.Type); Assert.Equal(typeof(int), barParam.ModelMetadata.ModelType); Assert.Equal(BindingSource.Query, barParam.Source); Assert.True(barParam.IsRequired); } [Fact] public void TestParameterAttributesCanBeInspected() { var apiDescription = GetApiDescription(([Description("The name.")] string name) => { }); Assert.Equal(1, apiDescription.ParameterDescriptions.Count); var nameParam = apiDescription.ParameterDescriptions[0]; Assert.Equal(typeof(string), nameParam.Type); Assert.Equal(typeof(string), nameParam.ModelMetadata.ModelType); Assert.Equal(BindingSource.Query, nameParam.Source); Assert.False(nameParam.IsRequired); Assert.NotNull(nameParam.ParameterDescriptor); Assert.Equal("name", nameParam.ParameterDescriptor.Name); Assert.Equal(typeof(string), nameParam.ParameterDescriptor.ParameterType); var descriptor = Assert.IsAssignableFrom<IParameterInfoParameterDescriptor>(nameParam.ParameterDescriptor); Assert.NotNull(descriptor.ParameterInfo); var description = Assert.Single(descriptor.ParameterInfo.GetCustomAttributes<DescriptionAttribute>()); Assert.NotNull(description); Assert.Equal("The name.", description.Description); } [Fact] public void RespectsProducesProblemExtensionMethod() { // Arrange var builder = CreateBuilder(); builder.MapGet("/api/todos", () => "").ProducesProblem(StatusCodes.Status400BadRequest); var context = new ApiDescriptionProviderContext(Array.Empty<ActionDescriptor>()); var endpointDataSource = builder.DataSources.OfType<EndpointDataSource>().Single(); var hostEnvironment = new HostEnvironment { ApplicationName = nameof(EndpointMetadataApiDescriptionProviderTest) }; var provider = CreateEndpointMetadataApiDescriptionProvider(endpointDataSource); // Act provider.OnProvidersExecuting(context); // Assert var apiDescription = Assert.Single(context.Results); var responseTypes = Assert.Single(apiDescription.SupportedResponseTypes); Assert.Equal(typeof(ProblemDetails), responseTypes.Type); } [Fact] public void RespectsProducesWithGroupNameExtensionMethod() { // Arrange var endpointGroupName = "SomeEndpointGroupName"; var builder = CreateBuilder(); builder.MapGet("/api/todos", () => "").Produces<InferredJsonClass>().WithGroupName(endpointGroupName); var context = new ApiDescriptionProviderContext(Array.Empty<ActionDescriptor>()); var endpointDataSource = builder.DataSources.OfType<EndpointDataSource>().Single(); var hostEnvironment = new HostEnvironment { ApplicationName = nameof(EndpointMetadataApiDescriptionProviderTest) }; var provider = CreateEndpointMetadataApiDescriptionProvider(endpointDataSource); // Act provider.OnProvidersExecuting(context); // Assert var apiDescription = Assert.Single(context.Results); var responseTypes = Assert.Single(apiDescription.SupportedResponseTypes); Assert.Equal(typeof(InferredJsonClass), responseTypes.Type); Assert.Equal(endpointGroupName, apiDescription.GroupName); } [Fact] public void RespectsExcludeFromDescription() { // Arrange var builder = CreateBuilder(); builder.MapGet("/api/todos", () => "").Produces<InferredJsonClass>().ExcludeFromDescription(); var context = new ApiDescriptionProviderContext(Array.Empty<ActionDescriptor>()); var endpointDataSource = builder.DataSources.OfType<EndpointDataSource>().Single(); var hostEnvironment = new HostEnvironment { ApplicationName = nameof(EndpointMetadataApiDescriptionProviderTest) }; var provider = CreateEndpointMetadataApiDescriptionProvider(endpointDataSource); // Act provider.OnProvidersExecuting(context); // Assert Assert.Empty(context.Results); } [Fact] public void HandlesProducesWithProducesProblem() { // Arrange var builder = CreateBuilder(); builder.MapGet("/api/todos", () => "") .Produces<InferredJsonClass>(StatusCodes.Status200OK) .ProducesValidationProblem() .ProducesProblem(StatusCodes.Status404NotFound) .ProducesProblem(StatusCodes.Status409Conflict); var context = new ApiDescriptionProviderContext(Array.Empty<ActionDescriptor>()); var endpointDataSource = builder.DataSources.OfType<EndpointDataSource>().Single(); var hostEnvironment = new HostEnvironment { ApplicationName = nameof(EndpointMetadataApiDescriptionProviderTest) }; var provider = CreateEndpointMetadataApiDescriptionProvider(endpointDataSource); // Act provider.OnProvidersExecuting(context); provider.OnProvidersExecuted(context); // Assert Assert.Collection( context.Results.SelectMany(r => r.SupportedResponseTypes).OrderBy(r => r.StatusCode), responseType => { Assert.Equal(typeof(InferredJsonClass), responseType.Type); Assert.Equal(200, responseType.StatusCode); Assert.Equal(new[] { "application/json" }, GetSortedMediaTypes(responseType)); }, responseType => { Assert.Equal(typeof(HttpValidationProblemDetails), responseType.Type); Assert.Equal(400, responseType.StatusCode); Assert.Equal(new[] { "application/problem+json" }, GetSortedMediaTypes(responseType)); }, responseType => { Assert.Equal(typeof(ProblemDetails), responseType.Type); Assert.Equal(404, responseType.StatusCode); Assert.Equal(new[] { "application/problem+json" }, GetSortedMediaTypes(responseType)); }, responseType => { Assert.Equal(typeof(ProblemDetails), responseType.Type); Assert.Equal(409, responseType.StatusCode); Assert.Equal(new[] { "application/problem+json" }, GetSortedMediaTypes(responseType)); }); } [Fact] public void HandleMultipleProduces() { // Arrange var builder = CreateBuilder(); builder.MapGet("/api/todos", () => "") .Produces<InferredJsonClass>(StatusCodes.Status200OK) .Produces<InferredJsonClass>(StatusCodes.Status201Created); var context = new ApiDescriptionProviderContext(Array.Empty<ActionDescriptor>()); var endpointDataSource = builder.DataSources.OfType<EndpointDataSource>().Single(); var hostEnvironment = new HostEnvironment { ApplicationName = nameof(EndpointMetadataApiDescriptionProviderTest) }; var provider = CreateEndpointMetadataApiDescriptionProvider(endpointDataSource); // Act provider.OnProvidersExecuting(context); provider.OnProvidersExecuted(context); // Assert Assert.Collection( context.Results.SelectMany(r => r.SupportedResponseTypes).OrderBy(r => r.StatusCode), responseType => { Assert.Equal(typeof(InferredJsonClass), responseType.Type); Assert.Equal(200, responseType.StatusCode); Assert.Equal(new[] { "application/json" }, GetSortedMediaTypes(responseType)); }, responseType => { Assert.Equal(typeof(InferredJsonClass), responseType.Type); Assert.Equal(201, responseType.StatusCode); Assert.Equal(new[] { "application/json" }, GetSortedMediaTypes(responseType)); }); } [Fact] public void HandleAcceptsMetadata() { // Arrange var builder = CreateBuilder(); builder.MapPost("/api/todos", () => "") .Accepts<string>("application/json", "application/xml"); var context = new ApiDescriptionProviderContext(Array.Empty<ActionDescriptor>()); var endpointDataSource = builder.DataSources.OfType<EndpointDataSource>().Single(); var hostEnvironment = new HostEnvironment { ApplicationName = nameof(EndpointMetadataApiDescriptionProviderTest) }; var provider = CreateEndpointMetadataApiDescriptionProvider(endpointDataSource); // Act provider.OnProvidersExecuting(context); provider.OnProvidersExecuted(context); // Assert Assert.Collection( context.Results.SelectMany(r => r.SupportedRequestFormats), requestType => { Assert.Equal("application/json", requestType.MediaType); }, requestType => { Assert.Equal("application/xml", requestType.MediaType); }); } [Fact] public void HandleAcceptsMetadataWithTypeParameter() { // Arrange var builder = new TestEndpointRouteBuilder(new ApplicationBuilder(null)); builder.MapPost("/api/todos", (InferredJsonClass inferredJsonClass) => "") .Accepts(typeof(InferredJsonClass), "application/json"); var context = new ApiDescriptionProviderContext(Array.Empty<ActionDescriptor>()); var endpointDataSource = builder.DataSources.OfType<EndpointDataSource>().Single(); var hostEnvironment = new HostEnvironment { ApplicationName = nameof(EndpointMetadataApiDescriptionProviderTest) }; var provider = CreateEndpointMetadataApiDescriptionProvider(endpointDataSource); // Act provider.OnProvidersExecuting(context); provider.OnProvidersExecuted(context); // Assert var parameterDescriptions = context.Results.SelectMany(r => r.ParameterDescriptions); var bodyParameterDescription = parameterDescriptions.Single(); Assert.Equal(typeof(InferredJsonClass), bodyParameterDescription.Type); Assert.Equal(typeof(InferredJsonClass).Name, bodyParameterDescription.Name); Assert.True(bodyParameterDescription.IsRequired); } [Fact] public void FavorsProducesMetadataOverAttribute() { // Arrange var builder = CreateBuilder(); builder.MapGet("/api/todos", [ProducesResponseType(typeof(List<string>), StatusCodes.Status200OK)]() => "") .Produces<InferredJsonClass>(StatusCodes.Status200OK); var context = new ApiDescriptionProviderContext(Array.Empty<ActionDescriptor>()); var endpointDataSource = builder.DataSources.OfType<EndpointDataSource>().Single(); var hostEnvironment = new HostEnvironment { ApplicationName = nameof(EndpointMetadataApiDescriptionProviderTest) }; var provider = CreateEndpointMetadataApiDescriptionProvider(endpointDataSource); // Act provider.OnProvidersExecuting(context); provider.OnProvidersExecuted(context); // Assert Assert.Collection( context.Results.SelectMany(r => r.SupportedResponseTypes).OrderBy(r => r.StatusCode), responseType => { Assert.Equal(typeof(InferredJsonClass), responseType.Type); Assert.Equal(200, responseType.StatusCode); Assert.Equal(new[] { "application/json" }, GetSortedMediaTypes(responseType)); }); } #nullable enable [Fact] public void HandleDefaultIAcceptsMetadataForRequiredBodyParameter() { // Arrange var services = new ServiceCollection(); var serviceProvider = services.BuildServiceProvider(); var builder = new TestEndpointRouteBuilder(new ApplicationBuilder(serviceProvider)); builder.MapPost("/api/todos", (InferredJsonClass inferredJsonClass) => ""); var context = new ApiDescriptionProviderContext(Array.Empty<ActionDescriptor>()); var endpointDataSource = builder.DataSources.OfType<EndpointDataSource>().Single(); var hostEnvironment = new HostEnvironment { ApplicationName = nameof(EndpointMetadataApiDescriptionProviderTest) }; var provider = CreateEndpointMetadataApiDescriptionProvider(endpointDataSource); // Act provider.OnProvidersExecuting(context); provider.OnProvidersExecuted(context); // Assert var parameterDescriptions = context.Results.SelectMany(r => r.ParameterDescriptions); var bodyParameterDescription = parameterDescriptions.Single(); Assert.Equal(typeof(InferredJsonClass), bodyParameterDescription.Type); Assert.Equal(typeof(InferredJsonClass).Name, bodyParameterDescription.Name); Assert.True(bodyParameterDescription.IsRequired); // Assert var requestFormats = context.Results.SelectMany(r => r.SupportedRequestFormats); var defaultRequestFormat = requestFormats.Single(); Assert.Equal("application/json", defaultRequestFormat.MediaType); } #nullable restore #nullable enable [Fact] public void HandleDefaultIAcceptsMetadataForOptionalBodyParameter() { // Arrange var services = new ServiceCollection(); var serviceProvider = services.BuildServiceProvider(); var builder = new TestEndpointRouteBuilder(new ApplicationBuilder(serviceProvider)); builder.MapPost("/api/todos", (InferredJsonClass? inferredJsonClass) => ""); var context = new ApiDescriptionProviderContext(Array.Empty<ActionDescriptor>()); var endpointDataSource = builder.DataSources.OfType<EndpointDataSource>().Single(); var hostEnvironment = new HostEnvironment { ApplicationName = nameof(EndpointMetadataApiDescriptionProviderTest) }; var provider = CreateEndpointMetadataApiDescriptionProvider(endpointDataSource); // Act provider.OnProvidersExecuting(context); provider.OnProvidersExecuted(context); // Assert var parameterDescriptions = context.Results.SelectMany(r => r.ParameterDescriptions); var bodyParameterDescription = parameterDescriptions.Single(); Assert.Equal(typeof(InferredJsonClass), bodyParameterDescription.Type); Assert.Equal(typeof(InferredJsonClass).Name, bodyParameterDescription.Name); Assert.False(bodyParameterDescription.IsRequired); // Assert var requestFormats = context.Results.SelectMany(r => r.SupportedRequestFormats); var defaultRequestFormat = requestFormats.Single(); Assert.Equal("application/json", defaultRequestFormat.MediaType); } #nullable restore #nullable enable [Fact] public void HandleIAcceptsMetadataWithConsumesAttributeAndInferredOptionalFromBodyType() { // Arrange var services = new ServiceCollection(); var serviceProvider = services.BuildServiceProvider(); var builder = new TestEndpointRouteBuilder(new ApplicationBuilder(serviceProvider)); builder.MapPost("/api/todos", [Consumes("application/xml")] (InferredJsonClass? inferredJsonClass) => ""); var context = new ApiDescriptionProviderContext(Array.Empty<ActionDescriptor>()); var endpointDataSource = builder.DataSources.OfType<EndpointDataSource>().Single(); var hostEnvironment = new HostEnvironment { ApplicationName = nameof(EndpointMetadataApiDescriptionProviderTest) }; var provider = CreateEndpointMetadataApiDescriptionProvider(endpointDataSource); // Act provider.OnProvidersExecuting(context); provider.OnProvidersExecuted(context); // Assert var parameterDescriptions = context.Results.SelectMany(r => r.ParameterDescriptions); var bodyParameterDescription = parameterDescriptions.Single(); Assert.Equal(typeof(void), bodyParameterDescription.Type); Assert.Equal(typeof(void).Name, bodyParameterDescription.Name); Assert.True(bodyParameterDescription.IsRequired); // Assert var requestFormats = context.Results.SelectMany(r => r.SupportedRequestFormats); var defaultRequestFormat = requestFormats.Single(); Assert.Equal("application/xml", defaultRequestFormat.MediaType); } #nullable restore [Fact] public void ProducesRouteInfoOnlyForRouteParameters() { var builder = CreateBuilder(); string GetName(int fromQuery, string name = "default") => $"Hello {name}!"; builder.MapGet("/api/todos/{name}", GetName); var context = new ApiDescriptionProviderContext(Array.Empty<ActionDescriptor>()); var endpointDataSource = builder.DataSources.OfType<EndpointDataSource>().Single(); var hostEnvironment = new HostEnvironment { ApplicationName = nameof(EndpointMetadataApiDescriptionProviderTest) }; var provider = new EndpointMetadataApiDescriptionProvider( endpointDataSource, hostEnvironment, new DefaultParameterPolicyFactory(Options.Create(new RouteOptions()), new TestServiceProvider()), new ServiceProviderIsService()); // Act provider.OnProvidersExecuting(context); // Assert var apiDescription = Assert.Single(context.Results); Assert.Collection(apiDescription.ParameterDescriptions, parameter => { Assert.Equal("fromQuery", parameter.Name); Assert.Null(parameter.RouteInfo); }, parameter => { Assert.Equal("name", parameter.Name); Assert.NotNull(parameter.RouteInfo); Assert.Empty(parameter.RouteInfo!.Constraints); Assert.True(parameter.RouteInfo!.IsOptional); Assert.Equal("default", parameter.RouteInfo!.DefaultValue); }); } [Fact] public void HandlesEndpointWithRouteConstraints() { var builder = CreateBuilder(); builder.MapGet("/api/todos/{name:minlength(8):guid:maxlength(20)}", (string name) => ""); var context = new ApiDescriptionProviderContext(Array.Empty<ActionDescriptor>()); var endpointDataSource = builder.DataSources.OfType<EndpointDataSource>().Single(); var hostEnvironment = new HostEnvironment { ApplicationName = nameof(EndpointMetadataApiDescriptionProviderTest) }; var provider = CreateEndpointMetadataApiDescriptionProvider(endpointDataSource); // Act provider.OnProvidersExecuting(context); // Assert var apiDescription = Assert.Single(context.Results); var parameter = Assert.Single(apiDescription.ParameterDescriptions); Assert.NotNull(parameter.RouteInfo); Assert.Collection(parameter.RouteInfo!.Constraints, constraint => Assert.IsType<MinLengthRouteConstraint>(constraint), constraint => Assert.IsType<GuidRouteConstraint>(constraint), constraint => Assert.IsType<MaxLengthRouteConstraint>(constraint)); } private static IEnumerable<string> GetSortedMediaTypes(ApiResponseType apiResponseType) { return apiResponseType.ApiResponseFormats .OrderBy(format => format.MediaType) .Select(format => format.MediaType); } private static IList<ApiDescription> GetApiDescriptions( Delegate action, string pattern = null, IEnumerable<string> httpMethods = null, string displayName = null) { var methodInfo = action.Method; var attributes = methodInfo.GetCustomAttributes(); var context = new ApiDescriptionProviderContext(Array.Empty<ActionDescriptor>()); var httpMethodMetadata = new HttpMethodMetadata(httpMethods ?? new[] { "GET" }); var metadataItems = new List<object>(attributes) { methodInfo, httpMethodMetadata }; var endpointMetadata = new EndpointMetadataCollection(metadataItems.ToArray()); var routePattern = RoutePatternFactory.Parse(pattern ?? "/"); var endpoint = new RouteEndpoint(httpContext => Task.CompletedTask, routePattern, 0, endpointMetadata, displayName); var endpointDataSource = new DefaultEndpointDataSource(endpoint); var provider = CreateEndpointMetadataApiDescriptionProvider(endpointDataSource); provider.OnProvidersExecuting(context); provider.OnProvidersExecuted(context); return context.Results; } private static EndpointMetadataApiDescriptionProvider CreateEndpointMetadataApiDescriptionProvider(EndpointDataSource endpointDataSource) => new EndpointMetadataApiDescriptionProvider( endpointDataSource, new HostEnvironment { ApplicationName = nameof(EndpointMetadataApiDescriptionProviderTest) }, new DefaultParameterPolicyFactory(Options.Create(new RouteOptions()), new TestServiceProvider()), new ServiceProviderIsService()); private static TestEndpointRouteBuilder CreateBuilder() => new TestEndpointRouteBuilder(new ApplicationBuilder(new TestServiceProvider())); private static ApiDescription GetApiDescription(Delegate action, string pattern = null, string displayName = null) => Assert.Single(GetApiDescriptions(action, pattern, displayName: displayName)); private static void TestAction() { } private static void TestActionWithDefaultValue(int foo = 42) { } private class InferredJsonClass { } private interface IInferredServiceInterface { } private interface IInferredJsonInterface { } private class ServiceProviderIsService : IServiceProviderIsService { public bool IsService(Type serviceType) => serviceType == typeof(IInferredServiceInterface); } private class HostEnvironment : IHostEnvironment { public string EnvironmentName { get; set; } public string ApplicationName { get; set; } public string ContentRootPath { get; set; } public IFileProvider ContentRootFileProvider { get; set; } } private class TestEndpointRouteBuilder : IEndpointRouteBuilder { public TestEndpointRouteBuilder(IApplicationBuilder applicationBuilder) { ApplicationBuilder = applicationBuilder ?? throw new ArgumentNullException(nameof(applicationBuilder)); DataSources = new List<EndpointDataSource>(); } public IApplicationBuilder ApplicationBuilder { get; } public IApplicationBuilder CreateApplicationBuilder() => ApplicationBuilder.New(); public ICollection<EndpointDataSource> DataSources { get; } public IServiceProvider ServiceProvider => ApplicationBuilder.ApplicationServices; } private record TryParseStringRecord(int Value) { public static bool TryParse(string value, out TryParseStringRecord result) => throw new NotImplementedException(); } private record struct TryParseStringRecordStruct(int Value) { public static bool TryParse(string value, out TryParseStringRecordStruct result) => throw new NotImplementedException(); } private record BindAsyncRecord(int Value) { public static ValueTask<BindAsyncRecord> BindAsync(HttpContext context, ParameterInfo parameter) => throw new NotImplementedException(); public static bool TryParse(string value, out BindAsyncRecord result) => throw new NotImplementedException(); } private class TestServiceProvider : IServiceProvider { public void Dispose() { } public object GetService(Type serviceType) { if (serviceType == typeof(IOptions<RouteHandlerOptions>)) { return Options.Create(new RouteHandlerOptions()); } return null; } } } }
using System; using System.IO.Abstractions; using Konnie.InzOutz; using Konnie.Model.FilesHistory; using Moq; using Newtonsoft.Json; using NUnit.Framework; namespace Konnie.Tests.Model.FilesHistory { [TestFixture] public class JsonFilePersistedFilesHistoryTests { public class FileIsDifferentTests { [Test] public void NoPreviousTaskHistoryReturnsFileIsDifferent() { var historyJsonFilePath = "thing"; var mockFileSystem = new Mock<IFileSystem>(); mockFileSystem .Setup(fs => fs.File.Exists(historyJsonFilePath)) .Returns(true); var mockHistoryFileConverter = new Mock<IHistoryFileConverter>(); mockHistoryFileConverter .Setup(h => h.LoadHistoryFile(historyJsonFilePath)) .Returns(new HistoryFile { { "TaskOne", new FileModifiedDateByAbsoluteFilePath { {"FilePath", DateTime.Now} } } }); var filesHistory = new JsonFilePersistedFilesHistory(historyJsonFilePath, "TaskTwo", null, mockFileSystem.Object, mockHistoryFileConverter.Object); filesHistory.LoadFileHistory(); Assert.That(filesHistory.FileIsDifferent("SomeOtherFilePath", DateTime.Now), Is.True); } [Test] public void HistoryIsTaskSpecificAndDoesntConfuseFilesInOtherTasks() { var historyJsonFilePath = "thing"; var mockFileSystem = new Mock<IFileSystem>(); mockFileSystem .Setup(fs => fs.File.Exists(historyJsonFilePath)) .Returns(true); var mockHistoryFileConverter = new Mock<IHistoryFileConverter>(); var taskName = "TaskOne"; var filepath = "FilePath"; var lastModified = DateTime.Now; mockHistoryFileConverter .Setup(h => h.LoadHistoryFile(historyJsonFilePath)) .Returns(new HistoryFile { { taskName, new FileModifiedDateByAbsoluteFilePath { {"OtherFilePath", lastModified} } }, { "OtherTaskName", new FileModifiedDateByAbsoluteFilePath { {filepath, lastModified} } } }); var filesHistory = new JsonFilePersistedFilesHistory(historyJsonFilePath, taskName, null, mockFileSystem.Object, mockHistoryFileConverter.Object); filesHistory.LoadFileHistory(); Assert.That(filesHistory.FileIsDifferent(filepath, lastModified), Is.True); } [Test] public void HistoryWithPreviousTaskWithNoRecordOfFileReturnsTrue() { var historyJsonFilePath = "thing"; var mockFileSystem = new Mock<IFileSystem>(); mockFileSystem .Setup(fs => fs.File.Exists(historyJsonFilePath)) .Returns(true); var mockHistoryFileConverter = new Mock<IHistoryFileConverter>(); var taskName = "TaskOne"; var filepath = "FilePath"; mockHistoryFileConverter .Setup(h => h.LoadHistoryFile(historyJsonFilePath)) .Returns(new HistoryFile { { taskName, new FileModifiedDateByAbsoluteFilePath { {"SomeOtherPath", DateTime.Now} } } }); var filesHistory = new JsonFilePersistedFilesHistory(historyJsonFilePath, taskName, null, mockFileSystem.Object, mockHistoryFileConverter.Object); filesHistory.LoadFileHistory(); Assert.That(filesHistory.FileIsDifferent(filepath, DateTime.Now), Is.True); } [Test] public void HistoryWithTaskWithPreviousFileWithDayOldModifiedDateReturnsTrue() { var historyJsonFilePath = "thing"; var mockFileSystem = new Mock<IFileSystem>(); mockFileSystem .Setup(fs => fs.File.Exists(historyJsonFilePath)) .Returns(true); var mockHistoryFileConverter = new Mock<IHistoryFileConverter>(); var taskName = "TaskOne"; var filepath = "FilePath"; var lastModified = DateTime.Now; mockHistoryFileConverter .Setup(h => h.LoadHistoryFile(historyJsonFilePath)) .Returns(new HistoryFile { { taskName, new FileModifiedDateByAbsoluteFilePath { {filepath, lastModified} } } }); var filesHistory = new JsonFilePersistedFilesHistory(historyJsonFilePath, taskName, null, mockFileSystem.Object, mockHistoryFileConverter.Object); filesHistory.LoadFileHistory(); Assert.That(filesHistory.FileIsDifferent(filepath, lastModified.AddDays(1)), Is.True); } } public class InitialisingTests { /// <summary> /// If the file exists but can't be serialised into a HistoryFile object then we want to ignore this /// error and write over the file when commiting. /// </summary> [Test] public void JsonExceptionThrownIsIgnored() { var historyFilePath = "filePath"; var mockFileSystem = new Mock<IFileSystem>(); mockFileSystem .Setup(fs => fs.File.Exists(historyFilePath)) .Returns(true); var mockHistoryFileConverter = new Mock<IHistoryFileConverter>(); mockHistoryFileConverter .Setup(h => h.LoadHistoryFile(historyFilePath)) .Throws<JsonReaderException>(); var jsonFilePersistedHistory = new JsonFilePersistedFilesHistory(historyFilePath, "SomeTask", null, mockFileSystem.Object, mockHistoryFileConverter.Object); jsonFilePersistedHistory.LoadFileHistory(); } [Test] public void DoesntThrowIfHistoryFileDoesntExist() { var mockFileSystem = new Mock<IFileSystem>(); var historyFilePath = "filePath"; mockFileSystem.Setup(fs => fs.File.Exists(historyFilePath)).Returns(false); var jsonFilePersistedHistory = new JsonFilePersistedFilesHistory(historyFilePath, "SomeTask", null, mockFileSystem.Object); jsonFilePersistedHistory.LoadFileHistory(); } } public class UpdateHistoryTests { [Test] public void HistoryUpdatesFileValueItHasSeenBefore() { var historyJsonFilePath = "thing"; var mockFileSystem = new Mock<IFileSystem>(); mockFileSystem .Setup(fs => fs.File.Exists(historyJsonFilePath)) .Returns(true); var mockHistoryFileConverter = new Mock<IHistoryFileConverter>(); var taskName = "TaskOne"; var filepath = "FilePath"; var lastModified = DateTime.Now; mockHistoryFileConverter .Setup(h => h.LoadHistoryFile(historyJsonFilePath)) .Returns(new HistoryFile { { taskName, new FileModifiedDateByAbsoluteFilePath { {filepath, lastModified} } } }); var filesHistory = new JsonFilePersistedFilesHistory(historyJsonFilePath, taskName, null, mockFileSystem.Object, mockHistoryFileConverter.Object); filesHistory.LoadFileHistory(); Assert.That(filesHistory.FileIsDifferent(filepath, lastModified.AddDays(1)), Is.True); filesHistory.UpdateHistory(filepath, lastModified.AddDays(1)); Assert.That(filesHistory.FileIsDifferent(filepath, lastModified.AddDays(1)), Is.False); } [Test] public void HistoryUpdatesFileValueItHasntSeenBefore() { var historyJsonFilePath = "thing"; var mockFileSystem = new Mock<IFileSystem>(); mockFileSystem .Setup(fs => fs.File.Exists(historyJsonFilePath)) .Returns(true); var mockHistoryFileConverter = new Mock<IHistoryFileConverter>(); var taskName = "TaskOne"; var filepath = "FilePath"; var lastModified = DateTime.Now; mockHistoryFileConverter .Setup(h => h.LoadHistoryFile(historyJsonFilePath)) .Returns(new HistoryFile { { taskName, new FileModifiedDateByAbsoluteFilePath() } }); var filesHistory = new JsonFilePersistedFilesHistory(historyJsonFilePath, taskName, null, mockFileSystem.Object, mockHistoryFileConverter.Object); filesHistory.LoadFileHistory(); Assert.That(filesHistory.FileIsDifferent(filepath, lastModified.AddDays(1)), Is.True); filesHistory.UpdateHistory(filepath, lastModified.AddDays(1)); Assert.That(filesHistory.FileIsDifferent(filepath, lastModified.AddDays(1)), Is.False); } } public class CommitChangesTests { [Test] public void CallsToHistoryFileConverterToSaveChanges() { var historyJsonFilePath = "thing"; var mockFileSystem = new Mock<IFileSystem>(); mockFileSystem .Setup(fs => fs.File.Exists(historyJsonFilePath)) .Returns(true); var mockHistoryFileConverter = new Mock<IHistoryFileConverter>(); var taskName = "TaskOne"; var historyFile = new HistoryFile { { taskName, new FileModifiedDateByAbsoluteFilePath { {"SomeFile", DateTime.Now } } } }; mockHistoryFileConverter .Setup(h => h.LoadHistoryFile(historyJsonFilePath)) .Returns(historyFile); var filesHistory = new JsonFilePersistedFilesHistory(historyJsonFilePath, taskName, null, mockFileSystem.Object, mockHistoryFileConverter.Object); filesHistory.LoadFileHistory(); filesHistory.CommitChanges(); mockHistoryFileConverter.Verify(h => h.SaveHistoryFile(historyFile, historyJsonFilePath)); } } } }
/*************************************************************************** * PluginFactory.cs * * Copyright (C) 2006 Novell, Inc. * Written by Aaron Bockover <[email protected]> ****************************************************************************/ /* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.Reflection; using Banshee.Base; namespace Banshee.Plugins { public enum PluginFactoryType { Type, Instance } public delegate void GenericEventHandler<U, V>(U o, V args); public class PluginFactoryEventArgs<T> where T : IPlugin { private T plugin; private Type type; public PluginFactoryEventArgs(T plugin) { this.plugin = plugin; this.type = plugin.GetType(); } public PluginFactoryEventArgs(Type type) { this.type = type; } public T Plugin { get { return plugin; } } public Type Type { get { return type; } } } public class PluginFactory<T> : IDisposable, IEnumerable<T>, IEnumerable where T : IPlugin { private List<T> plugin_instances = new List<T>(); private List<Type> plugin_types = new List<Type>(); private List<DirectoryInfo> scan_directories = new List<DirectoryInfo>(); private string include_mask = "*.dll"; private PluginFactoryType factory_type; public event GenericEventHandler<PluginFactory<T>, PluginFactoryEventArgs<T>> PluginLoaded; public PluginFactory() : this(PluginFactoryType.Instance) { } public PluginFactory(PluginFactoryType factoryType) { factory_type = factoryType; } public void Dispose() { foreach(T t in this) { t.Dispose(); } } public void RemovePlugin(T plugin) { plugin_instances.Remove(plugin); RemovePlugin(plugin.GetType()); } public void RemovePlugin(Type type) { plugin_types.Remove(type); } public void AddScanDirectory(DirectoryInfo directory) { AddScanDirectory(directory, false); } public void AddScanDirectory(DirectoryInfo directory, bool recurse) { if(directory == null || !directory.Exists) { return; } scan_directories.Add(directory); if(!recurse) { return; } foreach(DirectoryInfo sub_directory in directory.GetDirectories()) { AddScanDirectory(sub_directory, recurse); } } public void AddScanDirectory(string directory) { AddScanDirectory(directory, false); } public void AddScanDirectory(string directory, bool recurse) { AddScanDirectory(new DirectoryInfo(directory), recurse); } public void AddScanDirectoryFromEnvironmentVariable(string env) { string env_path = Environment.GetEnvironmentVariable(env); if(env_path == null || env_path == String.Empty) { return; } try { AddScanDirectory(new DirectoryInfo(env_path), true); } catch { } } public void LoadPlugins() { foreach(DirectoryInfo directory in scan_directories) { LoadPluginsFromDirectory(directory); } } public void LoadPluginsFromDirectory(DirectoryInfo directory) { try { foreach(FileInfo file in directory.GetFiles(include_mask)) { LoadPluginsFromFile(file); } } catch(DirectoryNotFoundException) { try { directory.Create(); } catch { } } } public void LoadPluginsFromFile(FileInfo file) { //Cornel under win32 everything is a damn dll :p try { Assembly asm = Assembly.LoadFrom(file.FullName); LoadPluginsFromAssembly(asm); } catch { } } public void LoadPluginsFromAssembly(Assembly assembly) { Type [] check_types = null; List<Type> non_entry_types = null; try { check_types = ReflectionUtil.ModuleGetTypes(assembly, "PluginModuleEntry"); } catch { } if(check_types == null) { check_types = assembly.GetTypes(); non_entry_types = new List<Type>(); } foreach(Type type in check_types) { if(!type.IsSubclassOf(typeof(T)) || type.IsAbstract) { continue; } bool already_loaded = false; foreach(Type loaded_type in plugin_types) { if(loaded_type == type) { already_loaded = true; break; } } if(already_loaded) { continue; } if(non_entry_types != null) { non_entry_types.Add(type); } LoadPluginFromType(type); } if(non_entry_types != null && non_entry_types.Count > 0) { Console.WriteLine( "Plugin module: {0}\n" + "Does not implement PluginModuleEntry.GetTypes. For faster startup performance\n" + "and to lower memory consumption, it is recommended that the following code\n" + "be added to the plugin module:\n", assembly.Location); Console.WriteLine("public static class PluginModuleEntry"); Console.WriteLine("{"); Console.WriteLine(" public static Type [] GetTypes()"); Console.WriteLine(" {"); Console.WriteLine(" return new Type [] {"); for(int i = 0; i < non_entry_types.Count; i++) { Console.WriteLine(" typeof({0}){1}", non_entry_types[i].FullName, i < non_entry_types.Count -1 ? "," : String.Empty); } Console.WriteLine(" };"); Console.WriteLine(" }"); Console.WriteLine("}\n"); } else if(non_entry_types != null) { try { Console.WriteLine( "Assembly.GetTypes() was called on assembly:\n" + "{0}\n\n" + "This assembly does not include any {1} types\n" + "and should probably be filtered from being passed to\n" + "PluginFactory.LoadPluginsFromAssembly to prevent memory\n" + "loss and performance issues.\n\n", assembly.Location, typeof(T).FullName); } catch { } } } public void LoadPluginFromType(Type type) { if(factory_type == PluginFactoryType.Instance) { try { T plugin = (T)Activator.CreateInstance(type); plugin_instances.Add(plugin); plugin_types.Add(type); OnPluginLoaded(plugin); } catch (Exception ex){ Console.WriteLine(ex.Message); } } else { plugin_types.Add(type); OnPluginLoaded(type); } } protected void OnPluginLoaded(T plugin) { GenericEventHandler<PluginFactory<T>, PluginFactoryEventArgs<T>> handler = PluginLoaded; if(handler != null) { handler(this, new PluginFactoryEventArgs<T>(plugin)); } } protected void OnPluginLoaded(Type type) { GenericEventHandler<PluginFactory<T>, PluginFactoryEventArgs<T>> handler = PluginLoaded; if(handler != null) { handler(this, new PluginFactoryEventArgs<T>(type)); } } public IEnumerator<T> GetEnumerator() { return plugin_instances.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return plugin_instances.GetEnumerator(); } public IEnumerable<Type> PluginTypes { get { return plugin_types; } } public string IncludeMask { get { return include_mask; } set { include_mask = value; } } } }
// 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>CampaignConversionGoal</c> resource.</summary> public sealed partial class CampaignConversionGoalName : gax::IResourceName, sys::IEquatable<CampaignConversionGoalName> { /// <summary>The possible contents of <see cref="CampaignConversionGoalName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>customers/{customer_id}/campaignConversionGoals/{campaign_id}~{category}~{source}</c>. /// </summary> CustomerCampaignCategorySource = 1, } private static gax::PathTemplate s_customerCampaignCategorySource = new gax::PathTemplate("customers/{customer_id}/campaignConversionGoals/{campaign_id_category_source}"); /// <summary>Creates a <see cref="CampaignConversionGoalName"/> 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="CampaignConversionGoalName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static CampaignConversionGoalName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new CampaignConversionGoalName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="CampaignConversionGoalName"/> with the pattern /// <c>customers/{customer_id}/campaignConversionGoals/{campaign_id}~{category}~{source}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="categoryId">The <c>Category</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// A new instance of <see cref="CampaignConversionGoalName"/> constructed from the provided ids. /// </returns> public static CampaignConversionGoalName FromCustomerCampaignCategorySource(string customerId, string campaignId, string categoryId, string sourceId) => new CampaignConversionGoalName(ResourceNameType.CustomerCampaignCategorySource, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), categoryId: gax::GaxPreconditions.CheckNotNullOrEmpty(categoryId, nameof(categoryId)), sourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="CampaignConversionGoalName"/> with pattern /// <c>customers/{customer_id}/campaignConversionGoals/{campaign_id}~{category}~{source}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="categoryId">The <c>Category</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CampaignConversionGoalName"/> with pattern /// <c>customers/{customer_id}/campaignConversionGoals/{campaign_id}~{category}~{source}</c>. /// </returns> public static string Format(string customerId, string campaignId, string categoryId, string sourceId) => FormatCustomerCampaignCategorySource(customerId, campaignId, categoryId, sourceId); /// <summary> /// Formats the IDs into the string representation of this <see cref="CampaignConversionGoalName"/> with pattern /// <c>customers/{customer_id}/campaignConversionGoals/{campaign_id}~{category}~{source}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="categoryId">The <c>Category</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CampaignConversionGoalName"/> with pattern /// <c>customers/{customer_id}/campaignConversionGoals/{campaign_id}~{category}~{source}</c>. /// </returns> public static string FormatCustomerCampaignCategorySource(string customerId, string campaignId, string categoryId, string sourceId) => s_customerCampaignCategorySource.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(categoryId, nameof(categoryId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)))}"); /// <summary> /// Parses the given resource name string into a new <see cref="CampaignConversionGoalName"/> 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}/campaignConversionGoals/{campaign_id}~{category}~{source}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="campaignConversionGoalName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="CampaignConversionGoalName"/> if successful.</returns> public static CampaignConversionGoalName Parse(string campaignConversionGoalName) => Parse(campaignConversionGoalName, false); /// <summary> /// Parses the given resource name string into a new <see cref="CampaignConversionGoalName"/> 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}/campaignConversionGoals/{campaign_id}~{category}~{source}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="campaignConversionGoalName">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="CampaignConversionGoalName"/> if successful.</returns> public static CampaignConversionGoalName Parse(string campaignConversionGoalName, bool allowUnparsed) => TryParse(campaignConversionGoalName, allowUnparsed, out CampaignConversionGoalName 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="CampaignConversionGoalName"/> 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}/campaignConversionGoals/{campaign_id}~{category}~{source}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="campaignConversionGoalName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="CampaignConversionGoalName"/>, 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 campaignConversionGoalName, out CampaignConversionGoalName result) => TryParse(campaignConversionGoalName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CampaignConversionGoalName"/> 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}/campaignConversionGoals/{campaign_id}~{category}~{source}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="campaignConversionGoalName">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="CampaignConversionGoalName"/>, 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 campaignConversionGoalName, bool allowUnparsed, out CampaignConversionGoalName result) { gax::GaxPreconditions.CheckNotNull(campaignConversionGoalName, nameof(campaignConversionGoalName)); gax::TemplatedResourceName resourceName; if (s_customerCampaignCategorySource.TryParseName(campaignConversionGoalName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerCampaignCategorySource(resourceName[0], split1[0], split1[1], split1[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(campaignConversionGoalName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private CampaignConversionGoalName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string campaignId = null, string categoryId = null, string customerId = null, string sourceId = null) { Type = type; UnparsedResource = unparsedResourceName; CampaignId = campaignId; CategoryId = categoryId; CustomerId = customerId; SourceId = sourceId; } /// <summary> /// Constructs a new instance of a <see cref="CampaignConversionGoalName"/> class from the component parts of /// pattern <c>customers/{customer_id}/campaignConversionGoals/{campaign_id}~{category}~{source}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="categoryId">The <c>Category</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param> public CampaignConversionGoalName(string customerId, string campaignId, string categoryId, string sourceId) : this(ResourceNameType.CustomerCampaignCategorySource, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), categoryId: gax::GaxPreconditions.CheckNotNullOrEmpty(categoryId, nameof(categoryId)), sourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId))) { } /// <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>Campaign</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CampaignId { get; } /// <summary> /// The <c>Category</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CategoryId { 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>Source</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string SourceId { 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.CustomerCampaignCategorySource: return s_customerCampaignCategorySource.Expand(CustomerId, $"{CampaignId}~{CategoryId}~{SourceId}"); 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 CampaignConversionGoalName); /// <inheritdoc/> public bool Equals(CampaignConversionGoalName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(CampaignConversionGoalName a, CampaignConversionGoalName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(CampaignConversionGoalName a, CampaignConversionGoalName b) => !(a == b); } public partial class CampaignConversionGoal { /// <summary> /// <see cref="CampaignConversionGoalName"/>-typed view over the <see cref="ResourceName"/> resource name /// property. /// </summary> internal CampaignConversionGoalName ResourceNameAsCampaignConversionGoalName { get => string.IsNullOrEmpty(ResourceName) ? null : CampaignConversionGoalName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="CampaignName"/>-typed view over the <see cref="Campaign"/> resource name property. /// </summary> internal CampaignName CampaignAsCampaignName { get => string.IsNullOrEmpty(Campaign) ? null : CampaignName.Parse(Campaign, allowUnparsed: true); set => Campaign = value?.ToString() ?? ""; } } }
using System; using System.Collections.Generic; using System.Text; using FlatRedBall; using MathFunctions = FlatRedBall.Math.MathFunctions; using FlatRedBall.Math.Geometry; using FlatRedBall.Graphics; using FlatRedBall.Instructions.Pause; using FlatRedBall.Instructions.Interpolation; using System.Reflection; using FlatRedBall.Math; using System.Collections.ObjectModel; using Microsoft.Xna.Framework; namespace FlatRedBall.Instructions { #region InterpolationType Enum public enum InterpolatorType { Linear, ClosestRotation } #endregion public static class InstructionManager { #region Fields static object syncLock = new object(); static Queue<Instruction> instructionQueue = new Queue<Instruction>(); static bool mIsExecutingInstructions = true; static InstructionList mInstructions = new InstructionList(); //static ListBuffer<Instruction> mInstructionBuffer; static InstructionList mUnpauseInstructions = new InstructionList(); static Dictionary<Type, IInterpolator> mInterpolators = new Dictionary<Type, IInterpolator>(); static Dictionary<Type, IInterpolator> mRotationInterpolators = new Dictionary<Type, IInterpolator>(); static List<VelocityValueRelationship> mVelocityValueRelationships = new List<VelocityValueRelationship>(); static List<AnimationValueRelationship> mAnimationValueRelationships = new List<AnimationValueRelationship>(); static List<AbsoluteRelativeValueRelationship> mAbsoluteRelativeValueRelationships = new List<AbsoluteRelativeValueRelationship>(); static List<string> mRotationMembers = new List<string>(); #endregion #region Properties #region XML Docs /// <summary> /// Holds instructions which will be executed by the InstructionManager /// in its Update method (called automatically by FlatRedBallServices). /// </summary> /// <remarks> /// Instructions for managed PositionedObjects like Sprites and Text objects /// should be added to the object's internal InstructionList. This prevents instructions /// from referencing removed objects and helps with debugging. This list should only be used /// on un-managed objects or for instructions which do not associate with a particular object. /// </remarks> #endregion public static InstructionList Instructions { get { return mInstructions; } } public static bool IsEnginePaused { get { return mUnpauseInstructions.Count != 0; } } #region XML Docs /// <summary> /// Whether the (automatically called) Update method executes instructions. Default true. /// </summary> #endregion public static bool IsExecutingInstructions { get { return mIsExecutingInstructions; } set { mIsExecutingInstructions = value; } } #if SILVERLIGHT #else public static ReadOnlyCollection<VelocityValueRelationship> VelocityValueRelationships { get; private set; } public static ReadOnlyCollection<AbsoluteRelativeValueRelationship> AbsoluteRelativeValueRelationships { get; private set; } #endif #endregion #region Methods #region Constructor/Initialize // This would normally be private, but we're making // it public because Glue doesn't do the regular engine // setup, but it still needs the information that is created // in this Class' Initialize calls. public static void Initialize() { //mInstructionBuffer = new ListBuffer<Instruction>(mInstructions); CreateInterpolators(); CreateValueRelationships(); CreateRotationMembers(); } #endregion #region Public Methods public static void AddSafe(Instruction instruction) { lock (syncLock) { instructionQueue.Enqueue(instruction); } } public static void AddSafe(Action action) { lock (syncLock) { instructionQueue.Enqueue(new DelegateInstruction(action)); } } public static void Add(Instruction instruction) { mInstructions.Add(instruction); } public static void ExecuteInstructionsOnConsideringTime(IInstructable instructable) { ExecuteInstructionsOnConsideringTime(instructable, TimeManager.CurrentTime); } public static void ExecuteInstructionsOnConsideringTime(IInstructable instructable, double currentTime) { Instructions.Instruction instruction; while (instructable.Instructions.Count > 0 && instructable.Instructions[0].TimeToExecute <= currentTime) { instruction = instructable.Instructions[0]; instruction.Execute(); // The instruction may have cleared the InstructionList, so we need to test if it did. if (instructable.Instructions.Count < 1) continue; if (instruction.CycleTime == 0) instructable.Instructions.Remove(instruction); else { instruction.TimeToExecute += instruction.CycleTime; instructable.Instructions.InsertionSortAscendingTimeToExecute(); } } } public static Type GetTypeForMember(Type type, string member) { PropertyInfo propertyInfo = type.GetProperty(member); if (propertyInfo != null) { return propertyInfo.PropertyType; } FieldInfo fieldInfo = type.GetField(member); if (fieldInfo != null) { return fieldInfo.FieldType; } return null; } public static AnimationValueRelationship GetAnimationValueRelationship(string frameMemberName) { for (int i = 0; i < mAnimationValueRelationships.Count; i++) { if (mAnimationValueRelationships[i].Frame == frameMemberName) { return mAnimationValueRelationships[i]; } } return null; } public static string GetStateForVelocity(string velocity) { for (int i = 0; i < mVelocityValueRelationships.Count; i++) { if (mVelocityValueRelationships[i].Velocity == velocity) return mVelocityValueRelationships[i].State; } return null; } public static string GetRelativeForAbsolute(string absolute) { for (int i = 0; i < mAbsoluteRelativeValueRelationships.Count; i++) { if (mAbsoluteRelativeValueRelationships[i].AbsoluteValue == absolute) { return mAbsoluteRelativeValueRelationships[i].RelativeValue; } } return null; } public static string GetVelocityForState(string state) { for (int i = 0; i < mVelocityValueRelationships.Count; i++) { if (mVelocityValueRelationships[i].State == state) return mVelocityValueRelationships[i].Velocity; } return null; } public static bool IsObjectReferencedByInstructions(object objectToReference) { for (int i = 0; i < mInstructions.Count; i++) { if (mInstructions[i].Target == objectToReference) { return true; } } return false; } public static bool IsRotationMember(string rotationMember) { return mRotationMembers.Contains(rotationMember); } #region Move and Relative Move public static void MoveThrough<T>(FlatRedBall.PositionedObject positionedObject, IList<T> list, float velocity) where T : IPositionable { double time = TimeManager.CurrentTime; float lastX = positionedObject.X; float lastY = positionedObject.Y; float lastZ = positionedObject.Z; float distanceX = 0; float distanceY = 0; float distanceZ = 0; double totalDistance = 0; Vector3 newVelocity = new Vector3(); foreach (IPositionable positionable in list) { distanceX = positionable.X - lastX; distanceY = positionable.Y - lastY; distanceZ = positionable.Z - lastZ; totalDistance = (float)System.Math.Sqrt( distanceX * distanceX + distanceY * distanceY + distanceZ * distanceZ); newVelocity.X = distanceX; newVelocity.Y = distanceY; newVelocity.Z = distanceZ; newVelocity.Normalize(); newVelocity *= velocity; positionedObject.Instructions.Add(new Instruction<FlatRedBall.PositionedObject, Vector3>( positionedObject, "Velocity", newVelocity, time)); lastX = positionable.X; lastY = positionable.Y; lastZ = positionable.Z; time += totalDistance / velocity; } positionedObject.Instructions.Add(new Instruction<FlatRedBall.PositionedObject, Vector3>( positionedObject, "Velocity", new Vector3(), time)); } public static void MoveToAccurate(FlatRedBall.PositionedObject positionedObject, float x, float y, float z, double secondsToTake) { if (secondsToTake != 0.0f) { positionedObject.XVelocity = (x - positionedObject.X) / (float)secondsToTake; positionedObject.YVelocity = (y - positionedObject.Y) / (float)secondsToTake; positionedObject.ZVelocity = (z - positionedObject.Z) / (float)secondsToTake; double timeToExecute = TimeManager.CurrentTime + secondsToTake; positionedObject.Instructions.Add( new Instruction<FlatRedBall.PositionedObject, float>(positionedObject, "XVelocity", 0, timeToExecute)); positionedObject.Instructions.Add( new Instruction<FlatRedBall.PositionedObject, float>(positionedObject, "YVelocity", 0, timeToExecute)); positionedObject.Instructions.Add( new Instruction<FlatRedBall.PositionedObject, float>(positionedObject, "ZVelocity", 0, timeToExecute)); positionedObject.Instructions.Add( new Instruction<FlatRedBall.PositionedObject, float>(positionedObject, "X", x, timeToExecute)); positionedObject.Instructions.Add( new Instruction<FlatRedBall.PositionedObject, float>(positionedObject, "Y", y, timeToExecute)); positionedObject.Instructions.Add( new Instruction<FlatRedBall.PositionedObject, float>(positionedObject, "Z", z, timeToExecute)); } else { positionedObject.X = x; positionedObject.Y = y; positionedObject.Z = z; } } public static void MoveTo(FlatRedBall.PositionedObject positionedObject, float x, float y, float z, double secondsToTake) { if (secondsToTake != 0.0f) { positionedObject.XVelocity = (x - positionedObject.X) / (float)secondsToTake; positionedObject.YVelocity = (y - positionedObject.Y) / (float)secondsToTake; positionedObject.ZVelocity = (z - positionedObject.Z) / (float)secondsToTake; double timeToExecute = TimeManager.CurrentTime + secondsToTake; positionedObject.Instructions.Add( new Instruction<FlatRedBall.PositionedObject, float>(positionedObject, "XVelocity", 0, timeToExecute)); positionedObject.Instructions.Add( new Instruction<FlatRedBall.PositionedObject, float>(positionedObject, "YVelocity", 0, timeToExecute)); positionedObject.Instructions.Add( new Instruction<FlatRedBall.PositionedObject, float>(positionedObject, "ZVelocity", 0, timeToExecute)); } else { positionedObject.X = x; positionedObject.Y = y; positionedObject.Z = z; } } #endregion #region Pause Methods internal static PositionedObjectList<FlatRedBall.PositionedObject> PositionedObjectsIgnoringPausing = new PositionedObjectList<FlatRedBall.PositionedObject>(); public static void IgnorePausingFor(FlatRedBall.PositionedObject positionedObject) { // This function needs to tolerate // the same object being added multiple // times. The reason is that an Entity in // Glue may set one of its objects to be ignored // in pausing, but then the object itself may also // be set to be ignored. if (!PositionedObjectsIgnoringPausing.Contains(positionedObject)) { PositionedObjectsIgnoringPausing.Add(positionedObject); } } public static void IgnorePausingFor<T>(IList<T> list) where T : FlatRedBall.PositionedObject { for (int i = 0; i < list.Count; i++) { IgnorePausingFor(list[i]); } } public static void IgnorePausingFor(Scene scene) { IgnorePausingFor(scene.SpriteFrames); IgnorePausingFor(scene.Sprites); IgnorePausingFor(scene.Texts); } public static void IgnorePausingFor(ShapeCollection shapeCollection) { IgnorePausingFor(shapeCollection.AxisAlignedCubes); IgnorePausingFor(shapeCollection.AxisAlignedRectangles); IgnorePausingFor(shapeCollection.Capsule2Ds); IgnorePausingFor(shapeCollection.Circles); IgnorePausingFor(shapeCollection.Lines); IgnorePausingFor(shapeCollection.Polygons); IgnorePausingFor(shapeCollection.Spheres); } static void IgnorePausingFor<T>(PositionedObjectList<T> list) where T : FlatRedBall.PositionedObject { int count = list.Count; for (int i = 0; i < count; i++) { IgnorePausingFor(list[i]); } } public static void PauseEngine() { PauseEngine(true); } public static void PauseEngine(bool storeUnpauseInstructions) { if (mUnpauseInstructions.Count != 0) { throw new System.InvalidOperationException( "Can't execute pause since there are already instructions in the Unpause InstructionList." + " Are you causing PauseEngine twice in a row?" + " Each PauseEngine method must be followed by an UnpauseEngine before PauseEngine can be called again."); } // When the engine pauses, each manager stops // all activity and fills the unpauseInstructions // with instructions that are executed to restart activity. // Turn off sorting so we don't sort over and over and over... // Looks like we never need to turn this back on. mUnpauseInstructions.SortOnAdd = false; SpriteManager.Pause(mUnpauseInstructions); ShapeManager.Pause(mUnpauseInstructions); #if SILVERLIGHT throw new NotImplementedException(); #else TextManager.Pause(mUnpauseInstructions); #endif InstructionListUnpause instructions = new InstructionListUnpause(mInstructions); mInstructions.Clear(); mUnpauseInstructions.Add(instructions); if (!storeUnpauseInstructions) { mUnpauseInstructions.Clear(); } // ... now do one sort at the end to make sure all is sorted properly // Actually, no, don't sort, it's not necessary! We're going to execute // everything anyway. //mUnpauseInstructions.Sort((a, b) => a.TimeToExecute.CompareTo(b)); } public static void FindAndExecuteUnpauseInstruction( object target ) { for( int iCurInstruction = mUnpauseInstructions.Count - 1; iCurInstruction > -1; iCurInstruction-- ) { if( mUnpauseInstructions[ iCurInstruction ].Target == target ) { mUnpauseInstructions[ iCurInstruction ].Execute(); mUnpauseInstructions.RemoveAt( iCurInstruction ); break; } } } public static void UnpauseEngine() { foreach (Instruction instruction in mUnpauseInstructions) { instruction.Execute(); } mUnpauseInstructions.Clear(); } #endregion public static void Remove(Instruction instruction) { mInstructions.Remove(instruction); } #region XML Docs /// <summary> /// Sets a member on an uncasted object. If the type of objectToSetOn is known, use /// LateBinder for performance and safety reasons. /// </summary> /// <param name="objectToSetOn">The object whose field or property should be set.</param> /// <param name="memberName">The name of the field or property to set.</param> /// <param name="valueToSet">The value of the field or property to set.</param> #endregion public static void UncastedSetMember(object objectToSetOn, string memberName, object valueToSet) { if (objectToSetOn == null) { throw new ArgumentNullException("Argument " + objectToSetOn + " cannot be null"); } Type typeOfObject = objectToSetOn.GetType(); IEnumerable<PropertyInfo> properties = typeOfObject.GetProperties(); foreach (PropertyInfo propertyInfo in properties) { if (propertyInfo.Name == memberName) { propertyInfo.SetValue(objectToSetOn, valueToSet, null); return; // end here since it's been set - there's no reason to keep going on to fields } } var fields = typeOfObject.GetFields(); foreach (FieldInfo field in fields) { if (field.Name == memberName) { field.SetValue(objectToSetOn, valueToSet); } } } #endregion #region Internal static internal IInterpolator GetInterpolator(Type type) { return GetInterpolator(type, InterpolatorType.Linear); } static internal IInterpolator GetInterpolator(Type type, string memberName) { InterpolatorType interpolatorType = InterpolatorType.Linear; if (mRotationMembers.Contains(memberName)) interpolatorType = InterpolatorType.ClosestRotation; return GetInterpolator(type, interpolatorType); } static internal IInterpolator GetInterpolator(Type type, InterpolatorType interpolatorType) { Dictionary<Type, IInterpolator> interpolatorDictionary = null; switch (interpolatorType) { case InterpolatorType.Linear: interpolatorDictionary = mInterpolators; break; case InterpolatorType.ClosestRotation: interpolatorDictionary = mRotationInterpolators; break; } if (interpolatorDictionary.ContainsKey(type)) { return interpolatorDictionary[type]; } else { throw new InvalidOperationException("There is no interpolator registered for type " + type.ToString()); } } static internal bool HasInterpolatorForType(Type type) { return mInterpolators.ContainsKey(type); } #region XML Docs /// <summary> /// Executes contained instructions. /// </summary> /// <param name="currentTime">The number of seconds since the start of application execution.</param> #endregion public static void Update(double currentTime) { //Flush(); Instructions.Instruction instruction; lock (syncLock) { while (instructionQueue.Count > 0) { Add(instructionQueue.Dequeue()); } } while (mIsExecutingInstructions && mInstructions.Count > 0 && mInstructions[0].TimeToExecute <= currentTime) { instruction = mInstructions[0]; instruction.Execute(); // The instruction may have cleared the InstructionList, so we need to test if it did. if (mInstructions.Count < 1) continue; if (instruction.CycleTime == 0) mInstructions.Remove(instruction); else { instruction.TimeToExecute += instruction.CycleTime; mInstructions.InsertionSortAscendingTimeToExecute(); } } // The ScreenManager doesn't have any engine-initiated // activity, it's all initiated by custom code. However, // instructions are supposed to execute before any custom code // runs. Therefore, we're going to have these be handled here: if (Screens.ScreenManager.CurrentScreen != null) { ExecuteInstructionsOnConsideringTime(Screens.ScreenManager.CurrentScreen); } } #endregion #region Private Methods private static void CreateInterpolators() { mInterpolators.Add(typeof(float), new FloatInterpolator()); mInterpolators.Add(typeof(double), new DoubleInterpolator()); mInterpolators.Add(typeof(long), new LongInterpolator()); mInterpolators.Add(typeof(int), new IntInterpolator()); mRotationInterpolators.Add(typeof(float), new FloatAngleInterpolator()); } private static void CreateRotationMembers() { mRotationMembers.Add("RotationX"); mRotationMembers.Add("RotationY"); mRotationMembers.Add("RotationZ"); mRotationMembers.Add("RelativeRotationX"); mRotationMembers.Add("RelativeRotationY"); mRotationMembers.Add("RelativeRotationZ"); } private static void CreateValueRelationships() { #region Create the Value Relationships mVelocityValueRelationships.Add(new VelocityValueRelationship("X", "XVelocity", "XAcceleration")); mVelocityValueRelationships.Add(new VelocityValueRelationship("Y", "YVelocity", "YAcceleration")); mVelocityValueRelationships.Add(new VelocityValueRelationship("Z", "ZVelocity", "ZAcceleration")); mVelocityValueRelationships.Add(new VelocityValueRelationship("RelativeX", "RelativeXVelocity", "RelativeXAcceleration")); mVelocityValueRelationships.Add(new VelocityValueRelationship("RelativeY", "RelativeYVelocity", "RelativeYAcceleration")); mVelocityValueRelationships.Add(new VelocityValueRelationship("RelativeZ", "RelativeZVelocity", "RelativeZAcceleration")); mVelocityValueRelationships.Add(new VelocityValueRelationship("ScaleX", "ScaleXVelocity", null)); mVelocityValueRelationships.Add(new VelocityValueRelationship("ScaleY", "ScaleYVelocity", null)); mVelocityValueRelationships.Add(new VelocityValueRelationship("ScaleZ", "ScaleZVelocity", null)); mVelocityValueRelationships.Add(new VelocityValueRelationship("Radius", "RadiusVelocity", null)); mVelocityValueRelationships.Add(new VelocityValueRelationship("Alpha", "AlphaRate", null)); mVelocityValueRelationships.Add(new VelocityValueRelationship("Red", "RedRate", null)); mVelocityValueRelationships.Add(new VelocityValueRelationship("Green", "GreenRate", null)); mVelocityValueRelationships.Add(new VelocityValueRelationship("Blue", "BlueRate", null)); mVelocityValueRelationships.Add(new VelocityValueRelationship("RotationX", "RotationXVelocity", null)); mVelocityValueRelationships.Add(new VelocityValueRelationship("RotationY", "RotationYVelocity", null)); mVelocityValueRelationships.Add(new VelocityValueRelationship("RotationZ", "RotationZVelocity", null)); mVelocityValueRelationships.Add(new VelocityValueRelationship("RelativeRotationX", "RelativeRotationXVelocity", null)); mVelocityValueRelationships.Add(new VelocityValueRelationship("RelativeRotationY", "RelativeRotationYVelocity", null)); mVelocityValueRelationships.Add(new VelocityValueRelationship("RelativeRotationZ", "RelativeRotationZVelocity", null)); mVelocityValueRelationships.Add(new VelocityValueRelationship("LeftDestination", "LeftDestinationVelocity", null)); mVelocityValueRelationships.Add(new VelocityValueRelationship("RightDestination", "RightDestinationVelocity", null)); mVelocityValueRelationships.Add(new VelocityValueRelationship("TopDestination", "TopDestinationVelocity", null)); mVelocityValueRelationships.Add(new VelocityValueRelationship("BottomDestination", "BottomDestinationVelocity", null)); mVelocityValueRelationships.Add(new VelocityValueRelationship("Scale", "ScaleVelocity", null)); mVelocityValueRelationships.Add(new VelocityValueRelationship("Spacing", "SpacingVelocity", null)); #endregion #region Create the Animation Relationships mAnimationValueRelationships.Add(new AnimationValueRelationship("CurrentFrameIndex", "AnimationSpeed", "CurrentChain", "Count")); #endregion #region Create the Absolute/Relative Relationships mAbsoluteRelativeValueRelationships.Add(new AbsoluteRelativeValueRelationship("X", "RelativeX")); mAbsoluteRelativeValueRelationships.Add(new AbsoluteRelativeValueRelationship("Y", "RelativeY")); mAbsoluteRelativeValueRelationships.Add(new AbsoluteRelativeValueRelationship("Z", "RelativeZ")); mAbsoluteRelativeValueRelationships.Add(new AbsoluteRelativeValueRelationship("XVelocity", "RelativeXVelocity")); mAbsoluteRelativeValueRelationships.Add(new AbsoluteRelativeValueRelationship("YVelocity", "RelativeYVelocity")); mAbsoluteRelativeValueRelationships.Add(new AbsoluteRelativeValueRelationship("ZVelocity", "RelativeZVelocity")); mAbsoluteRelativeValueRelationships.Add(new AbsoluteRelativeValueRelationship("RotationX", "RelativeRotationX")); mAbsoluteRelativeValueRelationships.Add(new AbsoluteRelativeValueRelationship("RotationY", "RelativeRotationY")); mAbsoluteRelativeValueRelationships.Add(new AbsoluteRelativeValueRelationship("RotationZ", "RelativeRotationZ")); mAbsoluteRelativeValueRelationships.Add(new AbsoluteRelativeValueRelationship("RotationXVelocity", "RelativeRotationXVelocity")); mAbsoluteRelativeValueRelationships.Add(new AbsoluteRelativeValueRelationship("RotationYVelocity", "RelativeRotationYVelocity")); mAbsoluteRelativeValueRelationships.Add(new AbsoluteRelativeValueRelationship("RotationZVelocity", "RelativeRotationZVelocity")); mAbsoluteRelativeValueRelationships.Add(new AbsoluteRelativeValueRelationship("Top", "RelativeTop")); mAbsoluteRelativeValueRelationships.Add(new AbsoluteRelativeValueRelationship("Bottom", "RelativeBottom")); mAbsoluteRelativeValueRelationships.Add(new AbsoluteRelativeValueRelationship("Left", "RelativeLeft")); mAbsoluteRelativeValueRelationships.Add(new AbsoluteRelativeValueRelationship("Right", "RelativeRight")); #endregion #if !SILVERLIGHT VelocityValueRelationships = new ReadOnlyCollection<VelocityValueRelationship>(mVelocityValueRelationships); AbsoluteRelativeValueRelationships = new ReadOnlyCollection<AbsoluteRelativeValueRelationship>(mAbsoluteRelativeValueRelationships); #endif } //private static void Flush() //{ // mInstructionBuffer.Flush(); //} #endregion #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Drawing; using System.Text; using System.Windows.Forms; using Epi.Data; using Epi.Data.MongoDB; using Epi.Windows.Dialogs; namespace Epi.Data.MongoDB.Forms { /// <summary> /// Dialog for building a MongoDB connection string /// </summary> public partial class ConnectionStringDialog : DialogBase, IConnectionStringGui { #region Public Data Members #endregion //Public Data Members #region Constructors /// <summary> /// Default Constructor /// </summary> public ConnectionStringDialog() { InitializeComponent(); this.cmbServerName.Items.Add("<Browse for more>"); this.cmbServerName.Text = ""; dbConnectionStringBuilder = new MongoDBConnectionStringBuilder(); } #endregion //Constructors #region IConnectionStringBuilder Members public bool ShouldIgnoreNonExistance { set { } } public virtual void SetDatabaseName(string databaseName) { } public virtual void SetServerName(string serverName) { } public virtual void SetUserName(string userName) { } public virtual void SetPassword(string password) { } /// <summary> /// Module-level SqlDBConnectionString object member. /// </summary> protected MongoDBConnectionStringBuilder dbConnectionStringBuilder; /// <summary> /// Gets or sets the SqlDBConnectionString Object /// </summary> public DbConnectionStringBuilder DbConnectionStringBuilder { get { return dbConnectionStringBuilder; } //set //{ // dbConnectionStringBuilder = (SqlConnectionStringBuilder)value; //} } /// <summary> /// Sets the preferred database name /// </summary> public virtual string PreferredDatabaseName { set { txtDatabaseName.Text = value; } get { return txtDatabaseName.Text; } } /// <summary> /// Gets a user friendly description of the connection string /// </summary> public virtual string ConnectionStringDescription { get { return cmbServerName.Text + "::" + txtDatabaseName.Text; } } /// <summary> /// Gets whether or not the user entered a password /// </summary> public bool UsesPassword { get { if (this.txtPassword.Text.Length > 0) { return true; } else { return false; } } } #endregion //IConnectionStringBuilder Members #region Event Handlers /// <summary> /// Handles the Click event of the OK button /// </summary> /// <param name="sender">Object that fired the event</param> /// <param name="e">.NET supplied event parameters</param> private void btnOK_Click(object sender, EventArgs e) { OnOkClick(); } /// <summary> /// Handles the Click event of the Cancel button /// </summary> /// <param name="sender">Object that fired the event</param> /// <param name="e">.NET supplied event parameters</param> private void btnCancel_Click(object sender, EventArgs e) { OnCancelClick(); } /// <summary> /// Handles the Change event of the Server Name's selection /// </summary> /// <param name="sender">Object that fired the event</param> /// <param name="e">.NET supplied event parameters</param> private void cmbServerName_SelectedIndexChanged(object sender, EventArgs e) { // if last item in list (Browse for Servers) if (cmbServerName.SelectedIndex == (cmbServerName.Items.Count - 1)) { string serverName = BrowseForServers.BrowseNetworkServers(); if (!string.IsNullOrEmpty(serverName)) { this.cmbServerName.Items.Insert(0, serverName); this.cmbServerName.SelectedIndex = 0; return; } this.cmbServerName.SelectedText = string.Empty; } } #endregion Event Handlers #region Private Methods #endregion //Private Methods #region Protected Methods /// <summary> /// Validates if all the necessary input is provided. /// </summary> /// <returns></returns> protected override bool ValidateInput() { base.ValidateInput(); // Server name if (Util.IsEmpty(this.cmbServerName.Text.Trim())) { ErrorMessages.Add("Server name is required"); // TODO: Hard coded string } // Database name string databaseName = txtDatabaseName.Text.Trim(); Epi.Validator.ValidateDatabaseName(databaseName, ErrorMessages); if (!string.IsNullOrEmpty(txtPort.Text)) { uint result; if (!uint.TryParse(txtPort.Text, out result)) { ErrorMessages.Add("Invalid port"); } } return (ErrorMessages.Count == 0); } /// <summary> /// Occurs when cancel is clicked /// </summary> protected void OnCancelClick() { this.dbConnectionStringBuilder.ConnectionString = string.Empty ; this.PreferredDatabaseName = string.Empty; this.DialogResult = DialogResult.Cancel; this.Close(); } /// <summary> /// Occurs when OK is clicked /// </summary> protected virtual void OnOkClick() { if (ValidateInput()) { dbConnectionStringBuilder = new MongoDBConnectionStringBuilder(); dbConnectionStringBuilder.Database = txtDatabaseName.Text.Trim(); dbConnectionStringBuilder.Server = cmbServerName.Text.Trim(); dbConnectionStringBuilder.User = txtUserName.Text.Trim(); dbConnectionStringBuilder.Password = txtPassword.Text.Trim(); if (!string.IsNullOrEmpty(txtPort.Text)) { dbConnectionStringBuilder.Port = txtPort.Text; } this.DialogResult = DialogResult.OK; this.Hide(); } else { ShowErrorMessages(); } } #endregion Protected Methods } }
// 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 gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Compute.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedReservationsClientTest { [xunit::FactAttribute] public void GetRequestObject() { moq::Mock<Reservations.ReservationsClient> mockGrpcClient = new moq::Mock<Reservations.ReservationsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetReservationRequest request = new GetReservationRequest { Zone = "zone255f4ea8", Reservation = "reservationf22d3388", Project = "projectaa6ff846", }; Reservation expectedResponse = new Reservation { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", Status = Reservation.Types.Status.Deleting, SpecificReservationRequired = false, SpecificReservation = new AllocationSpecificSKUReservation(), Description = "description2cf9da67", SelfLink = "self_link7e87f12d", SatisfiesPzs = false, Commitment = "commitment726158e4", }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ReservationsClient client = new ReservationsClientImpl(mockGrpcClient.Object, null); Reservation response = client.Get(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRequestObjectAsync() { moq::Mock<Reservations.ReservationsClient> mockGrpcClient = new moq::Mock<Reservations.ReservationsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetReservationRequest request = new GetReservationRequest { Zone = "zone255f4ea8", Reservation = "reservationf22d3388", Project = "projectaa6ff846", }; Reservation expectedResponse = new Reservation { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", Status = Reservation.Types.Status.Deleting, SpecificReservationRequired = false, SpecificReservation = new AllocationSpecificSKUReservation(), Description = "description2cf9da67", SelfLink = "self_link7e87f12d", SatisfiesPzs = false, Commitment = "commitment726158e4", }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Reservation>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ReservationsClient client = new ReservationsClientImpl(mockGrpcClient.Object, null); Reservation responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Reservation responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Get() { moq::Mock<Reservations.ReservationsClient> mockGrpcClient = new moq::Mock<Reservations.ReservationsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetReservationRequest request = new GetReservationRequest { Zone = "zone255f4ea8", Reservation = "reservationf22d3388", Project = "projectaa6ff846", }; Reservation expectedResponse = new Reservation { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", Status = Reservation.Types.Status.Deleting, SpecificReservationRequired = false, SpecificReservation = new AllocationSpecificSKUReservation(), Description = "description2cf9da67", SelfLink = "self_link7e87f12d", SatisfiesPzs = false, Commitment = "commitment726158e4", }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ReservationsClient client = new ReservationsClientImpl(mockGrpcClient.Object, null); Reservation response = client.Get(request.Project, request.Zone, request.Reservation); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAsync() { moq::Mock<Reservations.ReservationsClient> mockGrpcClient = new moq::Mock<Reservations.ReservationsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetReservationRequest request = new GetReservationRequest { Zone = "zone255f4ea8", Reservation = "reservationf22d3388", Project = "projectaa6ff846", }; Reservation expectedResponse = new Reservation { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", Status = Reservation.Types.Status.Deleting, SpecificReservationRequired = false, SpecificReservation = new AllocationSpecificSKUReservation(), Description = "description2cf9da67", SelfLink = "self_link7e87f12d", SatisfiesPzs = false, Commitment = "commitment726158e4", }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Reservation>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ReservationsClient client = new ReservationsClientImpl(mockGrpcClient.Object, null); Reservation responseCallSettings = await client.GetAsync(request.Project, request.Zone, request.Reservation, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Reservation responseCancellationToken = await client.GetAsync(request.Project, request.Zone, request.Reservation, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicyRequestObject() { moq::Mock<Reservations.ReservationsClient> mockGrpcClient = new moq::Mock<Reservations.ReservationsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyReservationRequest request = new GetIamPolicyReservationRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", OptionsRequestedPolicyVersion = -1471234741, }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ReservationsClient client = new ReservationsClientImpl(mockGrpcClient.Object, null); Policy response = client.GetIamPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyRequestObjectAsync() { moq::Mock<Reservations.ReservationsClient> mockGrpcClient = new moq::Mock<Reservations.ReservationsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyReservationRequest request = new GetIamPolicyReservationRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", OptionsRequestedPolicyVersion = -1471234741, }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ReservationsClient client = new ReservationsClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.GetIamPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicy() { moq::Mock<Reservations.ReservationsClient> mockGrpcClient = new moq::Mock<Reservations.ReservationsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyReservationRequest request = new GetIamPolicyReservationRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ReservationsClient client = new ReservationsClientImpl(mockGrpcClient.Object, null); Policy response = client.GetIamPolicy(request.Project, request.Zone, request.Resource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyAsync() { moq::Mock<Reservations.ReservationsClient> mockGrpcClient = new moq::Mock<Reservations.ReservationsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyReservationRequest request = new GetIamPolicyReservationRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ReservationsClient client = new ReservationsClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.GetIamPolicyAsync(request.Project, request.Zone, request.Resource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.GetIamPolicyAsync(request.Project, request.Zone, request.Resource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicyRequestObject() { moq::Mock<Reservations.ReservationsClient> mockGrpcClient = new moq::Mock<Reservations.ReservationsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyReservationRequest request = new SetIamPolicyReservationRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", ZoneSetPolicyRequestResource = new ZoneSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ReservationsClient client = new ReservationsClientImpl(mockGrpcClient.Object, null); Policy response = client.SetIamPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyRequestObjectAsync() { moq::Mock<Reservations.ReservationsClient> mockGrpcClient = new moq::Mock<Reservations.ReservationsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyReservationRequest request = new SetIamPolicyReservationRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", ZoneSetPolicyRequestResource = new ZoneSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ReservationsClient client = new ReservationsClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.SetIamPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicy() { moq::Mock<Reservations.ReservationsClient> mockGrpcClient = new moq::Mock<Reservations.ReservationsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyReservationRequest request = new SetIamPolicyReservationRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", ZoneSetPolicyRequestResource = new ZoneSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ReservationsClient client = new ReservationsClientImpl(mockGrpcClient.Object, null); Policy response = client.SetIamPolicy(request.Project, request.Zone, request.Resource, request.ZoneSetPolicyRequestResource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyAsync() { moq::Mock<Reservations.ReservationsClient> mockGrpcClient = new moq::Mock<Reservations.ReservationsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyReservationRequest request = new SetIamPolicyReservationRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", ZoneSetPolicyRequestResource = new ZoneSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ReservationsClient client = new ReservationsClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.SetIamPolicyAsync(request.Project, request.Zone, request.Resource, request.ZoneSetPolicyRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.SetIamPolicyAsync(request.Project, request.Zone, request.Resource, request.ZoneSetPolicyRequestResource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissionsRequestObject() { moq::Mock<Reservations.ReservationsClient> mockGrpcClient = new moq::Mock<Reservations.ReservationsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsReservationRequest request = new TestIamPermissionsReservationRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ReservationsClient client = new ReservationsClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse response = client.TestIamPermissions(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsRequestObjectAsync() { moq::Mock<Reservations.ReservationsClient> mockGrpcClient = new moq::Mock<Reservations.ReservationsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsReservationRequest request = new TestIamPermissionsReservationRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ReservationsClient client = new ReservationsClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissions() { moq::Mock<Reservations.ReservationsClient> mockGrpcClient = new moq::Mock<Reservations.ReservationsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsReservationRequest request = new TestIamPermissionsReservationRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ReservationsClient client = new ReservationsClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse response = client.TestIamPermissions(request.Project, request.Zone, request.Resource, request.TestPermissionsRequestResource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsAsync() { moq::Mock<Reservations.ReservationsClient> mockGrpcClient = new moq::Mock<Reservations.ReservationsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsReservationRequest request = new TestIamPermissionsReservationRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ReservationsClient client = new ReservationsClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.Project, request.Zone, request.Resource, request.TestPermissionsRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.Project, request.Zone, request.Resource, request.TestPermissionsRequestResource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
/* * 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. * * The design of this map service is based on SimianGrid's PHP-based * map service. See this URL for the original PHP version: * https://github.com/openmetaversefoundation/simiangrid/ */ using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Net; using System.Reflection; using Nini.Config; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Services.Interfaces; namespace OpenSim.Services.MapImageService { public class MapImageService : IMapImageService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private const int ZOOM_LEVELS = 8; private const int IMAGE_WIDTH = 256; private const int HALF_WIDTH = 128; private const int JPEG_QUALITY = 80; private static string m_TilesStoragePath = "maptiles"; private static object m_Sync = new object(); private static bool m_Initialized = false; private static string m_WaterTileFile = string.Empty; private static Color m_Watercolor = Color.FromArgb(29, 71, 95); public MapImageService(IConfigSource config) { if (!m_Initialized) { m_Initialized = true; m_log.Debug("[MAP IMAGE SERVICE]: Starting MapImage service"); IConfig serviceConfig = config.Configs["MapImageService"]; if (serviceConfig != null) { m_TilesStoragePath = serviceConfig.GetString("TilesStoragePath", m_TilesStoragePath); if (!Directory.Exists(m_TilesStoragePath)) Directory.CreateDirectory(m_TilesStoragePath); m_WaterTileFile = Path.Combine(m_TilesStoragePath, "water.jpg"); if (!File.Exists(m_WaterTileFile)) { Bitmap waterTile = new Bitmap(IMAGE_WIDTH, IMAGE_WIDTH); FillImage(waterTile, m_Watercolor); waterTile.Save(m_WaterTileFile, ImageFormat.Jpeg); } } } } #region IMapImageService public bool AddMapTile(int x, int y, byte[] imageData, out string reason) { reason = string.Empty; string fileName = GetFileName(1, x, y); lock (m_Sync) { try { using (FileStream f = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.Write)) f.Write(imageData, 0, imageData.Length); } catch (Exception e) { m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to save image file {0}: {1}", fileName, e); reason = e.Message; return false; } // Also save in png format? // Stitch seven more aggregate tiles together for (uint zoomLevel = 2; zoomLevel <= ZOOM_LEVELS; zoomLevel++) { // Calculate the width (in full resolution tiles) and bottom-left // corner of the current zoom level int width = (int)Math.Pow(2, (double)(zoomLevel - 1)); int x1 = x - (x % width); int y1 = y - (y % width); if (!CreateTile(zoomLevel, x1, y1)) { m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to create tile for {0} at zoom level {1}", fileName, zoomLevel); reason = string.Format("Map tile at zoom level {0} failed", zoomLevel); return false; } } } return true; } public byte[] GetMapTile(string fileName, out string format) { // m_log.DebugFormat("[MAP IMAGE SERVICE]: Getting map tile {0}", fileName); format = ".jpg"; string fullName = Path.Combine(m_TilesStoragePath, fileName); if (File.Exists(fullName)) { format = Path.GetExtension(fileName).ToLower(); //m_log.DebugFormat("[MAP IMAGE SERVICE]: Found file {0}, extension {1}", fileName, format); return File.ReadAllBytes(fullName); } else if (File.Exists(m_WaterTileFile)) { return File.ReadAllBytes(m_WaterTileFile); } else { m_log.DebugFormat("[MAP IMAGE SERVICE]: unable to get file {0}", fileName); return new byte[0]; } } #endregion private string GetFileName(uint zoomLevel, int x, int y) { string extension = "jpg"; return Path.Combine(m_TilesStoragePath, string.Format("map-{0}-{1}-{2}-objects.{3}", zoomLevel, x, y, extension)); } private Bitmap GetInputTileImage(string fileName) { try { if (File.Exists(fileName)) return new Bitmap(fileName); } catch (Exception e) { m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to read image data from {0}: {1}", fileName, e); } return null; } private Bitmap GetOutputTileImage(string fileName) { try { if (File.Exists(fileName)) return new Bitmap(fileName); else { // Create a new output tile with a transparent background Bitmap bm = new Bitmap(IMAGE_WIDTH, IMAGE_WIDTH, PixelFormat.Format24bppRgb); bm.MakeTransparent(); return bm; } } catch (Exception e) { m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to read image data from {0}: {1}", fileName, e); } return null; } private bool CreateTile(uint zoomLevel, int x, int y) { // m_log.DebugFormat("[MAP IMAGE SERVICE]: Create tile for {0} {1}, zoom {2}", x, y, zoomLevel); int prevWidth = (int)Math.Pow(2, (double)zoomLevel - 2); int thisWidth = (int)Math.Pow(2, (double)zoomLevel - 1); // Convert x and y to the bottom left tile for this zoom level int xIn = x - (x % prevWidth); int yIn = y - (y % prevWidth); // Convert x and y to the bottom left tile for the next zoom level int xOut = x - (x % thisWidth); int yOut = y - (y % thisWidth); // Try to open the four input tiles from the previous zoom level Bitmap inputBL = GetInputTileImage(GetFileName(zoomLevel - 1, xIn, yIn)); Bitmap inputBR = GetInputTileImage(GetFileName(zoomLevel - 1, xIn + prevWidth, yIn)); Bitmap inputTL = GetInputTileImage(GetFileName(zoomLevel - 1, xIn, yIn + prevWidth)); Bitmap inputTR = GetInputTileImage(GetFileName(zoomLevel - 1, xIn + prevWidth, yIn + prevWidth)); // Open the output tile (current zoom level) string outputFile = GetFileName(zoomLevel, xOut, yOut); Bitmap output = GetOutputTileImage(outputFile); if (output == null) return false; FillImage(output, m_Watercolor); if (inputBL != null) { ImageCopyResampled(output, inputBL, 0, HALF_WIDTH, 0, 0); inputBL.Dispose(); } if (inputBR != null) { ImageCopyResampled(output, inputBR, HALF_WIDTH, HALF_WIDTH, 0, 0); inputBR.Dispose(); } if (inputTL != null) { ImageCopyResampled(output, inputTL, 0, 0, 0, 0); inputTL.Dispose(); } if (inputTR != null) { ImageCopyResampled(output, inputTR, HALF_WIDTH, 0, 0, 0); inputTR.Dispose(); } // Write the modified output try { using (Bitmap final = new Bitmap(output)) { output.Dispose(); final.Save(outputFile, ImageFormat.Jpeg); } } catch (Exception e) { m_log.WarnFormat("[MAP IMAGE SERVICE]: Oops on saving {0} {1}", outputFile, e); } // Save also as png? return true; } #region Image utilities private void FillImage(Bitmap bm, Color c) { for (int x = 0; x < bm.Width; x++) for (int y = 0; y < bm.Height; y++) bm.SetPixel(x, y, c); } private void ImageCopyResampled(Bitmap output, Bitmap input, int destX, int destY, int srcX, int srcY) { int resamplingRateX = 2; // (input.Width - srcX) / (output.Width - destX); int resamplingRateY = 2; // (input.Height - srcY) / (output.Height - destY); for (int x = destX; x < destX + HALF_WIDTH; x++) for (int y = destY; y < destY + HALF_WIDTH; y++) { Color p = input.GetPixel(srcX + (x - destX) * resamplingRateX, srcY + (y - destY) * resamplingRateY); output.SetPixel(x, y, p); } } #endregion } }
// MIT License // // Copyright (c) 2017 Maarten van Sambeek. // // 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. namespace ConnectQl.Validation { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using System.Threading.Tasks; using ConnectQl.AsyncEnumerables; using ConnectQl.Expressions.Helpers; using ConnectQl.ExtensionMethods; using ConnectQl.Intellisense; using ConnectQl.Interfaces; using ConnectQl.Internal; using ConnectQl.Parser.Ast; using ConnectQl.Parser.Ast.Expressions; using ConnectQl.Parser.Ast.Sources; using ConnectQl.Parser.Ast.Statements; using ConnectQl.Parser.Ast.Targets; using ConnectQl.Parser.Ast.Visitors; using ConnectQl.Plugins; using ConnectQl.Resources; using ConnectQl.Results; using JetBrains.Annotations; /// <summary> /// The validator. /// </summary> internal class Validator : NodeVisitor { /// <summary> /// The default functions. /// </summary> private static readonly DefaultFunctions DefaultFunctions = new DefaultFunctions(); /// <summary> /// The context. /// </summary> private readonly IValidationContext context; /// <summary> /// Gets or sets the scope. /// </summary> private ValidationScope scope; /// <summary> /// Initializes a new instance of the <see cref="Validator"/> class. /// </summary> /// <param name="context"> /// The context. /// </param> private Validator([NotNull] IValidationContext context) { this.context = context; this.scope = new ValidationScope(context); this.scope.EnablePlugin(DefaultFunctions); } /// <summary> /// Validates the specified <see cref="Node"/>. /// </summary> /// <typeparam name="T"> /// The type of the node to validate. /// </typeparam> /// <param name="context"> /// The context. /// </param> /// <param name="node"> /// The node to validate. /// </param> /// <returns> /// The <see cref="Node"/>. /// </returns> [CanBeNull] public static T Validate<T>([NotNull] IValidationContext context, T node) where T : Node { return new Validator(context).Visit(node); } /// <summary> /// Validates the specified <see cref="Node"/>. /// </summary> /// <typeparam name="T"> /// The type of the node to validate. /// </typeparam> /// <param name="context"> /// The context. /// </param> /// <param name="node"> /// The node to validate. /// </param> /// <param name="functions"> /// The functions. /// </param> /// <returns> /// The <see cref="Node"/>. /// </returns> [CanBeNull] internal static T Validate<T>([NotNull] IValidationContext context, T node, [NotNull] out ILookup<string, IFunctionDescriptor> functions) where T : Node { var validator = new Validator(context); var result = validator.Visit(node); functions = ((IFunctionDictionary)validator.scope.Functions).Dictionary.ToLookup(d => d.Key.Split('\'')[0].ToLowerInvariant(), d => d.Value); return result; } /// <summary> /// Visits a <see cref="ConnectQl.Parser.Ast.Expressions.AliasedConnectQlExpression"/>. /// Adds the alias to the current scope (or a default alias if none exists). Returns a new node if an alias was created. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal override Node VisitAliasedSqlExpression(AliasedConnectQlExpression node) { if (node.Expression is WildcardConnectQlExpression) { return this.ValidateChildren(node); } var alias = this.scope.AddAlias(node.Alias ?? (node.Expression as FieldReferenceConnectQlExpression)?.Name); if (node.Alias != alias) { node = this.context.NodeData.CopyValues(node, new AliasedConnectQlExpression(node.Expression, alias)); } return this.ValidateChildren(node); } /// <summary> /// Visits a <see cref="ConnectQl.Parser.Ast.Expressions.BinaryConnectQlExpression"/> expression. /// Infers the type of the binary expression and stores it in the node data. Checks if children are in a grouping, /// if so, marks this node as a group too. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> [NotNull] protected internal override Node VisitBinarySqlExpression(BinaryConnectQlExpression node) { node = this.ValidateChildren(node); var resultType = new TypeDescriptor(OperatorHelper.InferType(node.Op, this.context.NodeData.GetType(node.First).SimplifiedType, this.context.NodeData.GetType(node.Second).SimplifiedType, error => this.AddError(node, error))); this.context.NodeData.SetType(node, resultType); if (this.scope.IsGroupByExpression(node)) { this.context.NodeData.SetScope(node, NodeScope.Group); } return node; } /// <summary> /// Visits a <see cref="ConstConnectQlExpression"/> expression. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> [NotNull] protected internal override Node VisitConstSqlExpression(ConstConnectQlExpression node) { this.context.NodeData.SetType(node, new TypeDescriptor(node.Value?.GetType() ?? typeof(object))); this.context.NodeData.SetScope(node, this.scope.IsGroupByExpression(node) ? NodeScope.Group : NodeScope.Constant); return node; } /// <summary> /// Visits a <see cref="FieldReferenceConnectQlExpression"/> expression. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> [CanBeNull] protected internal override Node VisitFieldReferenceSqlExpression(FieldReferenceConnectQlExpression node) { var replacer = this.context.NodeData.GetFieldReplacer(node); if (replacer != null) { return this.Visit(replacer); } this.context.NodeData.SetType(node, new TypeDescriptor(typeof(object))); this.context.NodeData.SetScope(node, this.scope.IsGroupByExpression(node) ? NodeScope.Group : NodeScope.Row); if (node.Source == null) { this.AddError(node, string.Format(Messages.FieldMustHaveASource, node.Name)); return node; } var source = this.scope.GetSource(node.Source); if (source == null) { this.AddError(node, string.Format(Messages.SourceReferencedBeforeDeclared, node.Source)); } this.context.NodeData.Set(node, "Source", source); return node; } /// <summary> /// The visit function call async. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The <see cref="Task"/>. /// </returns> protected internal override Node VisitFunctionCallSqlExpression(FunctionCallConnectQlExpression node) { var function = this.scope.GetFunction(node.Name, node.Arguments); if (function == null) { this.AddError(node, string.Format(Messages.FunctionNotFound, node.GetDisplay())); this.context.NodeData.SetType(node, new TypeDescriptor(typeof(object))); this.context.NodeData.SetFunction(node, this.scope.GetFunction(node.Name, node.Arguments)); this.context.NodeData.SetScope(node, NodeScope.Constant); return node; } this.context.NodeData.SetType(node, function.ReturnType); this.context.NodeData.SetFunction(node, this.scope.GetFunction(node.Name, node.Arguments)); var result = this.ValidateChildren(this.ReplaceEnumArguments(node)); for (var i = 0; i < function.Arguments.Count; i++) { ConversionHelper.ValidateConversion(node.Arguments[i], this.context.NodeData.GetType(node.Arguments[i]).SimplifiedType, function.Arguments[i].Type.SimplifiedType); } this.context.NodeData.SetScope(node, this.scope.IsGroupByExpression(node) || (node.Arguments.All(a => this.context.NodeData.GetScope(a) != NodeScope.Row) && node.Arguments.Any(a => this.context.NodeData.GetScope(a) == NodeScope.Group)) ? NodeScope.Group : NodeScope.Row); if (function.Arguments.Count > 0 && function.Arguments.Any(argument => argument.Type.Interfaces.Any(i => i.HasInterface(typeof(IAsyncEnumerable<>))))) { this.context.NodeData.SetScope(result, NodeScope.Group); } return result; } /// <summary> /// Visits a <see cref="ConnectQl.Parser.Ast.Sources.FunctionSource"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> [NotNull] protected internal override Node VisitFunctionSource(FunctionSource node) { if (node.Alias != null) { if (this.scope.GetSource(node.Alias) != null) { this.AddError(node, string.Format(Messages.AliasAlreadyUsed, node.Alias)); } else { this.scope.AddSource(node.Alias, node); } } var result = this.ValidateChildren(node); var function = this.context.NodeData.GetFunction(result.Function); if (!function?.ReturnType.Interfaces.Contains(typeof(IDataSource)) ?? false) { this.AddError(node, string.Format(Messages.FunctionIsNoDataSource, node.Function.Name.ToUpperInvariant())); } return result; } /// <summary> /// Visits a <see cref="ConnectQl.Parser.Ast.Targets.FunctionTarget"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> [NotNull] protected internal override Node VisitFunctionTarget(FunctionTarget node) { var result = this.ValidateChildren(node); var function = this.context.NodeData.GetFunction(result.Function); if (!function?.ReturnType.Interfaces.Contains(typeof(IDataTarget)) ?? false) { this.AddError(node, string.Format(Messages.FunctionIsNoDataTarget, node.Function.Name.ToUpperInvariant())); } return result; } /// <summary> /// Visits a <see cref="ConnectQl.Parser.Ast.Statements.ImportPluginStatement"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal override Node VisitImportPluginStatement(ImportPluginStatement node) { if (this.scope.IsPluginEnabled(node.Plugin)) { this.AddWarning(node, string.Format(Messages.PluginAlreadyEnabled, node.Plugin)); } if (!this.scope.EnablePlugin(node.Plugin) && !this.scope.IsLoadingPlugins) { var plugins = this.scope.GetAvailablePlugins().ToArray(); var availablePlugins = plugins.Length == 0 ? string.Empty : " " + string.Format(Messages.AvailablePlugins, string.Join(", ", plugins.Where(p => !string.Equals(p, "DefaultFunctions")))); this.AddError(node, $"Plugin {node.Plugin} was not found.{availablePlugins}"); } return base.VisitImportPluginStatement(node); } /// <summary> /// Visits a <see cref="ConnectQl.Parser.Ast.Sources.JoinSource"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal override Node VisitJoinSource(JoinSource node) { return this.ValidateChildren(node); } /// <summary> /// Visits the node and ensures the result is of type <typeparamref name="T"/>. When node is <c>null</c>, returns /// <c>null</c>. /// </summary> /// <typeparam name="T"> /// The type of the result. /// </typeparam> /// <param name="node"> /// The node. /// </param> /// <returns> /// The <typeparamref name="T"/>. /// </returns> protected internal override T Visit<T>(T node) { var result = base.Visit(node); if (!object.ReferenceEquals(result, node)) { this.context.NodeData.CopyValues(node, result); } return result; } /// <summary> /// Visits a <see cref="ConnectQl.Parser.Ast.Statements.SelectFromStatement"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal override Node VisitSelectFromStatement(SelectFromStatement node) { using (this.EnterScope()) { var source = this.Visit(node.Source); var where = this.Visit(node.Where); var groupings = this.Visit(node.Groupings); this.scope.AddGroupings(groupings); var having = this.Visit(node.Having); var expressions = this.Visit(node.Expressions); var aliasOrders = expressions.Join( node.Orders.Select( o => o.Expression as FieldReferenceConnectQlExpression).Where(fr => fr != null && fr.Source == null), e => e.Alias, fr => fr.Name, (expression, field) => new { expression, field, }); foreach (var aliasOrder in aliasOrders) { this.context.NodeData.SetFieldReplacer(aliasOrder.field, aliasOrder.expression.Expression); } var orders = this.Visit(node.Orders); foreach (var invalidOrderBy in orders.Select(o => o.Expression as FieldReferenceConnectQlExpression).Where(fr => fr != null && fr.Source == null)) { this.AddError(invalidOrderBy, string.Format(Messages.AliasNotDefined, invalidOrderBy.Name)); } var hasGroupings = groupings.Any(); if (hasGroupings) { if (having != null && this.context.NodeData.GetScope(having) == NodeScope.Row) { this.AddError(having, string.Format(Messages.MissingAggregateFunction, node.Having)); } foreach (var e in expressions.Where(e => this.context.NodeData.GetScope(e) == NodeScope.Row)) { this.AddError(e, string.Format(Messages.MissingAggregateFunction, e)); } } else if (having != null) { this.AddError(having, Messages.HavingNotAllowed); } return expressions != node.Expressions || source != node.Source || where != node.Where || groupings != node.Groupings || having != node.Having || orders != node.Orders ? this.context.NodeData.CopyValues(node, new SelectFromStatement(expressions, source, where, groupings, having, orders)) : node; } } /// <summary> /// Visits a <see cref="ConnectQl.Parser.Ast.Sources.SelectSource"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal override Node VisitSelectSource(SelectSource node) { this.scope.AddSource(node.Alias, node); return base.VisitSelectSource(node); } /// <summary> /// The visit trigger. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The <see cref="Node"/>. /// </returns> [NotNull] protected internal override Node VisitTrigger(Trigger node) { var result = (Trigger)node.VisitChildren(this); var function = this.context.NodeData.GetFunction(result.Function); if (!function?.ReturnType.Interfaces.Contains(typeof(ITrigger)) ?? false) { this.AddError(node, string.Format(Messages.FunctionIsNoTrigger, node.Function.Name.ToUpperInvariant())); } return result; } /// <summary> /// The visit unary async. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The <see cref="Task"/>. /// </returns> [NotNull] protected internal override Node VisitUnarySqlExpression(UnaryConnectQlExpression node) { node = this.ValidateChildren(node); this.context.NodeData.SetType(node, new TypeDescriptor(OperatorHelper.InferType(node.Op, this.context.NodeData.GetType(node.Expression).SimplifiedType))); if (this.scope.IsGroupByExpression(node)) { this.context.NodeData.SetScope(node, NodeScope.Group); } return node; } /// <summary> /// Visits a <see cref="ConnectQl.Parser.Ast.VariableDeclaration"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> [NotNull] protected internal override Node VisitVariableDeclaration(VariableDeclaration node) { node = this.ValidateChildren(node); this.scope.AddVariable(node.Name, node.Expression == null ? new TypeDescriptor(typeof(object)) : this.context.NodeData.GetType(node.Expression)); return node; } /// <summary> /// Visits a <see cref="ConnectQl.Parser.Ast.Sources.VariableSource"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> [NotNull] protected internal override Node VisitVariableSource(VariableSource node) { node = this.ValidateChildren(node); var variableType = this.scope.GetVariableType(node.Variable); if (variableType == null) { this.AddError(node, string.Format(Messages.UndeclaredVariable, node.Variable)); } else if (!variableType.Interfaces.Contains(typeof(IDataSource))) { this.AddError(node, string.Format(Messages.VariableIsNoDataSource, node.Variable)); } if (this.scope.GetSource(node.Alias) != null) { this.AddError(node, string.Format(Messages.AliasAlreadyUsed, node.Alias)); } else { this.scope.AddSource(node.Alias, node); } this.context.NodeData.SetType(node, variableType); this.context.NodeData.SetScope(node, NodeScope.Constant); return node; } /// <summary> /// Visits a <see cref="ConnectQl.Parser.Ast.Expressions.VariableConnectQlExpression"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> [NotNull] protected internal override Node VisitVariableSqlExpression(VariableConnectQlExpression node) { node = this.ValidateChildren(node); var variableType = this.scope.GetVariableType(node.Name); if (variableType == null) { this.AddError(node, string.Format(Messages.UndeclaredVariable, node.Name)); } this.context.NodeData.SetType(node, variableType); this.context.NodeData.SetScope(node, NodeScope.Constant); return node; } /// <summary> /// Visits a <see cref="ConnectQl.Parser.Ast.Targets.FunctionTarget"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> [NotNull] protected internal override Node VisitVariableTarget(VariableTarget node) { node = this.ValidateChildren(node); var variableType = this.scope.GetVariableType(node.Variable); if (variableType == null) { this.AddError(node, string.Format(Messages.UndeclaredVariable, node.Variable)); } else if (!variableType.Interfaces.Contains(typeof(IDataTarget))) { this.AddError(node, string.Format(Messages.VariableIsNoDataTarget, node.Variable)); } this.context.NodeData.SetType(node, variableType); this.context.NodeData.SetScope(node, NodeScope.Constant); return node; } /// <summary> /// Visits a <see cref="ConnectQl.Parser.Ast.Expressions.WildcardConnectQlExpression"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> [NotNull] protected internal override Node VisitWildCardSqlExpression(WildcardConnectQlExpression node) { if (node.Source != null) { var source = this.scope.GetSource(node.Source); if (source == null) { this.AddError(node, string.Format(Messages.SourceReferencedBeforeDeclared, node.Source)); } this.context.NodeData.Set(node, "Source", source); } this.context.NodeData.SetScope(node, NodeScope.Row); return node; } /// <summary> /// Enters a new scope. /// </summary> /// <returns> /// A <see cref="IDisposable"/>, that will exit the scope when disposed. /// </returns> [NotNull] private IDisposable EnterScope() { var scope = this.scope; this.scope = this.scope.CreateSubScope(); return new ActionOnDispose(() => this.scope = scope); } /// <summary> /// Adds an error for the specified node. /// </summary> /// <param name="node"> /// The node connected to this error. /// </param> /// <param name="message"> /// The message. /// </param> private void AddError(Node node, string message) { // ReSharper disable StyleCop.SA1126 this.context.NodeData.TryGet(node, "Context", out IParserContext parserContext); this.context.Messages.AddError(parserContext?.Start ?? new Position(), parserContext?.End ?? new Position(), message); // ReSharper restore StyleCop.SA1126 } /// <summary> /// Adds a warning for the specified node. /// </summary> /// <param name="node"> /// The node connected to this error. /// </param> /// <param name="message"> /// The message. /// </param> private void AddWarning(Node node, string message) { // ReSharper disable StyleCop.SA1126 this.context.NodeData.TryGet(node, "Context", out IParserContext parserContext); this.context.Messages.AddWarning(parserContext?.Start ?? new Position(), parserContext?.End ?? new Position(), message); // ReSharper restore StyleCop.SA1126 } /// <summary> /// Replaces strings and field references to enum values. /// </summary> /// <param name="node"> /// The node to replace values with. /// </param> /// <returns> /// The node with replaced. /// </returns> private Node ReplaceEnumArguments([NotNull] FunctionCallConnectQlExpression node) { var arguments = node.Arguments; var function = this.context.NodeData.GetFunction(node); for (var i = 0; i < function.Arguments.Count; i++) { var arg = arguments[i]; var param = function.Arguments[i].Type.SimplifiedType; if (!param.GetTypeInfo().IsEnum) { continue; } var constExpr = arg as ConstConnectQlExpression; var fieldExpr = arg as FieldReferenceConnectQlExpression; ConstConnectQlExpression enumExpr; if (fieldExpr != null && fieldExpr.Source == null) { enumExpr = new ConstConnectQlExpression(Enum.Parse(param, fieldExpr.Name, true)); } else if (constExpr?.Value is int) { enumExpr = new ConstConnectQlExpression(Enum.ToObject(param, constExpr.Value)); } else if (constExpr?.Value is string) { enumExpr = new ConstConnectQlExpression(Enum.Parse(param, (string)constExpr.Value, true)); } else { continue; } arguments = new ReadOnlyCollection<ConnectQlExpressionBase>( new List<ConnectQlExpressionBase>(arguments) { [i] = this.context.NodeData.CopyValues(arguments[i], enumExpr), }); } return arguments != node.Arguments ? this.context.NodeData.CopyValues(node, new FunctionCallConnectQlExpression(node.Name, arguments)) : node; } /// <summary> /// The validate children. /// </summary> /// <param name="node"> /// The node. /// </param> /// <typeparam name="T"> /// The type of the node. /// </typeparam> /// <returns> /// The <see cref="Task"/>. /// </returns> private T ValidateChildren<T>([NotNull] T node) where T : Node { var result = (T)node.VisitChildren(this); var baseExpression = node as ConnectQlExpressionBase; if (baseExpression == null) { return result; } var scopes = result.Children.OfType<ConnectQlExpressionBase>().Select(expression => new { Expression = expression, Scope = this.context.NodeData.GetScope(expression), }) .ToArray(); if (scopes.Any(s => s.Expression == null || s.Scope == NodeScope.Error || s.Scope == NodeScope.Initial)) { this.AddError(node, Messages.InvalidScope); } if (scopes.Any(s => s.Scope == NodeScope.Group)) { if (scopes.Any(s => s.Scope == NodeScope.Row)) { foreach (var child in scopes.Where(s => s.Scope == NodeScope.Row)) { this.AddError(child.Expression, string.Format(Messages.MissingAggregateFunction, child.Expression)); } } else { this.context.NodeData.SetScope(baseExpression, NodeScope.Group); } } else if (scopes.Any(s => s.Scope == NodeScope.Row)) { this.context.NodeData.SetScope(baseExpression, NodeScope.Row); } else { this.context.NodeData.SetScope(baseExpression, NodeScope.Constant); } return result; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; namespace MonoCross.Navigation { /// <summary> /// Represents a mapping of abstract types to native class types to each platform that the abstract types represent. /// </summary> [DebuggerDisplay("Count = {Count}")] public class NamedTypeMap : IDictionary<Type, Type> { /// <summary> /// The map from a named type to a type loader. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public IDictionary<NamedType, TypeLoader> Items { get { return _items; } } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] private readonly IDictionary<NamedType, TypeLoader> _items; /// <summary> /// Initializes a new instance of the <see cref="NamedTypeMap"/> class. /// </summary> public NamedTypeMap() { _items = new Dictionary<NamedType, TypeLoader>(); } /// <summary> /// Adds an entry with the specified abstract type and class type to the collection. /// </summary> /// <param name="abstractType">The type of the abstract to associate with the class type.</param> /// <param name="concreteType">The type of the class to associate with the abstract type.</param> public void Add(Type abstractType, Type concreteType) { Add(null, abstractType, concreteType); } /// <summary> /// Adds an entry with the specified abstract type and class type to the collection. /// </summary> /// <param name="name">A unique identifier for the abstract type.</param> /// <param name="abstractType">The type of the abstract to associate with the class type.</param> /// <param name="concreteType">The type of the class to associate with the abstract type.</param> public void Add(string name, Type abstractType, Type concreteType) { Add(name, abstractType, new TypeLoader(concreteType)); } /// <summary> /// Adds an entry with the specified abstract type and class type to the collection. /// </summary> /// <param name="name">A unique identifier for the abstract type.</param> /// <param name="abstractType">The type of the abstract to associate with the class type.</param> /// <param name="typeLoader">The type loader to associate with the abstract type.</param> public void Add(string name, Type abstractType, TypeLoader typeLoader) { CheckEntry(ref name, abstractType, typeLoader.Type); _items.Add(new NamedType(abstractType, name), typeLoader); } /// <summary> /// Gets the number of entries contained in the collection. /// </summary> public int Count { get { return _items.Count; } } /// <summary> /// Determines whether the collection contains an entry with the specified abstract type. /// </summary> /// <param name="abstractType">The abstract type to locate in the collection.</param> /// <returns><c>true</c> if the abstract type was located in the collection; otherwise, <c>false</c>.</returns> public bool ContainsKey(Type abstractType) { return ContainsKey(abstractType, null); } /// <summary> /// Determines whether the collection contains an entry with the specified abstract type. /// </summary> /// <param name="abstractType">The abstract type to locate in the collection.</param> /// <param name="name">A unique identifier for the abstract type.</param> /// <returns><c>true</c> if the abstract type was located in the collection; otherwise, <c>false</c>.</returns> public bool ContainsKey(Type abstractType, string name) { return _items.ContainsKey(new NamedType(abstractType, name)); } /// <summary> /// Removes all custom entries from the collection. /// </summary> public virtual void Clear() { _items.Clear(); } /// <summary> /// Removes the entry with the specified abstract type from the collection. /// </summary> /// <param name="abstractType">The abstract type of the entry to remove.</param> /// <returns><c>true</c> if the entry was successfully removed; otherwise, <c>false</c>.</returns> public bool Remove(Type abstractType) { return Remove(abstractType, null); } /// <summary> /// Removes the entry with the specified abstract type from the collection. /// </summary> /// <param name="abstractType">The abstract type of the entry to remove.</param> /// <param name="name">A unique identifier for the abstract type.</param> /// <returns><c>true</c> if the entry was successfully removed; otherwise, <c>false</c>.</returns> public bool Remove(Type abstractType, string name) { return _items.Remove(new NamedType(abstractType, name)); } /// <summary> /// Gets the class type associated with the specified abstract type. /// </summary> /// <param name="abstractType">The abstract type whose associated class type to get.</param> /// <param name="classType">When the method returns, the class type associated with the specified abstract type, if the abstract type was found; otherwise, <c>null</c>."/></param> /// <returns><c>true</c> if the class type was successfully retrieved; otherwise, <c>false</c>.</returns> public bool TryGetValue(Type abstractType, out Type classType) { return TryGetValue(abstractType, null, out classType); } /// <summary> /// Gets the class type associated with the specified name. /// </summary> /// <param name="name">A unique identifier for the abstract type.</param> /// <param name="classType">When the method returns, the class type associated with the specified abstract type, if the abstract type was found; otherwise, <c>null</c>."/></param> /// <returns><c>true</c> if the class type was successfully retrieved; otherwise, <c>false</c>.</returns> public bool TryGetValue(string name, out Type classType) { var retval = _items.FirstOrDefault(i => i.Key.Id == name); classType = retval.Value.Type; return retval.Key.Type != null; } /// <summary> /// Gets the class type associated with the specified abstract type. /// </summary> /// <param name="abstractType">The abstract type whose associated class type to get.</param> /// <param name="name">A unique identifier for the abstract type.</param> /// <param name="classType">When the method returns, the class type associated with the specified abstract type, if the abstract type was found; otherwise, <c>null</c>."/></param> /// <returns><c>true</c> if the class type was successfully retrieved; otherwise, <c>false</c>.</returns> public bool TryGetValue(Type abstractType, string name, out Type classType) { TypeLoader loader; var retval = _items.TryGetValue(new NamedType(abstractType, name), out loader); classType = loader.Type; return retval; } /// <summary> /// Gets the instance associated with the specified abstract type. /// </summary> /// <param name="abstractType">The abstract type whose associated class type to get.</param> /// <param name="instance">When the method returns, the instance associated with the specified abstract type, if the abstract type was found; otherwise, <c>null</c>."/></param> /// <returns><c>true</c> if the class type was successfully retrieved; otherwise, <c>false</c>.</returns> public bool TryGetInstance(Type abstractType, out object instance) { return TryGetInstance(abstractType, null, out instance); } /// <summary> /// Gets the instance associated with the specified name. /// </summary> /// <param name="name">A unique identifier for the abstract type.</param> /// <param name="instance">When the method returns, the instance associated with the specified abstract type, if the abstract type was found; otherwise, <c>null</c>."/></param> /// <returns><c>true</c> if the class type was successfully retrieved; otherwise, <c>false</c>.</returns> public bool TryGetInstance(string name, out object instance) { var retval = _items.FirstOrDefault(i => i.Key.Id == name); instance = retval.Value.Instance; return retval.Key.Type != null; } /// <summary> /// Gets the instance associated with the specified abstract type. /// </summary> /// <param name="abstractType">The abstract type whose associated class type to get.</param> /// <param name="name">A unique identifier for the abstract type.</param> /// <param name="instance">When the method returns, the instance associated with the specified abstract type, if the abstract type was found; otherwise, <c>null</c>."/></param> /// <returns><c>true</c> if the class type was successfully retrieved; otherwise, <c>false</c>.</returns> public bool TryGetInstance(Type abstractType, string name, out object instance) { TypeLoader loader; var retval = _items.TryGetValue(new NamedType(abstractType, name), out loader); instance = loader.Instance; return retval; } /// <summary> /// Gets or sets the class type associated with the specified interface type. /// </summary> /// <param name="abstractType">The interface type associated with the class type to get or set.</param> /// <returns>The class type associated with the <paramref name="abstractType"/>.</returns> public Type this[Type abstractType] { get { return this[abstractType, null].Type; } set { this[abstractType, null] = new TypeLoader(value); } } /// <summary> /// Gets or sets the class type associated with the specified interface type. /// </summary> /// <param name="abstractType">The interface type associated with the class type to get or set.</param> /// <param name="name">A unique identifier for the abstract type.</param> /// <returns>The class type associated with the <paramref name="abstractType"/>.</returns> public TypeLoader this[Type abstractType, string name] { get { return GetTypeLoader(abstractType, name); } set { CheckEntry(ref name, abstractType, value.Type); _items[new NamedType(abstractType, name)] = value; } } /// <summary> /// Performs type constraints on new entries. /// </summary> /// <param name="name">The entry name passed by reference so that it may be changed.</param> /// <param name="key">The key <see cref="Type"/>.</param> /// <param name="value">the value <see cref="Type"/>.</param> protected virtual void CheckEntry(ref string name, Type key, Type value) { } void ICollection<KeyValuePair<Type, Type>>.Add(KeyValuePair<Type, Type> item) { Add(item.Key, item.Value); } bool ICollection<KeyValuePair<Type, Type>>.Contains(KeyValuePair<Type, Type> item) { Type type; if (TryGetValue(item.Key, out type)) { return type == item.Value; } return false; } void ICollection<KeyValuePair<Type, Type>>.CopyTo(KeyValuePair<Type, Type>[] array, int arrayIndex) { _items.Select(i => new KeyValuePair<Type, Type>(i.Key.Type, i.Value.Type)).ToList().CopyTo(array, arrayIndex); } bool ICollection<KeyValuePair<Type, Type>>.Remove(KeyValuePair<Type, Type> item) { Type type; return TryGetValue(item.Key, out type) && type == item.Value && Remove(item.Key); } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] bool ICollection<KeyValuePair<Type, Type>>.IsReadOnly { get { return _items.IsReadOnly; } } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] ICollection<Type> IDictionary<Type, Type>.Keys { get { return _items.Keys.Select(k => k.Type).ToList(); } } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] ICollection<Type> IDictionary<Type, Type>.Values { get { return _items.Values.Select(k => k.Type).ToList(); } } IEnumerator<KeyValuePair<Type, Type>> IEnumerable<KeyValuePair<Type, Type>>.GetEnumerator() { return _items.Select(i => new KeyValuePair<Type, Type>(i.Key.Type, i.Value.Type)).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<KeyValuePair<Type, Type>>)this).GetEnumerator(); } #region Register/Resolve private TypeLoader GetTypeLoader(Type type, string name) { if (type == null) { throw new ArgumentNullException("type"); } TypeLoader initer; if (ContainsKey(type, name) && (initer = _items[new NamedType(type, name)]).Type != null) return initer; if (name != null) { if (ContainsKey(type) && (initer = _items[new NamedType(type)]).Type != null) return initer; } var abstracts = type.GetTypeInfo().ImplementedInterfaces.ToList(); var interfaceType = abstracts.FirstOrDefault(a => ContainsKey(a, name)); if (interfaceType != null) { return _items[new NamedType(interfaceType, name)]; } interfaceType = abstracts.FirstOrDefault(ContainsKey); return interfaceType == null ? default(TypeLoader) : _items[new NamedType(interfaceType)]; } /// <summary> /// Resolves the specified abstract type as a concrete instance. /// </summary> /// <param name="type">The abstract type to resolve.</param> /// <param name="name">An optional unique identifier for the abstract type.</param> /// <param name="parameters">An array of constructor parameters for initialization.</param> /// <exception cref="TypeLoadException">Thrown if the type cannot be found in the map.</exception> /// <returns>The object instance.</returns> public object Resolve(Type type, string name, params object[] parameters) { //Repackage invalid name as parameter if (name != null && !ContainsKey(type, name) && ContainsKey(type, null)) { var paras = new List<object> { name }; if (parameters != null) paras.AddRange(parameters); parameters = paras.ToArray(); return Resolve(type, null, parameters); } var initer = GetTypeLoader(type, name); if (initer.Type == null) { // If the type can't be initialized, return null if (!type.GetTypeInfo().DeclaredConstructors.Any()) return null; // If the type is not registered at all, provide an initializer anyways initer = new TypeLoader(type); return initer.Load(parameters); } // Add the loader to the items cache to persist singletons var retval = initer.Load(parameters); _items[new NamedType(type, name)] = initer; return retval; } /// <summary> /// Registers the specified key type and class type for <see cref="Resolve"/>. /// </summary> /// <param name="keyType">The key type to associate with the value type.</param> /// <param name="mappedType">The type of the class to associate with the key type.</param> public void Register(Type keyType, Type mappedType) { Register(keyType, mappedType, null); } /// <summary> /// Registers the specified key type and class type for <see cref="Resolve"/>. /// </summary> /// <param name="keyType">The key type to associate with the value type.</param> /// <param name="mappedType">The type of the class to associate with the key type.</param> /// <param name="namedInstance">An optional unique identifier for the key type.</param> public void Register(Type keyType, Type mappedType, string namedInstance) { this[keyType, namedInstance] = new TypeLoader(mappedType); } /// <summary> /// Registers the specified key type and class type for <see cref="Resolve"/>. /// </summary> /// <param name="keyType">The key type to associate with the value type.</param> /// <param name="namedInstance">An optional unique identifier for the key type.</param> /// <param name="nativeType">The type of the class to associate with the key type.</param> /// <param name="initialization">A method that initializes the object.</param> /// <param name="singletonInstance"><c>true</c> to create and cache the instance; otherwise <c>false</c> to create every time.</param> public void Register(Type keyType, Type nativeType, string namedInstance, Func<object> initialization, bool singletonInstance) { this[keyType, namedInstance] = new TypeLoader(nativeType, singletonInstance, initialization); } /// <summary> /// Registers the specified key type and class type for <see cref="Resolve"/>. /// </summary> /// <param name="keyType">The key type to associate with the value type.</param> /// <param name="namedInstance">An optional unique identifier for the key type.</param> /// <param name="nativeType">The type of the class to associate with the key type.</param> /// <param name="initialization">A method that initializes the object.</param> /// <param name="singletonInstance"><c>true</c> to create and cache the instance; otherwise <c>false</c> to create every time.</param> public void Register(Type keyType, Type nativeType, string namedInstance, Func<object[], object> initialization, bool singletonInstance) { this[keyType, namedInstance] = new TypeLoader(nativeType, singletonInstance, initialization); } /// <summary> /// Registers the specified key type and object for <see cref="Resolve"/>. /// </summary> /// <param name="keyType">The key type to associate with the value type.</param> /// <param name="mappedObject">The type of the class to associate with the key type.</param> public void Register(Type keyType, object mappedObject) { Register(keyType, mappedObject, null); } /// <summary> /// Registers the specified key type and object for <see cref="Resolve"/>. /// </summary> /// <param name="keyType">The key type to associate with the value type.</param> /// <param name="mappedObject">The type of the class to associate with the key type.</param> /// <param name="namedInstance">An optional unique identifier for the key type.</param> public void Register(Type keyType, object mappedObject, string namedInstance) { this[keyType, namedInstance] = new TypeLoader(mappedObject); } #endregion /// <summary> /// A key containing a type and optional name. /// </summary> public struct NamedType : IComparable, IEqualityComparer<NamedType> { /// <summary> /// Initializes a new <see cref="NamedType"/> instance. /// </summary> /// <param name="type">The mapped <see cref="Type"/>.</param> public NamedType(Type type) : this(type, null) { } /// <summary> /// Initializes a new <see cref="NamedType"/> instance. /// </summary> /// <param name="type">The mapped <see cref="Type"/>.</param> /// <param name="id">An optional name describing the type.</param> public NamedType(Type type, string id) { if (type == null) throw new ArgumentNullException("type"); Type = type; Id = id; } /// <summary> /// The type for this instance. This field is readonly. /// </summary> public readonly Type Type; /// <summary> /// An optional identifier. This field is readonly. /// </summary> public readonly string Id; #region Equality members /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { return Type == null ? -1 : Type.GetHashCode() ^ (Id == null ? 0 : Id.GetHashCode()); } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param> /// <returns><c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>. </returns> public override bool Equals(object obj) { return this == (NamedType)obj; } /// <summary> /// Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object. /// </summary> /// <param name="obj">An object to compare with this instance.</param> /// <returns>A value that indicates the relative order of the objects being compared. The return value has these meanings: Value Meaning Less than zero This instance precedes <paramref name="obj" /> in the sort order. Zero This instance occurs in the same position in the sort order as <paramref name="obj" />. Greater than zero This instance follows <paramref name="obj" /> in the sort order.</returns> public int CompareTo(object obj) { var p = (NamedType)obj; return GetHashCode() == p.GetHashCode() ? 0 : -1; } /// <summary> /// Determines whether the specified objects are equal. /// </summary> /// <param name="x">The first object of type <see cref="NamedType"/> to compare.</param> /// <param name="y">The second object of type <see cref="NamedType"/> to compare.</param> /// <returns> /// true if the specified objects are equal; otherwise, false. /// </returns> public bool Equals(NamedType x, NamedType y) { return x.GetHashCode() == y.GetHashCode(); } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <param name="obj">The object.</param> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public int GetHashCode(NamedType obj) { return obj.GetHashCode(); } /// <summary> /// Checks the specified NamedTypes for equality. /// </summary> /// <param name="a">The first <see cref="NamedType"/> to check.</param> /// <param name="b">The second <see cref="NamedType"/> to check.</param> /// <returns><c>true</c> if the parameters are equal; otherwise, <c>false</c>.</returns> public static bool operator ==(NamedType a, NamedType b) { return a.CompareTo(b) == 0; } /// <summary> /// Checks the specified NamedTypes for inequality. /// </summary> /// <param name="a">The first <see cref="NamedType"/> to check.</param> /// <param name="b">The second <see cref="NamedType"/> to check.</param> /// <returns><c>true</c> if the parameters are not equal; otherwise, <c>false</c>.</returns> public static bool operator !=(NamedType a, NamedType b) { return a.CompareTo(b) != 0; } #endregion } } }
using System; using System.Windows.Forms; using System.Drawing; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; namespace WeifenLuo.WinFormsUI.Docking { public delegate string GetPersistStringCallback(); public class DockContentHandler : IDisposable, IDockDragSource { public DockContentHandler(Form form) : this(form, null) { } public DockContentHandler(Form form, GetPersistStringCallback getPersistStringCallback) { if (!(form is IDockContent)) throw new ArgumentException(Strings.DockContent_Constructor_InvalidForm, "form"); m_form = form; m_getPersistStringCallback = getPersistStringCallback; m_events = new EventHandlerList(); Form.Disposed +=new EventHandler(Form_Disposed); Form.TextChanged += new EventHandler(Form_TextChanged); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { DockPanel = null; if (m_autoHideTab != null) m_autoHideTab.Dispose(); if (m_tab != null) m_tab.Dispose(); Form.Disposed -= new EventHandler(Form_Disposed); Form.TextChanged -= new EventHandler(Form_TextChanged); m_events.Dispose(); } } private Form m_form; public Form Form { get { return m_form; } } public IDockContent Content { get { return Form as IDockContent; } } private IDockContent m_previousActive = null; public IDockContent PreviousActive { get { return m_previousActive; } internal set { m_previousActive = value; } } private IDockContent m_nextActive = null; public IDockContent NextActive { get { return m_nextActive; } internal set { m_nextActive = value; } } private EventHandlerList m_events; private EventHandlerList Events { get { return m_events; } } private bool m_allowEndUserDocking = true; public bool AllowEndUserDocking { get { return m_allowEndUserDocking; } set { m_allowEndUserDocking = value; } } private double m_autoHidePortion = 0.25; public double AutoHidePortion { get { return m_autoHidePortion; } set { if (value <= 0) throw(new ArgumentOutOfRangeException(Strings.DockContentHandler_AutoHidePortion_OutOfRange)); if (m_autoHidePortion == value) return; m_autoHidePortion = value; if (DockPanel == null) return; if (DockPanel.ActiveAutoHideContent == Content) DockPanel.PerformLayout(); } } private bool m_closeButton = true; public bool CloseButton { get { return m_closeButton; } set { if (m_closeButton == value) return; m_closeButton = value; if (IsActiveContentHandler) Pane.RefreshChanges(); } } private bool m_closeButtonVisible = true; /// <summary> /// Determines whether the close button is visible on the content /// </summary> public bool CloseButtonVisible { get { return m_closeButtonVisible; } set { if (m_closeButtonVisible == value) return; m_closeButtonVisible = value; if (IsActiveContentHandler) Pane.RefreshChanges(); } } private bool IsActiveContentHandler { get { return Pane != null && Pane.ActiveContent != null && Pane.ActiveContent.DockHandler == this; } } private DockState DefaultDockState { get { if (ShowHint != DockState.Unknown && ShowHint != DockState.Hidden) return ShowHint; if ((DockAreas & DockAreas.Document) != 0) return DockState.Document; if ((DockAreas & DockAreas.DockRight) != 0) return DockState.DockRight; if ((DockAreas & DockAreas.DockLeft) != 0) return DockState.DockLeft; if ((DockAreas & DockAreas.DockBottom) != 0) return DockState.DockBottom; if ((DockAreas & DockAreas.DockTop) != 0) return DockState.DockTop; return DockState.Unknown; } } private DockState DefaultShowState { get { if (ShowHint != DockState.Unknown) return ShowHint; if ((DockAreas & DockAreas.Document) != 0) return DockState.Document; if ((DockAreas & DockAreas.DockRight) != 0) return DockState.DockRight; if ((DockAreas & DockAreas.DockLeft) != 0) return DockState.DockLeft; if ((DockAreas & DockAreas.DockBottom) != 0) return DockState.DockBottom; if ((DockAreas & DockAreas.DockTop) != 0) return DockState.DockTop; if ((DockAreas & DockAreas.Float) != 0) return DockState.Float; return DockState.Unknown; } } private DockAreas m_allowedAreas = DockAreas.DockLeft | DockAreas.DockRight | DockAreas.DockTop | DockAreas.DockBottom | DockAreas.Document | DockAreas.Float; public DockAreas DockAreas { get { return m_allowedAreas; } set { if (m_allowedAreas == value) return; if (!DockHelper.IsDockStateValid(DockState, value)) throw(new InvalidOperationException(Strings.DockContentHandler_DockAreas_InvalidValue)); m_allowedAreas = value; if (!DockHelper.IsDockStateValid(ShowHint, m_allowedAreas)) ShowHint = DockState.Unknown; } } private DockState m_dockState = DockState.Unknown; public DockState DockState { get { return m_dockState; } set { if (m_dockState == value) return; DockPanel.SuspendLayout(true); if (value == DockState.Hidden) IsHidden = true; else SetDockState(false, value, Pane); DockPanel.ResumeLayout(true, true); } } private DockPanel m_dockPanel = null; public DockPanel DockPanel { get { return m_dockPanel; } set { if (m_dockPanel == value) return; Pane = null; if (m_dockPanel != null) m_dockPanel.RemoveContent(Content); if (m_tab != null) { m_tab.Dispose(); m_tab = null; } if (m_autoHideTab != null) { m_autoHideTab.Dispose(); m_autoHideTab = null; } m_dockPanel = value; if (m_dockPanel != null) { m_dockPanel.AddContent(Content); Form.TopLevel = false; Form.FormBorderStyle = FormBorderStyle.None; Form.ShowInTaskbar = false; Form.WindowState = FormWindowState.Normal; if (Win32Helper.IsRunningOnMono) return; NativeMethods.SetWindowPos(Form.Handle, IntPtr.Zero, 0, 0, 0, 0, Win32.FlagsSetWindowPos.SWP_NOACTIVATE | Win32.FlagsSetWindowPos.SWP_NOMOVE | Win32.FlagsSetWindowPos.SWP_NOSIZE | Win32.FlagsSetWindowPos.SWP_NOZORDER | Win32.FlagsSetWindowPos.SWP_NOOWNERZORDER | Win32.FlagsSetWindowPos.SWP_FRAMECHANGED); } } } public Icon Icon { get { return Form.Icon; } } public DockPane Pane { get { return IsFloat ? FloatPane : PanelPane; } set { if (Pane == value) return; DockPanel.SuspendLayout(true); DockPane oldPane = Pane; SuspendSetDockState(); FloatPane = (value == null ? null : (value.IsFloat ? value : FloatPane)); PanelPane = (value == null ? null : (value.IsFloat ? PanelPane : value)); ResumeSetDockState(IsHidden, value != null ? value.DockState : DockState.Unknown, oldPane); DockPanel.ResumeLayout(true, true); } } private bool m_isHidden = true; public bool IsHidden { get { return m_isHidden; } set { if (m_isHidden == value) return; SetDockState(value, VisibleState, Pane); } } private string m_tabText = null; public string TabText { get { return m_tabText == null || m_tabText == "" ? Form.Text : m_tabText; } set { if (m_tabText == value) return; m_tabText = value; if (Pane != null) Pane.RefreshChanges(); } } private DockState m_visibleState = DockState.Unknown; public DockState VisibleState { get { return m_visibleState; } set { if (m_visibleState == value) return; SetDockState(IsHidden, value, Pane); } } private bool m_isFloat = false; public bool IsFloat { get { return m_isFloat; } set { if (m_isFloat == value) return; DockState visibleState = CheckDockState(value); if (visibleState == DockState.Unknown) throw new InvalidOperationException(Strings.DockContentHandler_IsFloat_InvalidValue); SetDockState(IsHidden, visibleState, Pane); } } [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")] public DockState CheckDockState(bool isFloat) { DockState dockState; if (isFloat) { if (!IsDockStateValid(DockState.Float)) dockState = DockState.Unknown; else dockState = DockState.Float; } else { dockState = (PanelPane != null) ? PanelPane.DockState : DefaultDockState; if (dockState != DockState.Unknown && !IsDockStateValid(dockState)) dockState = DockState.Unknown; } return dockState; } private DockPane m_panelPane = null; public DockPane PanelPane { get { return m_panelPane; } set { if (m_panelPane == value) return; if (value != null) { if (value.IsFloat || value.DockPanel != DockPanel) throw new InvalidOperationException(Strings.DockContentHandler_DockPane_InvalidValue); } DockPane oldPane = Pane; if (m_panelPane != null) RemoveFromPane(m_panelPane); m_panelPane = value; if (m_panelPane != null) { m_panelPane.AddContent(Content); SetDockState(IsHidden, IsFloat ? DockState.Float : m_panelPane.DockState, oldPane); } else SetDockState(IsHidden, DockState.Unknown, oldPane); } } private void RemoveFromPane(DockPane pane) { pane.RemoveContent(Content); SetPane(null); if (pane.Contents.Count == 0) pane.Dispose(); } private DockPane m_floatPane = null; public DockPane FloatPane { get { return m_floatPane; } set { if (m_floatPane == value) return; if (value != null) { if (!value.IsFloat || value.DockPanel != DockPanel) throw new InvalidOperationException(Strings.DockContentHandler_FloatPane_InvalidValue); } DockPane oldPane = Pane; if (m_floatPane != null) RemoveFromPane(m_floatPane); m_floatPane = value; if (m_floatPane != null) { m_floatPane.AddContent(Content); SetDockState(IsHidden, IsFloat ? DockState.Float : VisibleState, oldPane); } else SetDockState(IsHidden, DockState.Unknown, oldPane); } } private int m_countSetDockState = 0; private void SuspendSetDockState() { m_countSetDockState ++; } private void ResumeSetDockState() { m_countSetDockState --; if (m_countSetDockState < 0) m_countSetDockState = 0; } internal bool IsSuspendSetDockState { get { return m_countSetDockState != 0; } } private void ResumeSetDockState(bool isHidden, DockState visibleState, DockPane oldPane) { ResumeSetDockState(); SetDockState(isHidden, visibleState, oldPane); } internal void SetDockState(bool isHidden, DockState visibleState, DockPane oldPane) { if (IsSuspendSetDockState) return; if (DockPanel == null && visibleState != DockState.Unknown) throw new InvalidOperationException(Strings.DockContentHandler_SetDockState_NullPanel); if (visibleState == DockState.Hidden || (visibleState != DockState.Unknown && !IsDockStateValid(visibleState))) throw new InvalidOperationException(Strings.DockContentHandler_SetDockState_InvalidState); DockPanel dockPanel = DockPanel; if (dockPanel != null) dockPanel.SuspendLayout(true); SuspendSetDockState(); DockState oldDockState = DockState; if (m_isHidden != isHidden || oldDockState == DockState.Unknown) { m_isHidden = isHidden; } m_visibleState = visibleState; m_dockState = isHidden ? DockState.Hidden : visibleState; if (visibleState == DockState.Unknown) Pane = null; else { m_isFloat = (m_visibleState == DockState.Float); if (Pane == null) Pane = DockPanel.DockPaneFactory.CreateDockPane(Content, visibleState, true); else if (Pane.DockState != visibleState) { if (Pane.Contents.Count == 1) Pane.SetDockState(visibleState); else Pane = DockPanel.DockPaneFactory.CreateDockPane(Content, visibleState, true); } } if (Form.ContainsFocus) { if (DockState == DockState.Hidden || DockState == DockState.Unknown) { if (!Win32Helper.IsRunningOnMono) { DockPanel.ContentFocusManager.GiveUpFocus(Content); } } } SetPaneAndVisible(Pane); if (oldPane != null && !oldPane.IsDisposed && oldDockState == oldPane.DockState) RefreshDockPane(oldPane); if (Pane != null && DockState == Pane.DockState) { if ((Pane != oldPane) || (Pane == oldPane && oldDockState != oldPane.DockState)) { // Avoid early refresh of hidden AutoHide panes if ((Pane.DockWindow == null || Pane.DockWindow.Visible || Pane.IsHidden) && !Pane.IsAutoHide) { RefreshDockPane(Pane); } } } if (oldDockState != DockState) { if (DockState == DockState.Hidden || DockState == DockState.Unknown || DockHelper.IsDockStateAutoHide(DockState)) { if (!Win32Helper.IsRunningOnMono) { DockPanel.ContentFocusManager.RemoveFromList(Content); } } else if (!Win32Helper.IsRunningOnMono) { DockPanel.ContentFocusManager.AddToList(Content); } ResetAutoHidePortion(oldDockState, DockState); OnDockStateChanged(EventArgs.Empty); } ResumeSetDockState(); if (dockPanel != null) dockPanel.ResumeLayout(true, true); } private void ResetAutoHidePortion(DockState oldState, DockState newState) { if (oldState == newState || DockHelper.ToggleAutoHideState(oldState) == newState) return; switch (newState) { case DockState.DockTop: case DockState.DockTopAutoHide: AutoHidePortion = DockPanel.DockTopPortion; break; case DockState.DockLeft: case DockState.DockLeftAutoHide: AutoHidePortion = DockPanel.DockLeftPortion; break; case DockState.DockBottom: case DockState.DockBottomAutoHide: AutoHidePortion = DockPanel.DockBottomPortion; break; case DockState.DockRight: case DockState.DockRightAutoHide: AutoHidePortion = DockPanel.DockRightPortion; break; } } private static void RefreshDockPane(DockPane pane) { pane.RefreshChanges(); pane.ValidateActiveContent(); } internal string PersistString { get { return GetPersistStringCallback == null ? Form.GetType().ToString() : GetPersistStringCallback(); } } private GetPersistStringCallback m_getPersistStringCallback = null; public GetPersistStringCallback GetPersistStringCallback { get { return m_getPersistStringCallback; } set { m_getPersistStringCallback = value; } } private bool m_hideOnClose = false; public bool HideOnClose { get { return m_hideOnClose; } set { m_hideOnClose = value; } } private DockState m_showHint = DockState.Unknown; public DockState ShowHint { get { return m_showHint; } set { if (!DockHelper.IsDockStateValid(value, DockAreas)) throw (new InvalidOperationException(Strings.DockContentHandler_ShowHint_InvalidValue)); if (m_showHint == value) return; m_showHint = value; } } private bool m_isActivated = false; public bool IsActivated { get { return m_isActivated; } internal set { if (m_isActivated == value) return; m_isActivated = value; } } public bool IsDockStateValid(DockState dockState) { if (DockPanel != null && dockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.SystemMdi) return false; else return DockHelper.IsDockStateValid(dockState, DockAreas); } private string m_toolTipText = null; public string ToolTipText { get { return m_toolTipText; } set { m_toolTipText = value; } } public void Activate() { if (DockPanel == null) Form.Activate(); else if (Pane == null) Show(DockPanel); else { IsHidden = false; Pane.ActiveContent = Content; if (DockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.SystemMdi) { Form.Activate(); return; } else if (DockHelper.IsDockStateAutoHide(DockState)) { if (DockPanel.ActiveAutoHideContent != Content) { DockPanel.ActiveAutoHideContent = null; return; } } if (Form.ContainsFocus) return; if (Win32Helper.IsRunningOnMono) return; DockPanel.ContentFocusManager.Activate(Content); } } public void GiveUpFocus() { if (!Win32Helper.IsRunningOnMono) DockPanel.ContentFocusManager.GiveUpFocus(Content); } private IntPtr m_activeWindowHandle = IntPtr.Zero; internal IntPtr ActiveWindowHandle { get { return m_activeWindowHandle; } set { m_activeWindowHandle = value; } } public void Hide() { IsHidden = true; } internal void SetPaneAndVisible(DockPane pane) { SetPane(pane); SetVisible(); } private void SetPane(DockPane pane) { if (pane != null && pane.DockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.DockingMdi) { if (Form.Parent is DockPane) SetParent(null); if (Form.MdiParent != DockPanel.ParentForm) { FlagClipWindow = true; Form.MdiParent = DockPanel.ParentForm; } } else { FlagClipWindow = true; if (Form.MdiParent != null) Form.MdiParent = null; if (Form.TopLevel) Form.TopLevel = false; SetParent(pane); } } internal void SetVisible() { bool visible; if (IsHidden) visible = false; else if (Pane != null && Pane.DockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.DockingMdi) visible = true; else if (Pane != null && Pane.ActiveContent == Content) visible = true; else if (Pane != null && Pane.ActiveContent != Content) visible = false; else visible = Form.Visible; if (Form.Visible != visible) Form.Visible = visible; } private void SetParent(Control value) { if (Form.Parent == value) return; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Workaround of .Net Framework bug: // Change the parent of a control with focus may result in the first // MDI child form get activated. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! bool bRestoreFocus = false; if (Form.ContainsFocus) { // Suggested as a fix for a memory leak by bugreports if (value == null && !IsFloat) { if (!Win32Helper.IsRunningOnMono) { DockPanel.ContentFocusManager.GiveUpFocus(this.Content); } } else { DockPanel.SaveFocus(); bRestoreFocus = true; } } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Form.Parent = value; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Workaround of .Net Framework bug: // Change the parent of a control with focus may result in the first // MDI child form get activated. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if (bRestoreFocus) Activate(); // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! } public void Show() { if (DockPanel == null) Form.Show(); else Show(DockPanel); } public void Show(DockPanel dockPanel) { if (dockPanel == null) throw(new ArgumentNullException(Strings.DockContentHandler_Show_NullDockPanel)); if (DockState == DockState.Unknown) Show(dockPanel, DefaultShowState); else if (DockPanel != dockPanel) Show(dockPanel, DockState == DockState.Hidden ? m_visibleState : DockState); else Activate(); } public void Show(DockPanel dockPanel, DockState dockState) { if (dockPanel == null) throw(new ArgumentNullException(Strings.DockContentHandler_Show_NullDockPanel)); if (dockState == DockState.Unknown || dockState == DockState.Hidden) throw(new ArgumentException(Strings.DockContentHandler_Show_InvalidDockState)); dockPanel.SuspendLayout(true); DockPanel = dockPanel; if (dockState == DockState.Float) { if (FloatPane == null) Pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.Float, true); } else if (PanelPane == null) { DockPane paneExisting = null; foreach (DockPane pane in DockPanel.Panes) if (pane.DockState == dockState) { if (paneExisting == null || pane.IsActivated) paneExisting = pane; if (pane.IsActivated) break; } if (paneExisting == null) Pane = DockPanel.DockPaneFactory.CreateDockPane(Content, dockState, true); else Pane = paneExisting; } DockState = dockState; dockPanel.ResumeLayout(true, true); //we'll resume the layout before activating to ensure that the position Activate(); //and size of the form are finally processed before the form is shown } [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")] public void Show(DockPanel dockPanel, Rectangle floatWindowBounds) { if (dockPanel == null) throw(new ArgumentNullException(Strings.DockContentHandler_Show_NullDockPanel)); dockPanel.SuspendLayout(true); DockPanel = dockPanel; if (FloatPane == null) { IsHidden = true; // to reduce the screen flicker FloatPane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.Float, false); FloatPane.FloatWindow.StartPosition = FormStartPosition.Manual; } FloatPane.FloatWindow.Bounds = floatWindowBounds; Show(dockPanel, DockState.Float); Activate(); dockPanel.ResumeLayout(true, true); } public void Show(DockPane pane, IDockContent beforeContent) { if (pane == null) throw(new ArgumentNullException(Strings.DockContentHandler_Show_NullPane)); if (beforeContent != null && pane.Contents.IndexOf(beforeContent) == -1) throw(new ArgumentException(Strings.DockContentHandler_Show_InvalidBeforeContent)); pane.DockPanel.SuspendLayout(true); DockPanel = pane.DockPanel; Pane = pane; pane.SetContentIndex(Content, pane.Contents.IndexOf(beforeContent)); Show(); pane.DockPanel.ResumeLayout(true, true); } public void Show(DockPane previousPane, DockAlignment alignment, double proportion) { if (previousPane == null) throw(new ArgumentException(Strings.DockContentHandler_Show_InvalidPrevPane)); if (DockHelper.IsDockStateAutoHide(previousPane.DockState)) throw(new ArgumentException(Strings.DockContentHandler_Show_InvalidPrevPane)); previousPane.DockPanel.SuspendLayout(true); DockPanel = previousPane.DockPanel; DockPanel.DockPaneFactory.CreateDockPane(Content, previousPane, alignment, proportion, true); Show(); previousPane.DockPanel.ResumeLayout(true, true); } public void Close() { DockPanel dockPanel = DockPanel; if (dockPanel != null) dockPanel.SuspendLayout(true); Form.Close(); if (dockPanel != null) dockPanel.ResumeLayout(true, true); } private DockPaneStripBase.Tab m_tab = null; internal DockPaneStripBase.Tab GetTab(DockPaneStripBase dockPaneStrip) { if (m_tab == null) m_tab = dockPaneStrip.CreateTab(Content); return m_tab; } private IDisposable m_autoHideTab = null; internal IDisposable AutoHideTab { get { return m_autoHideTab; } set { m_autoHideTab = value; } } #region Events private static readonly object DockStateChangedEvent = new object(); public event EventHandler DockStateChanged { add { Events.AddHandler(DockStateChangedEvent, value); } remove { Events.RemoveHandler(DockStateChangedEvent, value); } } protected virtual void OnDockStateChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[DockStateChangedEvent]; if (handler != null) handler(this, e); } #endregion private void Form_Disposed(object sender, EventArgs e) { Dispose(); } private void Form_TextChanged(object sender, EventArgs e) { if (DockHelper.IsDockStateAutoHide(DockState)) DockPanel.RefreshAutoHideStrip(); else if (Pane != null) { if (Pane.FloatWindow != null) Pane.FloatWindow.SetText(); Pane.RefreshChanges(); } } private bool m_flagClipWindow = false; internal bool FlagClipWindow { get { return m_flagClipWindow; } set { if (m_flagClipWindow == value) return; m_flagClipWindow = value; if (m_flagClipWindow) Form.Region = new Region(Rectangle.Empty); else Form.Region = null; } } private ContextMenuStrip m_tabPageContextMenuStrip = null; public ContextMenuStrip TabPageContextMenuStrip { get { return m_tabPageContextMenuStrip; } set { m_tabPageContextMenuStrip = value; } } #region IDockDragSource Members Control IDragSource.DragControl { get { return Form; } } bool IDockDragSource.CanDockTo(DockPane pane) { if (!IsDockStateValid(pane.DockState)) return false; if (Pane == pane && pane.DisplayingContents.Count == 1) return false; return true; } Rectangle IDockDragSource.BeginDrag(Point ptMouse) { Size size; DockPane floatPane = this.FloatPane; if (DockState == DockState.Float || floatPane == null || floatPane.FloatWindow.NestedPanes.Count != 1) size = DockPanel.DefaultFloatWindowSize; else size = floatPane.FloatWindow.Size; Point location; Rectangle rectPane = Pane.ClientRectangle; if (DockState == DockState.Document) { if (Pane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) location = new Point(rectPane.Left, rectPane.Bottom - size.Height); else location = new Point(rectPane.Left, rectPane.Top); } else { location = new Point(rectPane.Left, rectPane.Bottom); location.Y -= size.Height; } location = Pane.PointToScreen(location); if (ptMouse.X > location.X + size.Width) location.X += ptMouse.X - (location.X + size.Width) + Measures.SplitterSize; return new Rectangle(location, size); } void IDockDragSource.EndDrag() { } public void FloatAt(Rectangle floatWindowBounds) { // TODO: where is the pane used? DockPane pane = DockPanel.DockPaneFactory.CreateDockPane(Content, floatWindowBounds, true); } public void DockTo(DockPane pane, DockStyle dockStyle, int contentIndex) { if (dockStyle == DockStyle.Fill) { bool samePane = (Pane == pane); if (!samePane) Pane = pane; int visiblePanes = 0; int convertedIndex = 0; while (visiblePanes <= contentIndex && convertedIndex < Pane.Contents.Count) { DockContent window = Pane.Contents[convertedIndex] as DockContent; if (window != null && !window.IsHidden) ++visiblePanes; ++convertedIndex; } contentIndex = Math.Min(Math.Max(0, convertedIndex-1), Pane.Contents.Count - 1); if (contentIndex == -1 || !samePane) pane.SetContentIndex(Content, contentIndex); else { DockContentCollection contents = pane.Contents; int oldIndex = contents.IndexOf(Content); int newIndex = contentIndex; if (oldIndex < newIndex) { newIndex += 1; if (newIndex > contents.Count -1) newIndex = -1; } pane.SetContentIndex(Content, newIndex); } } else { DockPane paneFrom = DockPanel.DockPaneFactory.CreateDockPane(Content, pane.DockState, true); INestedPanesContainer container = pane.NestedPanesContainer; if (dockStyle == DockStyle.Left) paneFrom.DockTo(container, pane, DockAlignment.Left, 0.5); else if (dockStyle == DockStyle.Right) paneFrom.DockTo(container, pane, DockAlignment.Right, 0.5); else if (dockStyle == DockStyle.Top) paneFrom.DockTo(container, pane, DockAlignment.Top, 0.5); else if (dockStyle == DockStyle.Bottom) paneFrom.DockTo(container, pane, DockAlignment.Bottom, 0.5); paneFrom.DockState = pane.DockState; } } public void DockTo(DockPanel panel, DockStyle dockStyle) { if (panel != DockPanel) throw new ArgumentException(Strings.IDockDragSource_DockTo_InvalidPanel, "panel"); DockPane pane; if (dockStyle == DockStyle.Top) pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.DockTop, true); else if (dockStyle == DockStyle.Bottom) pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.DockBottom, true); else if (dockStyle == DockStyle.Left) pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.DockLeft, true); else if (dockStyle == DockStyle.Right) pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.DockRight, true); else if (dockStyle == DockStyle.Fill) pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.Document, true); else return; } #endregion } }
using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Diagnostics.CodeAnalysis; namespace WeifenLuo.WinFormsUI.Docking { [ToolboxItem(false)] public partial class DockPane : UserControl, IDockDragSource { public enum AppearanceStyle { ToolWindow, Document } private enum HitTestArea { Caption, TabStrip, Content, None } private struct HitTestResult { public HitTestArea HitArea; public int Index; public HitTestResult(HitTestArea hitTestArea, int index) { HitArea = hitTestArea; Index = index; } } private DockPaneCaptionBase m_captionControl; private DockPaneCaptionBase CaptionControl { get { return m_captionControl; } } private DockPaneStripBase m_tabStripControl; public DockPaneStripBase TabStripControl { get { return m_tabStripControl; } } internal protected DockPane(IDockContent content, DockState visibleState, bool show) { InternalConstruct(content, visibleState, false, Rectangle.Empty, null, DockAlignment.Right, 0.5, show); } [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "1#")] internal protected DockPane(IDockContent content, FloatWindow floatWindow, bool show) { if (floatWindow == null) throw new ArgumentNullException("floatWindow"); InternalConstruct(content, DockState.Float, false, Rectangle.Empty, floatWindow.NestedPanes.GetDefaultPreviousPane(this), DockAlignment.Right, 0.5, show); } internal protected DockPane(IDockContent content, DockPane previousPane, DockAlignment alignment, double proportion, bool show) { if (previousPane == null) throw (new ArgumentNullException("previousPane")); InternalConstruct(content, previousPane.DockState, false, Rectangle.Empty, previousPane, alignment, proportion, show); } [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "1#")] internal protected DockPane(IDockContent content, Rectangle floatWindowBounds, bool show) { InternalConstruct(content, DockState.Float, true, floatWindowBounds, null, DockAlignment.Right, 0.5, show); } private void InternalConstruct(IDockContent content, DockState dockState, bool flagBounds, Rectangle floatWindowBounds, DockPane prevPane, DockAlignment alignment, double proportion, bool show) { if (dockState == DockState.Hidden || dockState == DockState.Unknown) throw new ArgumentException(Strings.DockPane_SetDockState_InvalidState); if (content == null) throw new ArgumentNullException(Strings.DockPane_Constructor_NullContent); if (content.DockHandler.DockPanel == null) throw new ArgumentException(Strings.DockPane_Constructor_NullDockPanel); SuspendLayout(); SetStyle(ControlStyles.Selectable, false); m_isFloat = (dockState == DockState.Float); m_contents = new DockContentCollection(); m_displayingContents = new DockContentCollection(this); m_dockPanel = content.DockHandler.DockPanel; m_dockPanel.AddPane(this); m_splitter = content.DockHandler.DockPanel.Extender.DockPaneSplitterControlFactory.CreateSplitterControl(this); m_nestedDockingStatus = new NestedDockingStatus(this); m_captionControl = DockPanel.DockPaneCaptionFactory.CreateDockPaneCaption(this); m_tabStripControl = DockPanel.DockPaneStripFactory.CreateDockPaneStrip(this); Controls.AddRange(new Control[] { m_captionControl, m_tabStripControl }); DockPanel.SuspendLayout(true); if (flagBounds) FloatWindow = DockPanel.FloatWindowFactory.CreateFloatWindow(DockPanel, this, floatWindowBounds); else if (prevPane != null) DockTo(prevPane.NestedPanesContainer, prevPane, alignment, proportion); SetDockState(dockState); if (show) content.DockHandler.Pane = this; else if (this.IsFloat) content.DockHandler.FloatPane = this; else content.DockHandler.PanelPane = this; ResumeLayout(); DockPanel.ResumeLayout(true, true); } private bool m_isDisposing; protected override void Dispose(bool disposing) { if (disposing) { // IMPORTANT: avoid nested call into this method on Mono. // https://github.com/dockpanelsuite/dockpanelsuite/issues/16 if (Win32Helper.IsRunningOnMono) { if (m_isDisposing) return; m_isDisposing = true; } m_dockState = DockState.Unknown; if (NestedPanesContainer != null) NestedPanesContainer.NestedPanes.Remove(this); if (DockPanel != null) { DockPanel.RemovePane(this); m_dockPanel = null; } Splitter.Dispose(); if (m_autoHidePane != null) m_autoHidePane.Dispose(); } base.Dispose(disposing); } private IDockContent m_activeContent = null; public virtual IDockContent ActiveContent { get { return m_activeContent; } set { if (ActiveContent == value) return; if (value != null) { if (!DisplayingContents.Contains(value)) throw (new InvalidOperationException(Strings.DockPane_ActiveContent_InvalidValue)); } else { if (DisplayingContents.Count != 0) throw (new InvalidOperationException(Strings.DockPane_ActiveContent_InvalidValue)); } IDockContent oldValue = m_activeContent; if (DockPanel.ActiveAutoHideContent == oldValue) DockPanel.ActiveAutoHideContent = null; m_activeContent = value; if (DockPanel.DocumentStyle == DocumentStyle.DockingMdi && DockState == DockState.Document) { if (m_activeContent != null) m_activeContent.DockHandler.Form.BringToFront(); } else { if (m_activeContent != null) m_activeContent.DockHandler.SetVisible(); if (oldValue != null && DisplayingContents.Contains(oldValue)) oldValue.DockHandler.SetVisible(); if (IsActivated && m_activeContent != null) m_activeContent.DockHandler.Activate(); } if (FloatWindow != null) FloatWindow.SetText(); if (DockPanel.DocumentStyle == DocumentStyle.DockingMdi && DockState == DockState.Document) RefreshChanges(false); // delayed layout to reduce screen flicker else RefreshChanges(); if (m_activeContent != null) TabStripControl.EnsureTabVisible(m_activeContent); } } private bool m_allowDockDragAndDrop = true; public virtual bool AllowDockDragAndDrop { get { return m_allowDockDragAndDrop; } set { m_allowDockDragAndDrop = value; } } private IDisposable m_autoHidePane = null; internal IDisposable AutoHidePane { get { return m_autoHidePane; } set { m_autoHidePane = value; } } private object m_autoHideTabs = null; internal object AutoHideTabs { get { return m_autoHideTabs; } set { m_autoHideTabs = value; } } private object TabPageContextMenu { get { IDockContent content = ActiveContent; if (content == null) return null; if (content.DockHandler.TabPageContextMenuStrip != null) return content.DockHandler.TabPageContextMenuStrip; else return null; } } internal bool HasTabPageContextMenu { get { return TabPageContextMenu != null; } } internal void ShowTabPageContextMenu(Control control, Point position) { object menu = TabPageContextMenu; if (menu == null) return; ContextMenuStrip contextMenuStrip = menu as ContextMenuStrip; if (contextMenuStrip != null) { contextMenuStrip.Show(control, position); return; } } private Rectangle CaptionRectangle { get { if (!HasCaption) return Rectangle.Empty; Rectangle rectWindow = DisplayingRectangle; int x, y, width; x = rectWindow.X; y = rectWindow.Y; width = rectWindow.Width; int height = CaptionControl.MeasureHeight(); return new Rectangle(x, y, width, height); } } internal Rectangle ContentRectangle { get { Rectangle rectWindow = DisplayingRectangle; Rectangle rectCaption = CaptionRectangle; Rectangle rectTabStrip = TabStripRectangle; int x = rectWindow.X; int y = rectWindow.Y + (rectCaption.IsEmpty ? 0 : rectCaption.Height); if (DockState == DockState.Document && DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Top) y += rectTabStrip.Height; int width = rectWindow.Width; int height = rectWindow.Height - rectCaption.Height - rectTabStrip.Height; return new Rectangle(x, y, width, height); } } internal Rectangle TabStripRectangle { get { if (Appearance == AppearanceStyle.ToolWindow) return TabStripRectangle_ToolWindow; else return TabStripRectangle_Document; } } private Rectangle TabStripRectangle_ToolWindow { get { if (DisplayingContents.Count <= 1 || IsAutoHide) return Rectangle.Empty; Rectangle rectWindow = DisplayingRectangle; int width = rectWindow.Width; int height = TabStripControl.MeasureHeight(); int x = rectWindow.X; int y = rectWindow.Bottom - height; Rectangle rectCaption = CaptionRectangle; if (rectCaption.Contains(x, y)) y = rectCaption.Y + rectCaption.Height; return new Rectangle(x, y, width, height); } } private Rectangle TabStripRectangle_Document { get { if (DisplayingContents.Count == 0) return Rectangle.Empty; if (DisplayingContents.Count == 1 && DockPanel.DocumentStyle == DocumentStyle.DockingSdi) return Rectangle.Empty; Rectangle rectWindow = DisplayingRectangle; int x = rectWindow.X; int width = rectWindow.Width; int height = TabStripControl.MeasureHeight(); int y = 0; if (DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) y = rectWindow.Height - height; else y = rectWindow.Y; return new Rectangle(x, y, width, height); } } public virtual string CaptionText { get { return ActiveContent == null ? string.Empty : ActiveContent.DockHandler.TabText; } } private DockContentCollection m_contents; public DockContentCollection Contents { get { return m_contents; } } private DockContentCollection m_displayingContents; public DockContentCollection DisplayingContents { get { return m_displayingContents; } } private DockPanel m_dockPanel; public DockPanel DockPanel { get { return m_dockPanel; } } private bool HasCaption { get { if (DockState == DockState.Document || DockState == DockState.Hidden || DockState == DockState.Unknown || (DockState == DockState.Float && FloatWindow.VisibleNestedPanes.Count <= 1)) return false; else return true; } } private bool m_isActivated = false; public bool IsActivated { get { return m_isActivated; } } internal void SetIsActivated(bool value) { if (m_isActivated == value) return; m_isActivated = value; if (DockState != DockState.Document) RefreshChanges(false); OnIsActivatedChanged(EventArgs.Empty); } private bool m_isActiveDocumentPane = false; public bool IsActiveDocumentPane { get { return m_isActiveDocumentPane; } } internal void SetIsActiveDocumentPane(bool value) { if (m_isActiveDocumentPane == value) return; m_isActiveDocumentPane = value; if (DockState == DockState.Document) RefreshChanges(); OnIsActiveDocumentPaneChanged(EventArgs.Empty); } public bool IsDockStateValid(DockState dockState) { foreach (IDockContent content in Contents) if (!content.DockHandler.IsDockStateValid(dockState)) return false; return true; } public bool IsAutoHide { get { return DockHelper.IsDockStateAutoHide(DockState); } } public AppearanceStyle Appearance { get { return (DockState == DockState.Document) ? AppearanceStyle.Document : AppearanceStyle.ToolWindow; } } public Rectangle DisplayingRectangle { get { return ClientRectangle; } } public void Activate() { if (DockHelper.IsDockStateAutoHide(DockState) && DockPanel.ActiveAutoHideContent != ActiveContent) DockPanel.ActiveAutoHideContent = ActiveContent; else if (!IsActivated && ActiveContent != null) ActiveContent.DockHandler.Activate(); } internal void AddContent(IDockContent content) { if (Contents.Contains(content)) return; Contents.Add(content); } internal void Close() { Dispose(); } public void CloseActiveContent() { CloseContent(ActiveContent); } internal void CloseContent(IDockContent content) { if (content == null) return; if (!content.DockHandler.CloseButton) return; DockPanel dockPanel = DockPanel; dockPanel.SuspendLayout(true); try { if (content.DockHandler.HideOnClose) { content.DockHandler.Hide(); NestedDockingStatus.NestedPanes.SwitchPaneWithFirstChild(this); } else content.DockHandler.Close(); } finally { dockPanel.ResumeLayout(true, true); } } private HitTestResult GetHitTest(Point ptMouse) { Point ptMouseClient = PointToClient(ptMouse); Rectangle rectCaption = CaptionRectangle; if (rectCaption.Contains(ptMouseClient)) return new HitTestResult(HitTestArea.Caption, -1); Rectangle rectContent = ContentRectangle; if (rectContent.Contains(ptMouseClient)) return new HitTestResult(HitTestArea.Content, -1); Rectangle rectTabStrip = TabStripRectangle; if (rectTabStrip.Contains(ptMouseClient)) return new HitTestResult(HitTestArea.TabStrip, TabStripControl.HitTest(TabStripControl.PointToClient(ptMouse))); return new HitTestResult(HitTestArea.None, -1); } private bool m_isHidden = true; public bool IsHidden { get { return m_isHidden; } } private void SetIsHidden(bool value) { if (m_isHidden == value) return; m_isHidden = value; if (DockHelper.IsDockStateAutoHide(DockState)) { DockPanel.RefreshAutoHideStrip(); DockPanel.PerformLayout(); } else if (NestedPanesContainer != null) ((Control)NestedPanesContainer).PerformLayout(); } protected override void OnLayout(LayoutEventArgs e) { SetIsHidden(DisplayingContents.Count == 0); if (!IsHidden) { CaptionControl.Bounds = CaptionRectangle; TabStripControl.Bounds = TabStripRectangle; SetContentBounds(); foreach (IDockContent content in Contents) { if (DisplayingContents.Contains(content)) if (content.DockHandler.FlagClipWindow && content.DockHandler.Form.Visible) content.DockHandler.FlagClipWindow = false; } } base.OnLayout(e); } internal void SetContentBounds() { Rectangle rectContent = ContentRectangle; if (DockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.DockingMdi) rectContent = DockPanel.RectangleToMdiClient(RectangleToScreen(rectContent)); Rectangle rectInactive = new Rectangle(-rectContent.Width, rectContent.Y, rectContent.Width, rectContent.Height); foreach (IDockContent content in Contents) if (content.DockHandler.Pane == this) { if (content == ActiveContent) content.DockHandler.Form.Bounds = rectContent; else content.DockHandler.Form.Bounds = rectInactive; } } internal void RefreshChanges() { RefreshChanges(true); } private void RefreshChanges(bool performLayout) { if (IsDisposed) return; CaptionControl.RefreshChanges(); TabStripControl.RefreshChanges(); if (DockState == DockState.Float && FloatWindow != null) FloatWindow.RefreshChanges(); if (DockHelper.IsDockStateAutoHide(DockState) && DockPanel != null) { DockPanel.RefreshAutoHideStrip(); DockPanel.PerformLayout(); } if (performLayout) PerformLayout(); } internal void RemoveContent(IDockContent content) { if (!Contents.Contains(content)) return; Contents.Remove(content); } public void SetContentIndex(IDockContent content, int index) { int oldIndex = Contents.IndexOf(content); if (oldIndex == -1) throw (new ArgumentException(Strings.DockPane_SetContentIndex_InvalidContent)); if (index < 0 || index > Contents.Count - 1) if (index != -1) throw (new ArgumentOutOfRangeException(Strings.DockPane_SetContentIndex_InvalidIndex)); if (oldIndex == index) return; if (oldIndex == Contents.Count - 1 && index == -1) return; Contents.Remove(content); if (index == -1) Contents.Add(content); else if (oldIndex < index) Contents.AddAt(content, index - 1); else Contents.AddAt(content, index); RefreshChanges(); } private void SetParent() { if (DockState == DockState.Unknown || DockState == DockState.Hidden) { SetParent(null); Splitter.Parent = null; } else if (DockState == DockState.Float) { SetParent(FloatWindow); Splitter.Parent = FloatWindow; } else if (DockHelper.IsDockStateAutoHide(DockState)) { SetParent(DockPanel.AutoHideControl); Splitter.Parent = null; } else { SetParent(DockPanel.DockWindows[DockState]); Splitter.Parent = Parent; } } private void SetParent(Control value) { if (Parent == value) return; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Workaround of .Net Framework bug: // Change the parent of a control with focus may result in the first // MDI child form get activated. //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! IDockContent contentFocused = GetFocusedContent(); if (contentFocused != null) DockPanel.SaveFocus(); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Parent = value; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Workaround of .Net Framework bug: // Change the parent of a control with focus may result in the first // MDI child form get activated. //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if (contentFocused != null) contentFocused.DockHandler.Activate(); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! } public new void Show() { Activate(); } internal void TestDrop(IDockDragSource dragSource, DockOutlineBase dockOutline) { if (!dragSource.CanDockTo(this)) return; Point ptMouse = Control.MousePosition; HitTestResult hitTestResult = GetHitTest(ptMouse); if (hitTestResult.HitArea == HitTestArea.Caption) dockOutline.Show(this, -1); else if (hitTestResult.HitArea == HitTestArea.TabStrip && hitTestResult.Index != -1) dockOutline.Show(this, hitTestResult.Index); } internal void ValidateActiveContent() { if (ActiveContent == null) { if (DisplayingContents.Count != 0) ActiveContent = DisplayingContents[0]; return; } if (DisplayingContents.IndexOf(ActiveContent) >= 0) return; IDockContent prevVisible = null; for (int i = Contents.IndexOf(ActiveContent) - 1; i >= 0; i--) if (Contents[i].DockHandler.DockState == DockState) { prevVisible = Contents[i]; break; } IDockContent nextVisible = null; for (int i = Contents.IndexOf(ActiveContent) + 1; i < Contents.Count; i++) if (Contents[i].DockHandler.DockState == DockState) { nextVisible = Contents[i]; break; } if (prevVisible != null) ActiveContent = prevVisible; else if (nextVisible != null) ActiveContent = nextVisible; else ActiveContent = null; } private static readonly object DockStateChangedEvent = new object(); public event EventHandler DockStateChanged { add { Events.AddHandler(DockStateChangedEvent, value); } remove { Events.RemoveHandler(DockStateChangedEvent, value); } } protected virtual void OnDockStateChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[DockStateChangedEvent]; if (handler != null) handler(this, e); } private static readonly object IsActivatedChangedEvent = new object(); public event EventHandler IsActivatedChanged { add { Events.AddHandler(IsActivatedChangedEvent, value); } remove { Events.RemoveHandler(IsActivatedChangedEvent, value); } } protected virtual void OnIsActivatedChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[IsActivatedChangedEvent]; if (handler != null) handler(this, e); } private static readonly object IsActiveDocumentPaneChangedEvent = new object(); public event EventHandler IsActiveDocumentPaneChanged { add { Events.AddHandler(IsActiveDocumentPaneChangedEvent, value); } remove { Events.RemoveHandler(IsActiveDocumentPaneChangedEvent, value); } } protected virtual void OnIsActiveDocumentPaneChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[IsActiveDocumentPaneChangedEvent]; if (handler != null) handler(this, e); } public DockWindow DockWindow { get { return (m_nestedDockingStatus.NestedPanes == null) ? null : m_nestedDockingStatus.NestedPanes.Container as DockWindow; } set { DockWindow oldValue = DockWindow; if (oldValue == value) return; DockTo(value); } } public FloatWindow FloatWindow { get { return (m_nestedDockingStatus.NestedPanes == null) ? null : m_nestedDockingStatus.NestedPanes.Container as FloatWindow; } set { FloatWindow oldValue = FloatWindow; if (oldValue == value) return; DockTo(value); } } private NestedDockingStatus m_nestedDockingStatus; public NestedDockingStatus NestedDockingStatus { get { return m_nestedDockingStatus; } } private bool m_isFloat; public bool IsFloat { get { return m_isFloat; } } public INestedPanesContainer NestedPanesContainer { get { if (NestedDockingStatus.NestedPanes == null) return null; else return NestedDockingStatus.NestedPanes.Container; } } private DockState m_dockState = DockState.Unknown; public DockState DockState { get { return m_dockState; } set { SetDockState(value); } } public DockPane SetDockState(DockState value) { if (value == DockState.Unknown || value == DockState.Hidden) throw new InvalidOperationException(Strings.DockPane_SetDockState_InvalidState); if ((value == DockState.Float) == this.IsFloat) { InternalSetDockState(value); return this; } if (DisplayingContents.Count == 0) return null; IDockContent firstContent = null; for (int i = 0; i < DisplayingContents.Count; i++) { IDockContent content = DisplayingContents[i]; if (content.DockHandler.IsDockStateValid(value)) { firstContent = content; break; } } if (firstContent == null) return null; firstContent.DockHandler.DockState = value; DockPane pane = firstContent.DockHandler.Pane; DockPanel.SuspendLayout(true); for (int i = 0; i < DisplayingContents.Count; i++) { IDockContent content = DisplayingContents[i]; if (content.DockHandler.IsDockStateValid(value)) content.DockHandler.Pane = pane; } DockPanel.ResumeLayout(true, true); return pane; } private void InternalSetDockState(DockState value) { if (m_dockState == value) return; DockState oldDockState = m_dockState; INestedPanesContainer oldContainer = NestedPanesContainer; m_dockState = value; SuspendRefreshStateChange(); IDockContent contentFocused = GetFocusedContent(); if (contentFocused != null) DockPanel.SaveFocus(); if (!IsFloat) DockWindow = DockPanel.DockWindows[DockState]; else if (FloatWindow == null) FloatWindow = DockPanel.FloatWindowFactory.CreateFloatWindow(DockPanel, this); if (contentFocused != null) { if (!Win32Helper.IsRunningOnMono) { DockPanel.ContentFocusManager.Activate(contentFocused); } } ResumeRefreshStateChange(oldContainer, oldDockState); } private int m_countRefreshStateChange = 0; private void SuspendRefreshStateChange() { m_countRefreshStateChange++; DockPanel.SuspendLayout(true); } private void ResumeRefreshStateChange() { m_countRefreshStateChange--; System.Diagnostics.Debug.Assert(m_countRefreshStateChange >= 0); DockPanel.ResumeLayout(true, true); } private bool IsRefreshStateChangeSuspended { get { return m_countRefreshStateChange != 0; } } private void ResumeRefreshStateChange(INestedPanesContainer oldContainer, DockState oldDockState) { ResumeRefreshStateChange(); RefreshStateChange(oldContainer, oldDockState); } private void RefreshStateChange(INestedPanesContainer oldContainer, DockState oldDockState) { if (IsRefreshStateChangeSuspended) return; SuspendRefreshStateChange(); DockPanel.SuspendLayout(true); IDockContent contentFocused = GetFocusedContent(); if (contentFocused != null) DockPanel.SaveFocus(); SetParent(); if (ActiveContent != null) ActiveContent.DockHandler.SetDockState(ActiveContent.DockHandler.IsHidden, DockState, ActiveContent.DockHandler.Pane); foreach (IDockContent content in Contents) { if (content.DockHandler.Pane == this) content.DockHandler.SetDockState(content.DockHandler.IsHidden, DockState, content.DockHandler.Pane); } if (oldContainer != null) { Control oldContainerControl = (Control)oldContainer; if (oldContainer.DockState == oldDockState && !oldContainerControl.IsDisposed) oldContainerControl.PerformLayout(); } if (DockHelper.IsDockStateAutoHide(oldDockState)) DockPanel.RefreshActiveAutoHideContent(); if (NestedPanesContainer.DockState == DockState) ((Control)NestedPanesContainer).PerformLayout(); if (DockHelper.IsDockStateAutoHide(DockState)) DockPanel.RefreshActiveAutoHideContent(); if (DockHelper.IsDockStateAutoHide(oldDockState) || DockHelper.IsDockStateAutoHide(DockState)) { DockPanel.RefreshAutoHideStrip(); DockPanel.PerformLayout(); } ResumeRefreshStateChange(); if (contentFocused != null) contentFocused.DockHandler.Activate(); DockPanel.ResumeLayout(true, true); if (oldDockState != DockState) OnDockStateChanged(EventArgs.Empty); } private IDockContent GetFocusedContent() { IDockContent contentFocused = null; foreach (IDockContent content in Contents) { if (content.DockHandler.Form.ContainsFocus) { contentFocused = content; break; } } return contentFocused; } public DockPane DockTo(INestedPanesContainer container) { if (container == null) throw new InvalidOperationException(Strings.DockPane_DockTo_NullContainer); DockAlignment alignment; if (container.DockState == DockState.DockLeft || container.DockState == DockState.DockRight) alignment = DockAlignment.Bottom; else alignment = DockAlignment.Right; return DockTo(container, container.NestedPanes.GetDefaultPreviousPane(this), alignment, 0.5); } public DockPane DockTo(INestedPanesContainer container, DockPane previousPane, DockAlignment alignment, double proportion) { if (container == null) throw new InvalidOperationException(Strings.DockPane_DockTo_NullContainer); if (container.IsFloat == this.IsFloat) { InternalAddToDockList(container, previousPane, alignment, proportion); return this; } IDockContent firstContent = GetFirstContent(container.DockState); if (firstContent == null) return null; DockPane pane; DockPanel.DummyContent.DockPanel = DockPanel; if (container.IsFloat) pane = DockPanel.DockPaneFactory.CreateDockPane(DockPanel.DummyContent, (FloatWindow)container, true); else pane = DockPanel.DockPaneFactory.CreateDockPane(DockPanel.DummyContent, container.DockState, true); pane.DockTo(container, previousPane, alignment, proportion); SetVisibleContentsToPane(pane); DockPanel.DummyContent.DockPanel = null; return pane; } private void SetVisibleContentsToPane(DockPane pane) { SetVisibleContentsToPane(pane, ActiveContent); } private void SetVisibleContentsToPane(DockPane pane, IDockContent activeContent) { for (int i = 0; i < DisplayingContents.Count; i++) { IDockContent content = DisplayingContents[i]; if (content.DockHandler.IsDockStateValid(pane.DockState)) { content.DockHandler.Pane = pane; i--; } } if (activeContent.DockHandler.Pane == pane) pane.ActiveContent = activeContent; } private void InternalAddToDockList(INestedPanesContainer container, DockPane prevPane, DockAlignment alignment, double proportion) { if ((container.DockState == DockState.Float) != IsFloat) throw new InvalidOperationException(Strings.DockPane_DockTo_InvalidContainer); int count = container.NestedPanes.Count; if (container.NestedPanes.Contains(this)) count--; if (prevPane == null && count > 0) throw new InvalidOperationException(Strings.DockPane_DockTo_NullPrevPane); if (prevPane != null && !container.NestedPanes.Contains(prevPane)) throw new InvalidOperationException(Strings.DockPane_DockTo_NoPrevPane); if (prevPane == this) throw new InvalidOperationException(Strings.DockPane_DockTo_SelfPrevPane); INestedPanesContainer oldContainer = NestedPanesContainer; DockState oldDockState = DockState; container.NestedPanes.Add(this); NestedDockingStatus.SetStatus(container.NestedPanes, prevPane, alignment, proportion); if (DockHelper.IsDockWindowState(DockState)) m_dockState = container.DockState; RefreshStateChange(oldContainer, oldDockState); } public void SetNestedDockingProportion(double proportion) { NestedDockingStatus.SetStatus(NestedDockingStatus.NestedPanes, NestedDockingStatus.PreviousPane, NestedDockingStatus.Alignment, proportion); if (NestedPanesContainer != null) ((Control)NestedPanesContainer).PerformLayout(); } public DockPane Float() { DockPanel.SuspendLayout(true); IDockContent activeContent = ActiveContent; DockPane floatPane = GetFloatPaneFromContents(); if (floatPane == null) { IDockContent firstContent = GetFirstContent(DockState.Float); if (firstContent == null) { DockPanel.ResumeLayout(true, true); return null; } floatPane = DockPanel.DockPaneFactory.CreateDockPane(firstContent, DockState.Float, true); } SetVisibleContentsToPane(floatPane, activeContent); DockPanel.ResumeLayout(true, true); return floatPane; } private DockPane GetFloatPaneFromContents() { DockPane floatPane = null; for (int i = 0; i < DisplayingContents.Count; i++) { IDockContent content = DisplayingContents[i]; if (!content.DockHandler.IsDockStateValid(DockState.Float)) continue; if (floatPane != null && content.DockHandler.FloatPane != floatPane) return null; else floatPane = content.DockHandler.FloatPane; } return floatPane; } private IDockContent GetFirstContent(DockState dockState) { for (int i = 0; i < DisplayingContents.Count; i++) { IDockContent content = DisplayingContents[i]; if (content.DockHandler.IsDockStateValid(dockState)) return content; } return null; } public void RestoreToPanel() { DockPanel.SuspendLayout(true); IDockContent activeContent = DockPanel.ActiveContent; for (int i = DisplayingContents.Count - 1; i >= 0; i--) { IDockContent content = DisplayingContents[i]; if (content.DockHandler.CheckDockState(false) != DockState.Unknown) content.DockHandler.IsFloat = false; } DockPanel.ResumeLayout(true, true); } [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] protected override void WndProc(ref Message m) { if (m.Msg == (int)Win32.Msgs.WM_MOUSEACTIVATE) Activate(); base.WndProc(ref m); } #region IDockDragSource Members #region IDragSource Members Control IDragSource.DragControl { get { return this; } } public IDockContent MouseOverTab { get; set; } #endregion bool IDockDragSource.IsDockStateValid(DockState dockState) { return IsDockStateValid(dockState); } bool IDockDragSource.CanDockTo(DockPane pane) { if (!IsDockStateValid(pane.DockState)) return false; if (pane == this) return false; return true; } Rectangle IDockDragSource.BeginDrag(Point ptMouse) { Point location = PointToScreen(new Point(0, 0)); Size size; DockPane floatPane = ActiveContent.DockHandler.FloatPane; if (DockState == DockState.Float || floatPane == null || floatPane.FloatWindow.NestedPanes.Count != 1) size = DockPanel.DefaultFloatWindowSize; else size = floatPane.FloatWindow.Size; if (ptMouse.X > location.X + size.Width) location.X += ptMouse.X - (location.X + size.Width) + Measures.SplitterSize; return new Rectangle(location, size); } void IDockDragSource.EndDrag() { } public void FloatAt(Rectangle floatWindowBounds) { if (FloatWindow == null || FloatWindow.NestedPanes.Count != 1) FloatWindow = DockPanel.FloatWindowFactory.CreateFloatWindow(DockPanel, this, floatWindowBounds); else FloatWindow.Bounds = floatWindowBounds; DockState = DockState.Float; NestedDockingStatus.NestedPanes.SwitchPaneWithFirstChild(this); } public void DockTo(DockPane pane, DockStyle dockStyle, int contentIndex) { if (dockStyle == DockStyle.Fill) { IDockContent activeContent = ActiveContent; for (int i = Contents.Count - 1; i >= 0; i--) { IDockContent c = Contents[i]; if (c.DockHandler.DockState == DockState) { c.DockHandler.Pane = pane; if (contentIndex != -1) pane.SetContentIndex(c, contentIndex); } } pane.ActiveContent = activeContent; } else { if (dockStyle == DockStyle.Left) DockTo(pane.NestedPanesContainer, pane, DockAlignment.Left, 0.5); else if (dockStyle == DockStyle.Right) DockTo(pane.NestedPanesContainer, pane, DockAlignment.Right, 0.5); else if (dockStyle == DockStyle.Top) DockTo(pane.NestedPanesContainer, pane, DockAlignment.Top, 0.5); else if (dockStyle == DockStyle.Bottom) DockTo(pane.NestedPanesContainer, pane, DockAlignment.Bottom, 0.5); DockState = pane.DockState; } } public void DockTo(DockPanel panel, DockStyle dockStyle) { if (panel != DockPanel) throw new ArgumentException(Strings.IDockDragSource_DockTo_InvalidPanel, "panel"); if (dockStyle == DockStyle.Top) DockState = DockState.DockTop; else if (dockStyle == DockStyle.Bottom) DockState = DockState.DockBottom; else if (dockStyle == DockStyle.Left) DockState = DockState.DockLeft; else if (dockStyle == DockStyle.Right) DockState = DockState.DockRight; else if (dockStyle == DockStyle.Fill) DockState = DockState.Document; } #endregion #region cachedLayoutArgs leak workaround /// <summary> /// There's a bug in the WinForms layout engine /// that can result in a deferred layout to not /// properly clear out the cached layout args after /// the layout operation is performed. /// Specifically, this bug is hit when the bounds of /// the Pane change, initiating a layout on the parent /// (DockWindow) which is where the bug hits. /// To work around it, when a pane loses the DockWindow /// as its parent, that parent DockWindow needs to /// perform a layout to flush the cached args, if they exist. /// </summary> private DockWindow _lastParentWindow; protected override void OnParentChanged(EventArgs e) { base.OnParentChanged(e); var newParent = Parent as DockWindow; if (newParent != _lastParentWindow) { if (_lastParentWindow != null) _lastParentWindow.PerformLayout(); _lastParentWindow = newParent; } } #endregion } }
// Copyright 2007-2016 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 { using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Context; using Events; using GreenPipes; using Internals.Extensions; using Logging; using Pipeline; using Transports; using Util; public class MassTransitBus : IBusControl, IDisposable { static readonly ILog _log = Logger.Get<MassTransitBus>(); readonly IBusObserver _busObservable; readonly IConsumePipe _consumePipe; readonly IBusHostCollection _hosts; readonly Lazy<IPublishEndpoint> _publishEndpoint; readonly IPublishEndpointProvider _publishEndpointProvider; readonly ISendEndpointProvider _sendEndpointProvider; Handle _busHandle; public MassTransitBus(Uri address, IConsumePipe consumePipe, ISendEndpointProvider sendEndpointProvider, IPublishEndpointProvider publishEndpointProvider, IBusHostCollection hosts, IBusObserver busObservable) { Address = address; _consumePipe = consumePipe; _sendEndpointProvider = sendEndpointProvider; _publishEndpointProvider = publishEndpointProvider; _busObservable = busObservable; _hosts = hosts; _publishEndpoint = new Lazy<IPublishEndpoint>(() => publishEndpointProvider.CreatePublishEndpoint(address)); } ConnectHandle IConsumePipeConnector.ConnectConsumePipe<T>(IPipe<ConsumeContext<T>> pipe) { return _consumePipe.ConnectConsumePipe(pipe); } ConnectHandle IRequestPipeConnector.ConnectRequestPipe<T>(Guid requestId, IPipe<ConsumeContext<T>> pipe) { return _consumePipe.ConnectRequestPipe(requestId, pipe); } Task IPublishEndpoint.Publish<T>(T message, CancellationToken cancellationToken) { return _publishEndpoint.Value.Publish(message, cancellationToken); } Task IPublishEndpoint.Publish<T>(T message, IPipe<PublishContext<T>> publishPipe, CancellationToken cancellationToken) { return _publishEndpoint.Value.Publish(message, publishPipe, cancellationToken); } Task IPublishEndpoint.Publish<T>(T message, IPipe<PublishContext> publishPipe, CancellationToken cancellationToken) { return _publishEndpoint.Value.Publish(message, publishPipe, cancellationToken); } Task IPublishEndpoint.Publish(object message, CancellationToken cancellationToken) { return _publishEndpoint.Value.Publish(message, cancellationToken); } Task IPublishEndpoint.Publish(object message, IPipe<PublishContext> publishPipe, CancellationToken cancellationToken) { return _publishEndpoint.Value.Publish(message, publishPipe, cancellationToken); } Task IPublishEndpoint.Publish(object message, Type messageType, CancellationToken cancellationToken) { return PublishEndpointConverterCache.Publish(this, message, messageType, cancellationToken); } Task IPublishEndpoint.Publish(object message, Type messageType, IPipe<PublishContext> publishPipe, CancellationToken cancellationToken) { return PublishEndpointConverterCache.Publish(this, message, messageType, publishPipe, cancellationToken); } Task IPublishEndpoint.Publish<T>(object values, CancellationToken cancellationToken) { return _publishEndpoint.Value.Publish<T>(values, cancellationToken); } Task IPublishEndpoint.Publish<T>(object values, IPipe<PublishContext<T>> publishPipe, CancellationToken cancellationToken) { return _publishEndpoint.Value.Publish(values, publishPipe, cancellationToken); } Task IPublishEndpoint.Publish<T>(object values, IPipe<PublishContext> publishPipe, CancellationToken cancellationToken) { return _publishEndpoint.Value.Publish<T>(values, publishPipe, cancellationToken); } public Uri Address { get; } Task<ISendEndpoint> ISendEndpointProvider.GetSendEndpoint(Uri address) { return _sendEndpointProvider.GetSendEndpoint(address); } public async Task<BusHandle> StartAsync(CancellationToken cancellationToken) { if (_busHandle != null) { _log.Warn($"The bus was already started, additional Start attempts are ignored: {Address}"); return _busHandle; } await _busObservable.PreStart(this).ConfigureAwait(false); Handle busHandle = null; var hosts = new List<HostHandle>(); try { if (_log.IsDebugEnabled) _log.DebugFormat("Starting bus hosts..."); foreach (var host in _hosts) { var hostHandle = await host.Start().ConfigureAwait(false); hosts.Add(hostHandle); } busHandle = new Handle(hosts, this, _busObservable); await busHandle.Ready.WithCancellation(cancellationToken).ConfigureAwait(false); await _busObservable.PostStart(this, busHandle.Ready).ConfigureAwait(false); _busHandle = busHandle; return _busHandle; } catch (Exception ex) { try { if (busHandle != null) { if (_log.IsDebugEnabled) _log.DebugFormat("Stopping bus hosts..."); await busHandle.StopAsync(cancellationToken).ConfigureAwait(false); } else { var handle = new Handle(hosts, this, _busObservable); await handle.StopAsync(cancellationToken).ConfigureAwait(false); } } catch (Exception stopException) { _log.Error("Failed to stop partially created bus", stopException); } await _busObservable.StartFaulted(this, ex).ConfigureAwait(false); throw; } } public Task StopAsync(CancellationToken cancellationToken = new CancellationToken()) { if (_busHandle == null) { _log.Warn($"The bus could not be stopped as it was never started: {Address}"); return TaskUtil.Completed; } return _busHandle.StopAsync(cancellationToken); } ConnectHandle IConsumeObserverConnector.ConnectConsumeObserver(IConsumeObserver observer) { return new MultipleConnectHandle(_hosts.Select(h => h.ConnectConsumeObserver(observer))); } ConnectHandle IConsumeMessageObserverConnector.ConnectConsumeMessageObserver<T>(IConsumeMessageObserver<T> observer) { return new MultipleConnectHandle(_hosts.Select(h => h.ConnectConsumeMessageObserver(observer))); } public ConnectHandle ConnectReceiveObserver(IReceiveObserver observer) { return new MultipleConnectHandle(_hosts.Select(x => x.ConnectReceiveObserver(observer))); } ConnectHandle IReceiveEndpointObserverConnector.ConnectReceiveEndpointObserver(IReceiveEndpointObserver observer) { return new MultipleConnectHandle(_hosts.Select(x => x.ConnectReceiveEndpointObserver(observer))); } public ConnectHandle ConnectPublishObserver(IPublishObserver observer) { return new MultipleConnectHandle(_hosts.Select(h => h.ConnectPublishObserver(observer))); } public ConnectHandle ConnectSendObserver(ISendObserver observer) { return new MultipleConnectHandle(_hosts.Select(h => h.ConnectSendObserver(observer))); } void IProbeSite.Probe(ProbeContext context) { var scope = context.CreateScope("bus"); scope.Set(new { Address }); foreach (var host in _hosts) host.Probe(scope); } void IDisposable.Dispose() { if (_busHandle != null && !_busHandle.Stopped) throw new MassTransitException("The bus was disposed without being stopped. Explicitly call StopAsync before the bus instance is disposed."); (_sendEndpointProvider as IDisposable)?.Dispose(); (_publishEndpointProvider as IDisposable)?.Dispose(); } class Handle : BusHandle { readonly IBus _bus; readonly IBusObserver _busObserver; readonly HostHandle[] _hostHandles; bool _stopped; public Handle(IEnumerable<HostHandle> hostHandles, IBus bus, IBusObserver busObserver) { _bus = bus; _busObserver = busObserver; _hostHandles = hostHandles.ToArray(); } public bool Stopped => _stopped; public Task<BusReady> Ready => ReadyOrNot(_hostHandles.Select(x => x.Ready)); public async Task StopAsync(CancellationToken cancellationToken) { if (_stopped) return; await _busObserver.PreStop(_bus).ConfigureAwait(false); try { if (_log.IsDebugEnabled) _log.DebugFormat("Stopping hosts..."); await Task.WhenAll(_hostHandles.Select(x => x.Stop(cancellationToken))).ConfigureAwait(false); await _busObserver.PostStop(_bus).ConfigureAwait(false); } catch (Exception exception) { await _busObserver.StopFaulted(_bus, exception).ConfigureAwait(false); throw; } _stopped = true; } async Task<BusReady> ReadyOrNot(IEnumerable<Task<HostReady>> hosts) { Task<HostReady>[] readyTasks = hosts as Task<HostReady>[] ?? hosts.ToArray(); foreach (Task<HostReady> ready in readyTasks) { await ready.ConfigureAwait(false); } HostReady[] hostsReady = await Task.WhenAll(readyTasks).ConfigureAwait(false); return new BusReadyEvent(hostsReady, _bus); } } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Collections; using System.Collections.ObjectModel; using System.Reflection; namespace System.Management.Automation { /// <summary> /// HelpErrorTracer is a class to help tracing errors happened during loading /// help content for a help topic. /// /// This class tracks help context information like help topic, help category /// and help file, which are usually not available when an error happens at /// down level. /// /// Following is how this class can be used. /// /// using(HelpErrorTracer.Trace(helpTopic, helpCategory, helpFile)) /// { /// InsideFunctionCall(); /// } /// /// At this moment, a TraceFrame instance, which is disposable, will be created. /// /// In inside function calls and the calls down on the call stack, error can /// be traced by calling, /// /// HelpErrorTracer.TraceError(errorRecord) /// /// At this moment, the errorRecord will be temporarily stored with in TraceFrame instance. /// /// When the TraceFrame instance is disposed, all errorRecords stored will be /// dumped into HelpSystem.LastErrors with context information attached. /// /// </summary> internal class HelpErrorTracer { /// <summary> /// TraceFrame class track basic context information for current help activity. /// /// TraceFrame instance exists in a scope governed by using statement. It is possible /// that a new TraceFrame instance will be created in the scope of another TraceFrame /// instance. The scopes of various live TraceFrame instances form a stack which is /// similar to call stacks of normal C# functions. This is why we call this class /// a "TraceFrame" /// /// TraceFrame itself implements IDisposable interface to guarantee a chance to /// write errors into system error pool when execution gets out of its scope. During /// disposal time, errorRecords accumulated will be written to system error pool /// together with error context information collected at instance creation. /// </summary> internal sealed class TraceFrame : IDisposable { // Following are help context information private string _helpFile = ""; // ErrorRecords accumulated during the help content loading. private Collection<ErrorRecord> _errors = new Collection<ErrorRecord>(); private HelpErrorTracer _helpTracer; /// <summary> /// Constructor. Here help context information will be collected. /// </summary> /// <param name="helpTracer"></param> /// <param name="helpFile"></param> internal TraceFrame(HelpErrorTracer helpTracer, string helpFile) { _helpTracer = helpTracer; _helpFile = helpFile; } /// <summary> /// This is a interface for code in trace frame scope to add errorRecord into /// accumulative error pool. /// </summary> /// <param name="errorRecord"></param> internal void TraceError(ErrorRecord errorRecord) { if (_helpTracer.HelpSystem.VerboseHelpErrors) _errors.Add(errorRecord); } /// <summary> /// This is a interface for code in trace frame scope to add errorRecord's into /// accumulative error pool. /// </summary> /// <param name="errorRecords"></param> internal void TraceErrors(Collection<ErrorRecord> errorRecords) { if (_helpTracer.HelpSystem.VerboseHelpErrors) { foreach (ErrorRecord errorRecord in errorRecords) { _errors.Add(errorRecord); } } } /// <summary> /// This is where we dump ErrorRecord's accumulated to help system error pool /// together with some context information. /// </summary> public void Dispose() { if (_helpTracer.HelpSystem.VerboseHelpErrors && _errors.Count > 0) { ErrorRecord errorRecord = new ErrorRecord(new ParentContainsErrorRecordException("Help Load Error"), "HelpLoadError", ErrorCategory.SyntaxError, null); errorRecord.ErrorDetails = new ErrorDetails(typeof(HelpErrorTracer).GetTypeInfo().Assembly, "HelpErrors", "HelpLoadError", _helpFile, _errors.Count); _helpTracer.HelpSystem.LastErrors.Add(errorRecord); foreach (ErrorRecord error in _errors) { _helpTracer.HelpSystem.LastErrors.Add(error); } } _helpTracer.PopFrame(this); } } internal HelpSystem HelpSystem { get; } internal HelpErrorTracer(HelpSystem helpSystem) { if (helpSystem == null) { throw PSTraceSource.NewArgumentNullException("HelpSystem"); } HelpSystem = helpSystem; } /// <summary> /// This tracks all live TraceFrame objects, which forms a stack. /// </summary> private ArrayList _traceFrames = new ArrayList(); /// <summary> /// This is the API to use for starting a help trace scope /// </summary> /// <param name="helpFile"></param> /// <returns></returns> internal IDisposable Trace(string helpFile) { TraceFrame traceFrame = new TraceFrame(this, helpFile); _traceFrames.Add(traceFrame); return traceFrame; } /// <summary> /// This is the api function used for adding errorRecords to TraceFrame's error /// pool. /// </summary> /// <param name="errorRecord"></param> internal void TraceError(ErrorRecord errorRecord) { if (_traceFrames.Count <= 0) return; TraceFrame traceFrame = (TraceFrame)_traceFrames[_traceFrames.Count - 1]; traceFrame.TraceError(errorRecord); } /// <summary> /// This is the api function used for adding errorRecords to TraceFrame's error /// pool. /// </summary> /// <param name="errorRecords"></param> internal void TraceErrors(Collection<ErrorRecord> errorRecords) { if (_traceFrames.Count <= 0) return; TraceFrame traceFrame = (TraceFrame)_traceFrames[_traceFrames.Count - 1]; traceFrame.TraceErrors(errorRecords); } internal void PopFrame(TraceFrame traceFrame) { if (_traceFrames.Count <= 0) return; TraceFrame lastFrame = (TraceFrame)_traceFrames[_traceFrames.Count - 1]; if (lastFrame == traceFrame) { _traceFrames.RemoveAt(_traceFrames.Count - 1); } } /// <summary> /// Track whether help error tracer is turned on. /// </summary> /// <value></value> internal bool IsOn { get { return (_traceFrames.Count > 0 && this.HelpSystem.VerboseHelpErrors); } } } }
using System; using System.Collections.Generic; using System.Net; using System.Security.Cryptography; using System.Text; using System.Xml; using IdSharp.Common.Utils; namespace IdSharp.WebLookup.Amazon { /// <summary> /// Amazon /// </summary> public static class Amazon { private static readonly Dictionary<AmazonServer, string> _amazonServers; internal const string HttpRequestUri = "/onca/xml"; static Amazon() { _amazonServers = new Dictionary<AmazonServer, string>(); _amazonServers.Add(AmazonServer.UnitedStates, "amazonaws.com"); _amazonServers.Add(AmazonServer.Germany, "amazonaws.de"); _amazonServers.Add(AmazonServer.Japan, "amazonaws.jp"); _amazonServers.Add(AmazonServer.UnitedKingdom, "amazonaws.co.uk"); _amazonServers.Add(AmazonServer.France, "amazonaws.fr"); _amazonServers.Add(AmazonServer.Canada, "amazonaws.ca"); } private static void FixSearchString(ref string value) { if (value == null) return; // remove everything after parentheses int parenIndex = value.IndexOf('('); if (parenIndex > 0) value = value.Substring(0, parenIndex); // remove all characters that are not letters, digits, or spaces for (int i = 0; i < value.Length; i++) { char c = value[i]; if (!char.IsLetterOrDigit(c) && c != ' ') { value = value.Replace(c, ' '); i--; } } // remove dangling digits for (int i = 0; i < value.Length; i++) { char c = value[i]; if (char.IsDigit(c)) { if (i > 0) { if (value[i - 1] != ' ' || (i != value.Length - 1 && value[i + 1] != ' ')) { continue; } } else { if (i != value.Length - 1 && value[i + 1] != ' ') { continue; } } value = value.Remove(i, 1); i--; } } // remove common words value = value.ToLower(); value = value.Replace(" the ", " "); value = value.Replace(" a ", " "); value = value.Replace(" of ", " "); value = value.Replace(" and ", " "); value = value.Replace(" an ", " "); value = value.Replace(" ost ", " "); value = value.Replace(" in ", " "); value = value.Replace(" disc ", " "); value = value.Replace(" disk ", " "); value = value.Replace(" cd ", " "); value = value.Trim(); if (value == "various") value = string.Empty; //value = value.Replace(' ', '+'); } /// <summary> /// Search /// </summary> /// <param name="server">The server.</param> /// <param name="awsAccessKeyId">Required: Your AWSAccessKeyId.</param> /// <param name="secretAccessKey">Required: Your Secret Access Key.</param> /// <param name="artist">The artist.</param> /// <param name="album">The album.</param> /// <param name="keywords">The keywords.</param> /// <param name="page">The page.</param> public static AmazonSearchResponse Search(AmazonServer server, string awsAccessKeyId, string secretAccessKey, string artist, string album, string keywords, int page) { if (string.IsNullOrWhiteSpace(awsAccessKeyId)) throw new ArgumentNullException("awsAccessKeyId"); if (string.IsNullOrWhiteSpace(secretAccessKey)) throw new ArgumentNullException("secretAccessKey"); String amazonDomain = GetDomain(server); FixSearchString(ref artist); FixSearchString(ref album); FixSearchString(ref keywords); string sort = (String.IsNullOrEmpty(artist) ? "artistrank" : "titlerank"); List<PostData> postData = new List<PostData>(); postData.Add(new PostData("Service", "AWSECommerceService")); postData.Add(new PostData("AWSAccessKeyId", awsAccessKeyId)); postData.Add(new PostData("Operation", "ItemSearch")); postData.Add(new PostData("SearchIndex", "Music")); if (!string.IsNullOrEmpty(artist)) postData.Add(new PostData("Artist", artist)); if (!string.IsNullOrEmpty(album)) postData.Add(new PostData("Title", album)); if (!string.IsNullOrEmpty(keywords)) postData.Add(new PostData("Keywords", keywords)); postData.Add(new PostData("ItemPage", page.ToString())); postData.Add(new PostData("Sort", sort)); postData.Add(new PostData("Timestamp", string.Format("{0:yyyy-MM-dd}T{0:HH:mm:ss}Z", DateTime.UtcNow))); string hostHeader = string.Format("ecs.{0}", amazonDomain); string signature = GetSignature(postData, hostHeader, secretAccessKey); postData.Add(new PostData("Signature", signature)); string requestUri = string.Format("http://{0}{1}", hostHeader, HttpRequestUri); requestUri = Http.GetQueryString(requestUri, postData); byte[] byteResponse = Http.Get(requestUri); if (byteResponse == null) throw new WebException(string.Format("Response from {0} was null", amazonDomain)); string response = Encoding.UTF8.GetString(byteResponse); AmazonSearchResponse result = new AmazonSearchResponse(); result.TotalPages = 0; result.TotalResults = 0; XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(response); foreach (XmlNode node in xmlDocument.ChildNodes) { if (node.Name == "ItemSearchResponse") { foreach (XmlNode responseNode in node.ChildNodes) { if (responseNode.Name == "OperationRequest") { foreach (XmlNode opReqNode in responseNode.ChildNodes) { if (opReqNode.Name == "Errors") { string fullErrorMessage = ""; foreach (XmlNode errorNode in opReqNode.ChildNodes) { if (errorNode.Name == "Error") { string errorMessage = ""; string errorCode = ""; foreach (XmlNode errorItemNode in errorNode.ChildNodes) { if (errorItemNode.Name == "Code") { errorCode = errorItemNode.InnerText; } else if (errorItemNode.Name == "Message") { errorMessage = errorItemNode.InnerText; } } if (errorMessage != "" || errorCode != "") { if (errorCode != "") errorMessage = string.Format("{0} ({1})", errorMessage, errorCode); if (fullErrorMessage != "") fullErrorMessage += "\n\n"; fullErrorMessage += errorMessage; } } } if (fullErrorMessage != "") throw new Exception(fullErrorMessage); } } } else if (responseNode.Name == "Items") { foreach (XmlNode itemNode in responseNode.ChildNodes) { if (itemNode.Name == "TotalResults") { int totalResults; if (int.TryParse(itemNode.InnerText, out totalResults)) result.TotalResults = totalResults; } else if (itemNode.Name == "TotalPages") { int totalPages; if (int.TryParse(itemNode.InnerText, out totalPages)) result.TotalPages = totalPages; } else if (itemNode.Name == "Item") { AmazonAlbum albumItem = new AmazonAlbum(server, awsAccessKeyId, secretAccessKey); result.Items.Add(albumItem); foreach (XmlNode itemDetail in itemNode.ChildNodes) { if (itemDetail.Name == "ASIN") { albumItem.Asin = itemDetail.InnerText; } else if (itemDetail.Name == "DetailPageURL") { albumItem.DetailPageUrl = itemDetail.InnerText; } else if (itemDetail.Name == "ItemAttributes") { foreach (XmlNode itemAttribute in itemDetail.ChildNodes) { if (itemAttribute.Name == "Artist") { albumItem.Artist = itemAttribute.InnerText; } else if (itemAttribute.Name == "Manufacturer") { albumItem.Manufacturer = itemAttribute.InnerText; } else if (itemAttribute.Name == "Title") { albumItem.Album = itemAttribute.InnerText; } } } } } } } } } } return result; } internal static string GetSignature(List<PostData> postData, string hostHeader, string secretAccessKey) { List<PostData> ordered = GetOrderedPostData(postData); StringBuilder getString = new StringBuilder(); foreach (PostData item in ordered) { if (getString.Length != 0) getString.Append("&"); getString.Append(item.Field); getString.Append("="); foreach (char c in item.Value) { if (c <= 255) { if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c == '-') || (c == '_') || (c == '.') || (c == '~')) { getString.Append(c); } else { getString.Append(string.Format("%{0:X2}", (int)c)); } } } } string stringToSign = string.Format("GET{0}{1}{0}{2}{0}{3}", "\n", hostHeader, HttpRequestUri, getString); HMACSHA256 hmac = new HMACSHA256(Encoding.ASCII.GetBytes(secretAccessKey)); byte[] hash = hmac.ComputeHash(Encoding.ASCII.GetBytes(stringToSign)); string signature = Encoding.ASCII.GetString(Base64Encoder.Encode(hash)).Replace("+", "%2B").Replace("=", "%3D"); return signature; } private static List<PostData> GetOrderedPostData(IEnumerable<PostData> postData) { List<PostData> newList = new List<PostData>(postData); newList.Sort(new PostDataComparer()); return newList; } private class PostDataComparer : Comparer<PostData> { public override int Compare(PostData x, PostData y) { return string.CompareOrdinal(x.Field, y.Field); } } /// <summary> /// Gets the domain for a specified AmazonServer. /// </summary> /// <param name="server">The server.</param> public static string GetDomain(AmazonServer server) { return _amazonServers[server]; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using Microsoft.Build.Framework; using Microsoft.Build.Tasks; using Microsoft.Build.Utilities; using Xunit; namespace Microsoft.Build.UnitTests { sealed public class CreateItem_Tests { /// <summary> /// CreateIteming identical lists results in empty list. /// </summary> [Fact] public void OneFromOneIsZero() { CreateItem t = new CreateItem(); t.BuildEngine = new MockEngine(); t.Include = new ITaskItem[] { new TaskItem("MyFile.txt") }; t.Exclude = new ITaskItem[] { new TaskItem("MyFile.txt") }; bool success = t.Execute(); Assert.True(success); Assert.Empty(t.Include); } /// <summary> /// CreateIteming completely different lists results in left list. /// </summary> [Fact] public void OneFromOneMismatchIsOne() { CreateItem t = new CreateItem(); t.BuildEngine = new MockEngine(); t.Include = new ITaskItem[] { new TaskItem("MyFile.txt") }; t.Exclude = new ITaskItem[] { new TaskItem("MyFileOther.txt") }; bool success = t.Execute(); Assert.True(success); Assert.Single(t.Include); Assert.Equal("MyFile.txt", t.Include[0].ItemSpec); } /// <summary> /// If 'Exclude' is unspecified, then 'Include' is the result. /// </summary> [Fact] public void UnspecifiedFromOneIsOne() { CreateItem t = new CreateItem(); t.BuildEngine = new MockEngine(); t.Include = new ITaskItem[] { new TaskItem("MyFile.txt") }; bool success = t.Execute(); Assert.True(success); Assert.Single(t.Include); Assert.Equal(t.Include[0].ItemSpec, t.Include[0].ItemSpec); } /// <summary> /// If 'Include' is unspecified, then empty is the result. /// </summary> [Fact] public void OneFromUnspecifiedIsEmpty() { CreateItem t = new CreateItem(); t.BuildEngine = new MockEngine(); t.Exclude = new ITaskItem[] { new TaskItem("MyFile.txt") }; bool success = t.Execute(); Assert.True(success); Assert.Empty(t.Include); } /// <summary> /// If 'Include' and 'Exclude' are unspecified, then empty is the result. /// </summary> [Fact] public void UnspecifiedFromUnspecifiedIsEmpty() { CreateItem t = new CreateItem(); t.BuildEngine = new MockEngine(); bool success = t.Execute(); Assert.True(success); Assert.Empty(t.Include); } /// <summary> /// CreateItem is case insensitive. /// </summary> [Fact] public void CaseDoesntMatter() { CreateItem t = new CreateItem(); t.BuildEngine = new MockEngine(); t.Include = new ITaskItem[] { new TaskItem("MyFile.txt") }; t.Exclude = new ITaskItem[] { new TaskItem("myfile.tXt") }; bool success = t.Execute(); Assert.True(success); Assert.Empty(t.Include); } /// <summary> /// Using the CreateItem task to expand wildcards, and then try accessing the RecursiveDir /// metadata to force batching. /// </summary> [Fact] public void WildcardsWithRecursiveDir() { ObjectModelHelpers.DeleteTempProjectDirectory(); ObjectModelHelpers.CreateFileInTempProjectDirectory("Myapp.proj", @" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <Target Name =`Repro`> <CreateItem Include=`**\*.txt`> <Output TaskParameter=`Include` ItemName=`Text`/> </CreateItem> <Copy SourceFiles=`@(Text)` DestinationFiles=`Destination\%(RecursiveDir)%(Filename)%(Extension)`/> </Target> </Project> "); ObjectModelHelpers.CreateFileInTempProjectDirectory("Foo.txt", "foo"); ObjectModelHelpers.CreateFileInTempProjectDirectory(Path.Combine("Subdir", "Bar.txt"), "bar"); ObjectModelHelpers.BuildTempProjectFileExpectSuccess("Myapp.proj"); ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(Path.Combine("Destination", "Foo.txt")); ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(Path.Combine("Destination", "Subdir", "Bar.txt")); } /// <summary> /// CreateItem should add additional metadata when instructed /// </summary> [Fact] public void AdditionalMetaData() { CreateItem t = new CreateItem(); t.BuildEngine = new MockEngine(); t.Include = new ITaskItem[] { new TaskItem("MyFile.txt") }; t.AdditionalMetadata = new string[] { "MyMetaData=SomeValue" }; bool success = t.Execute(); Assert.True(success); Assert.Equal("SomeValue", t.Include[0].GetMetadata("MyMetaData")); } /// <summary> /// We should be able to preserve the existing metadata on items /// </summary> [Fact] public void AdditionalMetaDataPreserveExisting() { CreateItem t = new CreateItem(); t.BuildEngine = new MockEngine(); TaskItem item = new TaskItem("MyFile.txt"); item.SetMetadata("MyMetaData", "SomePreserveMeValue"); t.Include = new ITaskItem[] { item }; t.PreserveExistingMetadata = true; t.AdditionalMetadata = new string[] { "MyMetaData=SomeValue" }; bool success = t.Execute(); Assert.True(success); Assert.Equal("SomePreserveMeValue", t.Include[0].GetMetadata("MyMetaData")); } /// <summary> /// The default is to overwrite existing metadata on items /// </summary> [Fact] public void AdditionalMetaDataOverwriteExisting() { CreateItem t = new CreateItem(); t.BuildEngine = new MockEngine(); TaskItem item = new TaskItem("MyFile.txt"); item.SetMetadata("MyMetaData", "SomePreserveMeValue"); t.Include = new ITaskItem[] { item }; // The default for CreateItem is to overwrite any existing metadata // t.PreserveExistingMetadata = false; t.AdditionalMetadata = new string[] { "MyMetaData=SomeOverwriteValue" }; bool success = t.Execute(); Assert.True(success); Assert.Equal("SomeOverwriteValue", t.Include[0].GetMetadata("MyMetaData")); } } }
#region License /* The MIT License * * Copyright (c) 2011 Red Badger Consulting * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion namespace RedBadger.Xpf.Sandbox { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using NekoCake.Crimson.Xpf; using RedBadger.Xpf.Adapters.Xna.Graphics; using RedBadger.Xpf.Adapters.Xna.Input; using RedBadger.Xpf.Controls; using RedBadger.Xpf.Data; using RedBadger.Xpf.Media; using RedBadger.Xpf.Media.Imaging; using Color = Microsoft.Xna.Framework.Color; public class Game1 : Game { private readonly GraphicsDeviceManager graphics; private readonly List<NinePatch> ninePatches = new List<NinePatch>(); private ObservableCollection<Chunk> chunks; private SpriteFontAdapter font; private RootElement root; private SpriteBatchAdapter spriteBatch; public Game1() { this.graphics = new GraphicsDeviceManager(this); this.Content.RootDirectory = "Content"; this.graphics.PreferredBackBufferHeight = 900; this.graphics.PreferredBackBufferWidth = 1400; this.IsMouseVisible = true; } protected override void Draw(GameTime gameTime) { this.GraphicsDevice.Clear(Color.CornflowerBlue); this.root.Draw(); base.Draw(gameTime); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. this.spriteBatch = new SpriteBatchAdapter(new SpriteBatch(this.GraphicsDevice)); var primitiveService = new PrimitivesService(this.GraphicsDevice); var renderer = new Renderer(this.spriteBatch, primitiveService); var input = new InputManager(); this.root = new RootElement(this.GraphicsDevice.Viewport.ToRect(), renderer, input); this.font = new SpriteFontAdapter(this.Content.Load<SpriteFont>(@"SpriteFont")); this.chunks = new ObservableCollection<Chunk>(); string[] files = Directory.GetFiles(Environment.CurrentDirectory + @"\Content\Textures"); foreach (string file in files) { var chunk = new Chunk { Name = Path.GetFileNameWithoutExtension(file), Texture = this.Content.Load<Texture2D>(@"Textures/" + Path.GetFileNameWithoutExtension(file)) }; this.chunks.Add(chunk); } var items = new ItemsControl { ItemTemplate = _ => { var textBlock = new TextBlock(this.font) { Foreground = new SolidColorBrush(Colors.White), HorizontalAlignment = HorizontalAlignment.Center }; textBlock.Bind( TextBlock.TextProperty, BindingFactory.CreateOneWay<Chunk, string>(o => o.Name)); var image = new Image { Stretch = Stretch.Fill, Width = 100, }; image.Bind( Image.SourceProperty, BindingFactory.CreateOneWay<Chunk, ImageSource>(o => o.XnaImage)); var panel = new StackPanel { Orientation = Orientation.Vertical, Background = new SolidColorBrush(new Media.Color(0, 0, 0, 100)), }; panel.Children.Add(image); panel.Children.Add(textBlock); var border = new Border { BorderBrush = new SolidColorBrush(Colors.Black), BorderThickness = new Thickness(2, 2, 2, 2), Margin = new Thickness(5, 5, 5, 5), Child = panel, }; var button = new Button { Content = border, Margin = new Thickness(5, 5, 5, 5), }; return button; }, ItemsSource = this.chunks, }; items.ItemsPanel.Margin = new Thickness(0, 0, 25, 0); var scrollViewer = new ScrollViewer { Content = items }; var canvas = new Canvas { }; var chunkPallet = new NinePatch(this.Content, canvas, "Chunk Pallet", this.font) { Width = 280, Height = 550, }; this.ninePatches.Add(chunkPallet); chunkPallet.Children.Add(scrollViewer); canvas.Children.Add(chunkPallet); Grid.SetColumn(scrollViewer, 1); Grid.SetRow(scrollViewer, 1); Canvas.SetLeft(chunkPallet, 740); Canvas.SetTop(chunkPallet, 20); this.root.Content = canvas; } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name = "gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) { this.Exit(); } this.root.Update(); foreach (NinePatch a in this.ninePatches) { a.Update(); } base.Update(gameTime); } public class Chunk { public string Name { get; set; } public Texture2D Texture { get; set; } public TextureImage XnaImage { get { return new TextureImage(new Texture2DAdapter(this.Texture)); } } public override string ToString() { return this.Name; } } } }
/*============================================================================ * Copyright (C) Microsoft Corporation, All rights reserved. *============================================================================ */ #region Using directives using System; using System.Management.Automation; using System.Globalization; #endregion namespace Microsoft.Management.Infrastructure.CimCmdlets { #region AsyncResultType /// <summary> /// <para> /// Async result type /// </para> /// </summary> public enum AsyncResultType { Result, Exception, Completion } #endregion #region CimResultContext /// <summary> /// Cim Result Context /// </summary> internal class CimResultContext { /// <summary> /// constructor /// </summary> /// <param name="ErrorSource"></param> internal CimResultContext(object ErrorSource) { this.errorSource = ErrorSource; } /// <summary> /// ErrorSource property /// </summary> internal object ErrorSource { get { return this.errorSource; } } private object errorSource; } #endregion #region AsyncResultEventArgsBase /// <summary> /// <para> /// Base class of asyn result event argument /// </para> /// </summary> internal abstract class AsyncResultEventArgsBase : EventArgs { /// <summary> /// Constructor /// </summary> /// <param name="session"></param> /// <param name="observable"></param> /// <param name="resultType"></param> public AsyncResultEventArgsBase( CimSession session, IObservable<object> observable, AsyncResultType resultType) { this.session = session; this.observable = observable; this.resultType = resultType; } /// <summary> /// Constructor /// </summary> /// <param name="session"></param> /// <param name="observable"></param> /// <param name="resultType"></param> /// <param name="context"></param> public AsyncResultEventArgsBase( CimSession session, IObservable<object> observable, AsyncResultType resultType, CimResultContext cimResultContext) { this.session = session; this.observable = observable; this.resultType = resultType; this.context = cimResultContext; } public readonly CimSession session; public readonly IObservable<object> observable; public readonly AsyncResultType resultType; // property ErrorSource public readonly CimResultContext context; } #endregion #region AsyncResult*Args /// <summary> /// <para> /// operation successfully completed event argument /// </para> /// </summary> internal class AsyncResultCompleteEventArgs : AsyncResultEventArgsBase { /// <summary> /// <para> /// Constructor /// </para> /// </summary> /// <param name="session"><see cref="CimSession"/> object</param> /// <param name="cancellationDisposable"></param> public AsyncResultCompleteEventArgs( CimSession session, IObservable<object> observable) : base(session, observable, AsyncResultType.Completion) { } } /// <summary> /// <para> /// async result argument with object /// </para> /// </summary> internal class AsyncResultObjectEventArgs : AsyncResultEventArgsBase { /// <summary> /// Constructor /// </summary> /// <param name="session"></param> /// <param name="observable"></param> /// <param name="resultObject"></param> public AsyncResultObjectEventArgs( CimSession session, IObservable<object> observable, object resultObject) : base(session, observable, AsyncResultType.Result) { this.resultObject = resultObject; } public readonly object resultObject; } /// <summary> /// <para> /// operation completed with exception event argument /// </para> /// </summary> internal class AsyncResultErrorEventArgs : AsyncResultEventArgsBase { /// <summary> /// Constructor /// </summary> /// <param name="session"></param> /// <param name="observable"></param> /// <param name="error"></param> public AsyncResultErrorEventArgs( CimSession session, IObservable<object> observable, Exception error) : base(session, observable, AsyncResultType.Exception) { this.error = error; } /// <summary> /// Constructor /// </summary> /// <param name="session"></param> /// <param name="observable"></param> /// <param name="error"></param> /// <param name="context"></param> public AsyncResultErrorEventArgs( CimSession session, IObservable<object> observable, Exception error, CimResultContext cimResultContext) : base(session, observable, AsyncResultType.Exception, cimResultContext) { this.error = error; } public readonly Exception error; } #endregion #region CimResultObserver /// <summary> /// <para> /// Observer to consume results from asynchronous operations, such as, /// EnumerateInstancesAsync operation of <see cref="CimSession"/> object. /// </para> /// <para> /// (See http://channel9.msdn.com/posts/J.Van.Gogh/Reactive-Extensions-API-in-depth-Contract/) /// for the IObserver/IObservable contact /// - the only possible sequence is OnNext* (OnCompleted|OnError)? /// - callbacks are serialized /// - Subscribe never throws /// </para> /// </summary> /// <typeparam name="T">object type</typeparam> internal class CimResultObserver<T> : IObserver<T> { /// <summary> /// Define delegate that handles new cmdlet action come from /// the operations related to the current CimSession object. /// </summary> /// <param name="cimSession">cimSession object, which raised the event</param> /// <param name="actionArgs">Event args</param> public delegate void ResultEventHandler( object observer, AsyncResultEventArgsBase resultArgs); /// <summary> /// Define an Event based on the NewActionHandler /// </summary> public event ResultEventHandler OnNewResult; /// <summary> /// Constructor /// </summary> /// <param name="session"><see cref="CimSession"/> object that issued the operation</param> /// <param name="observable">Operation that can be observed</param> public CimResultObserver(CimSession session, IObservable<object> observable) { this.session = session; this.observable = observable; } /// <summary> /// Constructor /// </summary> /// <param name="session"><see cref="CimSession"/> object that issued the operation</param> /// <param name="observable">Operation that can be observed</param> public CimResultObserver(CimSession session, IObservable<object> observable, CimResultContext cimResultContext) { this.session = session; this.observable = observable; this.context = cimResultContext; } /// <summary> /// <para> /// Operation completed successfully /// </para> /// </summary> public virtual void OnCompleted() { // callbacks should never throw any exception to // protocol layer, otherwise the client process will be // terminated because of unhandled exception, same with // OnNext, OnError try { AsyncResultCompleteEventArgs completeArgs = new AsyncResultCompleteEventArgs( this.session, this.observable); this.OnNewResult(this, completeArgs); } catch (Exception ex) { this.OnError(ex); DebugHelper.WriteLogEx("{0}", 0, ex); } } /// <summary> /// <para> /// Operation completed with an error /// </para> /// </summary> /// <param name="error">error object</param> public virtual void OnError(Exception error) { try { AsyncResultErrorEventArgs errorArgs = new AsyncResultErrorEventArgs( this.session, this.observable, error, this.context); this.OnNewResult(this, errorArgs); } catch (Exception ex) { // !!ignore the exception DebugHelper.WriteLogEx("{0}", 0, ex); } } /// <summary> /// Deliver the result value /// </summary> /// <param name="value"></param> protected void OnNextCore(object value) { DebugHelper.WriteLogEx("value = {0}.", 1, value); try { AsyncResultObjectEventArgs resultArgs = new AsyncResultObjectEventArgs( this.session, this.observable, value); this.OnNewResult(this, resultArgs); } catch (Exception ex) { this.OnError(ex); DebugHelper.WriteLogEx("{0}", 0, ex); } } /// <summary> /// <para> /// Operation got a new result object /// </para> /// </summary> /// <param name="value">result object</param> public virtual void OnNext(T value) { DebugHelper.WriteLogEx("value = {0}.", 1, value); // do not allow null value if (value == null) { return; } this.OnNextCore(value); } #region members /// <summary> /// Session object of the operation /// </summary> protected CimSession CurrentSession { get { return session; } } private CimSession session; /// <summary> /// async operation that can be observed /// </summary> private IObservable<object> observable; /// <summary> /// <see cref="CimResultContext"/> object used during delivering result. /// </summary> private CimResultContext context; #endregion } /// <summary> /// CimSubscriptionResultObserver class definition /// </summary> internal class CimSubscriptionResultObserver : CimResultObserver<CimSubscriptionResult> { /// <summary> /// constructor /// </summary> /// <param name="session"></param> /// <param name="observable"></param> public CimSubscriptionResultObserver(CimSession session, IObservable<object> observable) : base(session, observable) { } /// <summary> /// constructor /// </summary> /// <param name="session"></param> /// <param name="observable"></param> public CimSubscriptionResultObserver( CimSession session, IObservable<object> observable, CimResultContext context) : base(session, observable, context) { } /// <summary> /// Override the OnNext method /// </summary> /// <param name="value"></param> public override void OnNext(CimSubscriptionResult value) { DebugHelper.WriteLogEx(); base.OnNextCore(value); } } /// <summary> /// CimMethodResultObserver class definition /// </summary> internal class CimMethodResultObserver : CimResultObserver<CimMethodResultBase> { /// <summary> /// constructor /// </summary> /// <param name="session"></param> /// <param name="observable"></param> public CimMethodResultObserver(CimSession session, IObservable<object> observable) : base(session, observable) { } /// <summary> /// constructor /// </summary> /// <param name="session"></param> /// <param name="observable"></param> /// <param name="context"></param> public CimMethodResultObserver( CimSession session, IObservable<object> observable, CimResultContext context) : base(session, observable, context) { } /// <summary> /// Override the OnNext method /// </summary> /// <param name="value"></param> public override void OnNext(CimMethodResultBase value) { DebugHelper.WriteLogEx(); const string PSTypeCimMethodResult = @"Microsoft.Management.Infrastructure.CimMethodResult"; const string PSTypeCimMethodStreamedResult = @"Microsoft.Management.Infrastructure.CimMethodStreamedResult"; const string PSTypeCimMethodResultTemplate = @"{0}#{1}#{2}"; string resultObjectPSType = null; PSObject resultObject = null; CimMethodResult methodResult = value as CimMethodResult; if (methodResult != null) { resultObjectPSType = PSTypeCimMethodResult; resultObject = new PSObject(); foreach (CimMethodParameter param in methodResult.OutParameters) { resultObject.Properties.Add(new PSNoteProperty(param.Name, param.Value)); } } else { CimMethodStreamedResult methodStreamedResult = value as CimMethodStreamedResult; if (methodStreamedResult != null) { resultObjectPSType = PSTypeCimMethodStreamedResult; resultObject = new PSObject(); resultObject.Properties.Add(new PSNoteProperty(@"ParameterName", methodStreamedResult.ParameterName)); resultObject.Properties.Add(new PSNoteProperty(@"ItemType", methodStreamedResult.ItemType)); resultObject.Properties.Add(new PSNoteProperty(@"ItemValue", methodStreamedResult.ItemValue)); } } if (resultObject != null) { resultObject.Properties.Add(new PSNoteProperty(@"PSComputerName", this.CurrentSession.ComputerName)); resultObject.TypeNames.Insert(0, resultObjectPSType); resultObject.TypeNames.Insert(0, String.Format(CultureInfo.InvariantCulture, PSTypeCimMethodResultTemplate, resultObjectPSType, ClassName, MethodName)); base.OnNextCore(resultObject); } } /// <summary> /// methodname /// </summary> internal String MethodName { get; set; } /// <summary> /// classname /// </summary> internal String ClassName { get; set; } } /// <summary> /// IgnoreResultObserver class definition /// </summary> internal class IgnoreResultObserver : CimResultObserver<CimInstance> { /// <summary> /// constructor /// </summary> /// <param name="session"></param> /// <param name="observable"></param> public IgnoreResultObserver(CimSession session, IObservable<object> observable) : base(session, observable) { } /// <summary> /// Override the OnNext method /// </summary> /// <param name="value"></param> public override void OnNext(CimInstance value) { DebugHelper.WriteLogEx(); } } #endregion }
// For DataSet // For Trace using System; using System.Data; using System.Data.SqlClient; using System.Diagnostics; using System.Text; // For StringBuilder namespace Xsd2Db.Data { /// <summary> /// This abstract class implements most of the functionality required /// to map an XSD schema (represented with a DataSet) to an SQL creation /// script. /// </summary> public abstract class ScriptBasedDataSchemaAdapter : DataSchemaAdapter { private string tablePrefix; private string dbOwner; /// <summary> /// Create a new database conforming to the passed schema. /// </summary> /// <param name="schema">a DataSet containing the schema</param> /// <param name="force">overwrite the database if it exists</param> void DataSchemaAdapter.Create(DataSet schema, bool force) { Create(schema, force, string.Empty, "dbo"); } public void Create(DataSet schema, bool force, string TablePrefix) { Create(schema, force, TablePrefix, "dbo"); } public void Create(DataSet schema, bool force, string TablePrefix, string DbOwner) { Create(schema, force, TablePrefix, "dbo", true); } public void Create(DataSet schema, bool force, string TablePrefix, string DbOwner, bool useExisting) { this.TablePrefix = TablePrefix; this.DbOwner = DbOwner; // IDbConnection oconn = new SqlConnection() if (!useExisting) { using (IDbConnection conn = GetConnection()) { conn.Open(); // // Create the database if not use exisitng string script = GetCreateScript(schema.DataSetName, force); using (IDbCommand cmd = conn.CreateCommand()) { Debug.Assert(script.Length > 0); cmd.CommandText = script; cmd.ExecuteNonQuery(); } } } using (IDbConnection conn = GetConnection(schema.DataSetName)) { conn.Open(); // // Set up the schema // string script = GetSchemaScript(schema); if (script.Length > 0) { using (IDbCommand cmd = conn.CreateCommand()) { cmd.CommandText = script; cmd.ExecuteNonQuery(); } } } } /// <summary> /// Child classes should provice an implementation which returns a /// connection to the server on which to create the new database. /// </summary> /// <returns>an unopened connection to the server.</returns> protected abstract IDbConnection GetConnection(); /// <summary> /// Child classes should provice an implementation which returns a /// connection to the server on which to create the new database. /// The returned connection must be bound to the context of the /// catalog/database given as a parameter (by name). /// </summary> /// <param name="catalog">The catalog (i.e., database) context /// to connect to</param> /// <returns>an unopened connection to the server.</returns> protected abstract IDbConnection GetConnection(string catalog); /// <summary> /// Returns the type description for the column given. /// </summary> /// <param name="column"></param> /// <returns></returns> protected abstract string GetTypeFor(DataColumn column); /// <summary> /// Returns a safe version of the given name. /// </summary> /// <param name="inputValue">Original Name</param> /// <returns>Converted name</returns> protected abstract string MakeSafe(string inputValue); /// <summary> /// Returns a script which creates an empty database having the given name. /// </summary> /// <param name="databaseName">the name of the database to create</param> /// <param name="overwrite">should an existing database (of the same name) be deleted</param> /// <returns>the script required to create an empty database having the given name</returns> internal string GetCreateScript(string databaseName, bool overwrite) { if ((databaseName == null) || (databaseName.Trim().Length == 0)) { throw new ArgumentException(String.Format("The database name passed is {0}", ((databaseName == null) ? "null" : "empty")), "databaseName"); } StringBuilder command = new StringBuilder(); if (overwrite) { command.AppendFormat("IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'{0}') DROP DATABASE {1};\n CREATE DATABASE {1};\n", databaseName, MakeSafe(databaseName)); } else { command.AppendFormat("IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'{0}') BEGIN USE {1}; END\n ELSE\n BEGIN\n CREATE DATABASE {1};\n END;\n", databaseName, MakeSafe(databaseName)); } return command.ToString(); } /// <summary> /// Returns the creation script which corresponds to the schema /// contained in the .xsd file which is passed as a parameter. /// </summary> /// <exception cref="ArgumentException">This method does not support /// the creation of a schema containing tables that have zero (0) /// columns. Nor does is support relations where one (or both) sides /// of the relationship is defined by zero (0) columns.</exception> /// <exception cref="NotSupportedException">May be thrown if the /// method is unable to determine the database type for a column /// </exception> /// <param name="dataSet">the DataSet containing the database schema /// to be created. /// </param> /// <returns>An SQL creation script corresponding to the schema of /// the passed DataSet.</returns> internal string GetSchemaScript(DataSet dataSet) { if (dataSet == null) { throw new ArgumentException("null is not a valid parameter value", "dataSet"); } StringBuilder command = new StringBuilder(); foreach (DataTable table in dataSet.Tables) try { command.Append(MakeTable(table)); } catch (ArgumentException exception) { throw new ArgumentException("Table does not contain any columns", table.TableName, exception); } foreach (DataTable table in dataSet.Tables) if (table.PrimaryKey.Length > 0) { string tableName = MakeSafe(tablePrefix + table.TableName); string primaryKeyName = MakeSafe("PK_" + tablePrefix + table.TableName); string primaryKeyList = MakeList(table.PrimaryKey); command.AppendFormat("ALTER TABLE {0} WITH NOCHECK ADD CONSTRAINT {1} PRIMARY KEY CLUSTERED ({2});\n", tableName, primaryKeyName, primaryKeyList); } foreach (DataRelation relation in dataSet.Relations) try { command.Append(MakeRelation(relation)); } catch (ArgumentException exception) { throw new ArgumentException("Relationship has an empty column list", relation.RelationName, exception); } return command.ToString(); } /// <summary> /// Returns a script which creates a database table that /// corresponds to <paramref name="table"/>. /// </summary> /// <param name="table"></param> /// <returns>the script which creates a table corresponding to <paramref name="table"/></returns> private string MakeTable(DataTable table) { StringBuilder command = new StringBuilder(); string tableName = MakeSafe(tablePrefix + table.TableName); string tableColumns = MakeList(table.Columns); command.AppendFormat("if exists (select * from dbo.sysobjects where id = object_id(N'{0}') and OBJECTPROPERTY(id, N'IsUserTable') = 1) DROP TABLE {0};", tableName); command.AppendFormat("CREATE TABLE {0} ({1});\n", tableName, tableColumns); return command.ToString(); } /// <summary> /// Returns the names of the columns in <paramref name="columns"/>. /// </summary> /// <param name="columns">the collection of columns to be put in the list</param> /// <returns>the names of the columns in a comma separated list</returns> /// <exception cref="System.ArgumentException">This is thrown if /// <paramref name="columns"/> is empty or null</exception> private string MakeList(DataColumn[] columns) { if ((columns == null) || (columns.Length < 1)) { throw new ArgumentException("Invalid column list!", "columns"); } StringBuilder list = new StringBuilder(); bool isFirstColumn = true; foreach (DataColumn c in columns) { if (!isFirstColumn) { list.Append(", "); } list.Append(MakeSafe(c.ColumnName)); isFirstColumn = false; } return list.ToString(); } /// <summary> /// Returns the names of the columns in <paramref name="columns"/>. Each /// name is followed by the type of data which the column contains. /// </summary> /// <param name="columns">the collection of columns to be put in the list</param> /// <returns>the names of the columns in a comma separated list</returns> /// <exception cref="System.ArgumentException">This is thrown if /// <paramref name="columns"/> is empty or null</exception> private string MakeList(DataColumnCollection columns) { if ((columns == null) || (columns.Count < 1)) { throw new ArgumentException("Invalid column list!", "columns"); } StringBuilder list = new StringBuilder(); bool isFirstColumn = true; foreach (DataColumn c in columns) { if (!isFirstColumn) { list.Append(", "); } string columnName = MakeSafe(c.ColumnName); string columnType = GetTypeFor(c); list.AppendFormat("{0} {1}", columnName, columnType); isFirstColumn = false; } return list.ToString(); } /// <summary> /// Returns a script which will create a database relations /// corresponding to the passed DataRelation. /// </summary> /// <param name="relation">the DataRelation to be scripted</param> /// <returns>the script to create the relation</returns> /// <exception cref="System.ArgumentException">This is thrown if /// <paramref name="relation"/> is null or any of the /// key sets in the relation are empty</exception> private string MakeRelation(DataRelation relation) { if (relation == null) { throw new ArgumentException("Invalid argument value (null)", "relation"); } StringBuilder command = new StringBuilder(); string childTable = MakeSafe(tablePrefix + relation.ChildTable.TableName); string parentTable = MakeSafe(tablePrefix + relation.ParentTable.TableName); string relationName = MakeSafe(relation.RelationName); string childColumns = MakeList(relation.ChildColumns); string parentColumns = MakeList(relation.ParentColumns); command.AppendFormat("ALTER TABLE {0} ADD CONSTRAINT {1} FOREIGN KEY ({2}) REFERENCES {3} ({4});\n", childTable, relationName, childColumns, parentTable, parentColumns); return command.ToString(); } public string TablePrefix { set { tablePrefix = value; } get { return tablePrefix; } } public string DbOwner { set { dbOwner = value; } get { return dbOwner; } } } }
// Copyright 2009 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; using NodaTime.Text; using NUnit.Framework; namespace NodaTime.Test { [TestFixture] public partial class DurationTest { /// <summary> /// Using the default constructor is equivalent to Duration.Zero. /// </summary> [Test] public void DefaultConstructor() { var actual = new Duration(); Assert.AreEqual(Duration.Zero, actual); } [Test] public void BinarySerialization() { TestHelper.AssertBinaryRoundtrip(Duration.FromTicks(12345L)); } [Test] public void XmlSerialization() { Duration value = new PeriodBuilder { Days = 5, Hours = 3, Minutes = 20, Seconds = 35, Ticks = 1234500 }.Build().ToDuration(); TestHelper.AssertXmlRoundtrip(value, "<value>5:03:20:35.12345</value>"); TestHelper.AssertXmlRoundtrip(-value, "<value>-5:03:20:35.12345</value>"); } [Test] [TestCase("<value>XYZ</value>", typeof(UnparsableValueException), Description = "Completely unparsable")] public void XmlSerialization_Invalid(string xml, Type expectedExceptionType) { TestHelper.AssertXmlInvalid<Duration>(xml, expectedExceptionType); } // Tests copied from Nanoseconds in its brief existence... there may well be some overlap between // this and older Duration tests. [Test] [TestCase(long.MinValue)] [TestCase(long.MinValue + 1)] [TestCase(-NodaConstants.NanosecondsPerDay - 1)] [TestCase(-NodaConstants.NanosecondsPerDay)] [TestCase(-NodaConstants.NanosecondsPerDay + 1)] [TestCase(-1)] [TestCase(0)] [TestCase(1)] [TestCase(NodaConstants.NanosecondsPerDay - 1)] [TestCase(NodaConstants.NanosecondsPerDay)] [TestCase(NodaConstants.NanosecondsPerDay + 1)] [TestCase(long.MaxValue - 1)] [TestCase(long.MaxValue)] public void Int64Conversions(long int64Nanos) { var nanoseconds = Duration.FromNanoseconds(int64Nanos); Assert.AreEqual(int64Nanos, nanoseconds.ToInt64Nanoseconds()); } [Test] [TestCase(long.MinValue)] [TestCase(long.MinValue + 1)] [TestCase(-NodaConstants.NanosecondsPerDay - 1)] [TestCase(-NodaConstants.NanosecondsPerDay)] [TestCase(-NodaConstants.NanosecondsPerDay + 1)] [TestCase(-1)] [TestCase(0)] [TestCase(1)] [TestCase(NodaConstants.NanosecondsPerDay - 1)] [TestCase(NodaConstants.NanosecondsPerDay)] [TestCase(NodaConstants.NanosecondsPerDay + 1)] [TestCase(long.MaxValue - 1)] [TestCase(long.MaxValue)] public void DecimalConversions(long int64Nanos) { decimal decimalNanos = int64Nanos; var nanoseconds = Duration.FromNanoseconds(decimalNanos); Assert.AreEqual(decimalNanos, nanoseconds.ToDecimalNanoseconds()); // And multiply it by 100, which proves we still work for values out of the range of Int64 decimalNanos *= 100; nanoseconds = Duration.FromNanoseconds(decimalNanos); Assert.AreEqual(decimalNanos, nanoseconds.ToDecimalNanoseconds()); } [Test] [TestCase(long.MinValue)] [TestCase(long.MinValue + 1)] [TestCase(-NodaConstants.TicksPerDay - 1)] [TestCase(-NodaConstants.TicksPerDay)] [TestCase(-NodaConstants.TicksPerDay + 1)] [TestCase(-1)] [TestCase(0)] [TestCase(1)] [TestCase(NodaConstants.TicksPerDay - 1)] [TestCase(NodaConstants.TicksPerDay)] [TestCase(NodaConstants.TicksPerDay + 1)] [TestCase(long.MaxValue - 1)] [TestCase(long.MaxValue)] public void FromTicks(long ticks) { var nanoseconds = Duration.FromTicks(ticks); Assert.AreEqual(ticks * (decimal) NodaConstants.NanosecondsPerTick, nanoseconds.ToDecimalNanoseconds()); // Just another sanity check, although Ticks is covered in more detail later. Assert.AreEqual(ticks, nanoseconds.Ticks); } [Test] public void FromMethods_OutOfRange() { // Not checking the exact values here so much as that the exception is appropriate. Assert.Throws<ArgumentOutOfRangeException>(() => Duration.FromDays(int.MinValue)); Assert.Throws<ArgumentOutOfRangeException>(() => Duration.FromDays(int.MaxValue)); Assert.Throws<ArgumentOutOfRangeException>(() => Duration.FromHours(int.MinValue)); Assert.Throws<ArgumentOutOfRangeException>(() => Duration.FromHours(int.MaxValue)); Assert.Throws<ArgumentOutOfRangeException>(() => Duration.FromMinutes(long.MinValue)); Assert.Throws<ArgumentOutOfRangeException>(() => Duration.FromMinutes(long.MaxValue)); Assert.Throws<ArgumentOutOfRangeException>(() => Duration.FromSeconds(long.MinValue)); Assert.Throws<ArgumentOutOfRangeException>(() => Duration.FromSeconds(long.MaxValue)); Assert.Throws<ArgumentOutOfRangeException>(() => Duration.FromMilliseconds(long.MinValue)); Assert.Throws<ArgumentOutOfRangeException>(() => Duration.FromMilliseconds(long.MaxValue)); // FromTicks never throws. Assert.Throws<ArgumentOutOfRangeException>(() => Duration.FromNanoseconds(decimal.MinValue)); Assert.Throws<ArgumentOutOfRangeException>(() => Duration.FromNanoseconds(decimal.MaxValue)); } [Test] public void ConstituentParts_Positive() { var nanos = Duration.FromNanoseconds(NodaConstants.NanosecondsPerDay * 5 + 100); Assert.AreEqual(5, nanos.FloorDays); Assert.AreEqual(100, nanos.NanosecondOfFloorDay); } [Test] public void ConstituentParts_Negative() { var nanos = Duration.FromNanoseconds(NodaConstants.NanosecondsPerDay * -5 + 100); Assert.AreEqual(-5, nanos.FloorDays); Assert.AreEqual(100, nanos.NanosecondOfFloorDay); } [Test] public void ConstituentParts_Large() { // And outside the normal range of long... var nanos = Duration.FromNanoseconds(NodaConstants.NanosecondsPerDay * 365000m + 500m); Assert.AreEqual(365000, nanos.FloorDays); Assert.AreEqual(500, nanos.NanosecondOfFloorDay); } [Test] [TestCase(1, 100L, 2, 200L, 3, 300L)] [TestCase(1, NodaConstants.NanosecondsPerDay - 5, 3, 100L, 5, 95L, TestName = "Overflow")] [TestCase(1, 10L, -1, NodaConstants.NanosecondsPerDay - 100L, 0, NodaConstants.NanosecondsPerDay - 90L, TestName = "Underflow")] public void Addition_Subtraction(int leftDays, long leftNanos, int rightDays, long rightNanos, int resultDays, long resultNanos) { var left = new Duration(leftDays, leftNanos); var right = new Duration(rightDays, rightNanos); var result = new Duration(resultDays, resultNanos); Assert.AreEqual(result, left + right); Assert.AreEqual(result, left.Plus(right)); Assert.AreEqual(result, Duration.Add(left, right)); Assert.AreEqual(left, result - right); Assert.AreEqual(left, result.Minus(right)); Assert.AreEqual(left, Duration.Subtract(result, right)); } [Test] public void Equality() { var equal1 = new Duration(1, NodaConstants.NanosecondsPerHour); var equal2 = Duration.FromTicks(NodaConstants.TicksPerHour * 25); var different1 = new Duration(1, 200L); var different2 = new Duration(2, NodaConstants.TicksPerHour); TestHelper.TestEqualsStruct(equal1, equal2, different1); TestHelper.TestOperatorEquality(equal1, equal2, different1); TestHelper.TestEqualsStruct(equal1, equal2, different2); TestHelper.TestOperatorEquality(equal1, equal2, different2); } [Test] public void Comparison() { var equal1 = new Duration(1, NodaConstants.NanosecondsPerHour); var equal2 = Duration.FromTicks(NodaConstants.TicksPerHour * 25); var greater1 = new Duration(1, NodaConstants.NanosecondsPerHour + 1); var greater2 = new Duration(2, 0L); TestHelper.TestCompareToStruct(equal1, equal2, greater1); TestHelper.TestNonGenericCompareTo(equal1, equal2, greater1); TestHelper.TestOperatorComparisonEquality(equal1, equal2, greater1, greater2); } [Test] [TestCase(1, 5L, 2, 2, 10L, TestName = "Small, positive")] [TestCase(-1, NodaConstants.NanosecondsPerDay - 10, 2, -1, NodaConstants.NanosecondsPerDay - 20, TestName = "Small, negative")] [TestCase(365000, 1L, 2, 365000 * 2, 2L, TestName = "More than 2^63 nanos before multiplication")] [TestCase(1000, 1L, 365, 365000, 365L, TestName = "More than 2^63 nanos after multiplication")] [TestCase(1000, 1L, -365, -365001, NodaConstants.NanosecondsPerDay - 365L, TestName = "Less than -2^63 nanos after multiplication")] [TestCase(0, 1L, NodaConstants.NanosecondsPerDay, 1, 0L, TestName = "Large scalar")] public void Multiplication(int startDays, long startNanoOfDay, long scalar, int expectedDays, long expectedNanoOfDay) { var start = new Duration(startDays, startNanoOfDay); var expected = new Duration(expectedDays, expectedNanoOfDay); Assert.AreEqual(expected, start * scalar); } [Test] [TestCase(0, 0L, 0, 0L)] [TestCase(1, 0L, -1, 0L)] [TestCase(0, 500L, -1, NodaConstants.NanosecondsPerDay - 500L)] [TestCase(365000, 500L, -365001, NodaConstants.NanosecondsPerDay - 500L)] public void UnaryNegation(int startDays, long startNanoOfDay, int expectedDays, long expectedNanoOfDay) { var start = new Duration(startDays, startNanoOfDay); var expected = new Duration(expectedDays, expectedNanoOfDay); Assert.AreEqual(expected, -start); // Test it the other way round as well... Assert.AreEqual(start, -expected); } [Test] // Test cases around 0 [TestCase(-1, NodaConstants.NanosecondsPerDay - 1, NodaConstants.NanosecondsPerDay, 0, 0L)] [TestCase(0, 0L, NodaConstants.NanosecondsPerDay, 0, 0L)] [TestCase(0, 1L, NodaConstants.NanosecondsPerDay, 0, 0L)] // Test cases around dividing -1 day by "nanos per day" [TestCase(-2, NodaConstants.NanosecondsPerDay - 1, NodaConstants.NanosecondsPerDay, -1, NodaConstants.NanosecondsPerDay - 1)] // -1ns [TestCase(-1, 0, NodaConstants.NanosecondsPerDay, -1, NodaConstants.NanosecondsPerDay - 1)] // -1ns [TestCase(-1, 1L, NodaConstants.NanosecondsPerDay, 0, 0L)] // Test cases around dividing 1 day by "nanos per day" [TestCase(0, NodaConstants.NanosecondsPerDay - 1, NodaConstants.NanosecondsPerDay, 0, 0L)] [TestCase(1, 0, NodaConstants.NanosecondsPerDay, 0, 1L)] [TestCase(1, NodaConstants.NanosecondsPerDay - 1, NodaConstants.NanosecondsPerDay, 0, 1L)] [TestCase(10, 20L, 5, 2, 4L)] // Large value, which will use decimal arithmetic [TestCase(365000, 3000L, 1000, 365, 3L)] public void Division(int startDays, long startNanoOfDay, long divisor, int expectedDays, long expectedNanoOfDay) { var start = new Duration(startDays, startNanoOfDay); var expected = new Duration(expectedDays, expectedNanoOfDay); Assert.AreEqual(expected, start / divisor); } [Test] public void Ticks_Zero() { Assert.AreEqual(0, Duration.FromTicks(0).Ticks); Assert.AreEqual(0, Duration.FromNanoseconds(99L).Ticks); Assert.AreEqual(0, Duration.FromNanoseconds(-99L).Ticks); } [Test] [TestCase(5L)] [TestCase(NodaConstants.TicksPerDay * 2)] [TestCase(NodaConstants.TicksPerDay * 365000)] public void Ticks_Positive(long ticks) { Assert.IsTrue(ticks > 0); Duration start = Duration.FromTicks(ticks); Assert.AreEqual(ticks, start.Ticks); // We truncate towards zero... so subtracting 1 nanosecond should // reduce the number of ticks, and adding 99 nanoseconds should not change it Assert.AreEqual(ticks - 1, start.MinusSmallNanoseconds(1L).Ticks); Assert.AreEqual(ticks, start.PlusSmallNanoseconds(99L).Ticks); } [Test] [TestCase(-5L)] [TestCase(-NodaConstants.TicksPerDay * 2)] [TestCase(-NodaConstants.TicksPerDay * 365000)] public void Ticks_Negative(long ticks) { Assert.IsTrue(ticks < 0); Duration start = Duration.FromTicks(ticks); Assert.AreEqual(ticks, start.Ticks); // We truncate towards zero... so subtracting 99 nanoseconds should // have no effect, and adding 1 should increase the number of ticks Assert.AreEqual(ticks, start.MinusSmallNanoseconds(99L).Ticks); Assert.AreEqual(ticks + 1, start.PlusSmallNanoseconds(1L).Ticks); } [Test] public void Validation() { TestHelper.AssertValid(Duration.FromDays, (1 << 24) - 1); TestHelper.AssertOutOfRange(Duration.FromDays, 1 << 24); TestHelper.AssertValid(Duration.FromDays, -(1 << 24)); TestHelper.AssertOutOfRange(Duration.FromDays, -(1 << 24) - 1); } [Test] public void TicksWithOverflow() { Duration maxTicks = Duration.FromTicks(long.MaxValue) + Duration.FromTicks(1); Assert.Throws<OverflowException>(() => maxTicks.Ticks.ToString()); } [Test] public void PositiveComponents() { // Worked out with a calculator :) Duration duration = Duration.FromNanoseconds(1234567890123456L); Assert.AreEqual(14, duration.Days); Assert.AreEqual(24967890123456L, duration.NanosecondOfDay); Assert.AreEqual(6, duration.Hours); Assert.AreEqual(56, duration.Minutes); Assert.AreEqual(7, duration.Seconds); Assert.AreEqual(890, duration.Milliseconds); Assert.AreEqual(8901234, duration.SubsecondTicks); Assert.AreEqual(890123456, duration.SubsecondNanoseconds); } [Test] public void NegativeComponents() { // Worked out with a calculator :) Duration duration = Duration.FromNanoseconds(-1234567890123456L); Assert.AreEqual(-14, duration.Days); Assert.AreEqual(-24967890123456L, duration.NanosecondOfDay); Assert.AreEqual(-6, duration.Hours); Assert.AreEqual(-56, duration.Minutes); Assert.AreEqual(-7, duration.Seconds); Assert.AreEqual(-890, duration.Milliseconds); Assert.AreEqual(-8901234, duration.SubsecondTicks); Assert.AreEqual(-890123456, duration.SubsecondNanoseconds); } [Test] public void PositiveTotals() { Duration duration = Duration.FromDays(4) + Duration.FromHours(3) + Duration.FromMinutes(2) + Duration.FromSeconds(1) + Duration.FromNanoseconds(123456789L); Assert.AreEqual(4.1264, duration.TotalDays, 0.0001); Assert.AreEqual(99.0336, duration.TotalHours, 0.0001); Assert.AreEqual(5942.0187, duration.TotalMinutes, 0.0001); Assert.AreEqual(356521.123456789, duration.TotalSeconds, 0.000000001); } [Test] public void NegativeTotals() { Duration duration = Duration.FromDays(-4) + Duration.FromHours(-3) + Duration.FromMinutes(-2) + Duration.FromSeconds(-1) + Duration.FromNanoseconds(-123456789L); Assert.AreEqual(-4.1264, duration.TotalDays, 0.0001); Assert.AreEqual(-99.0336, duration.TotalHours, 0.0001); Assert.AreEqual(-5942.0187, duration.TotalMinutes, 0.0001); Assert.AreEqual(-356521.123456789, duration.TotalSeconds, 0.000000001); } [Test] public void MaxMinRelationship() { // Max and Min work like they do for other signed types - basically the max value is one less than the absolute // of the min value. Assert.AreEqual(Duration.MinValue, -Duration.MaxValue - Duration.Epsilon); } } }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////#define while //Lexical_TestClass_pre_009 #define while //Lexical_TestClass_pre_009 #define True1 //Lexical_TestClass_pre_012 #define True2 #define False1 #undef False1 #undef False1 #undef False2 //Lexical_TestClass_pre_013 #define foo// Should work fine #define bar // As should this #define aaa #define bbb #undef aaa// Should Work #undef bbb// Should also work #if !foo #error !foo #endif #if !bar #error !bar #endif #if aaa #error aaa #endif #if bbb #error bbb #endif #define TESTDEF //Lexical_TestClass_preproc_03 #define TESTDEF3 //Lexical_TestClass_preproc_04 #define TESTDEF2 #undef TESTDEF3 #define FOO //Lexical_TestClass_preproc_05 #if FOO #define BAR #endif #define FOO2 //Lexical_TestClass_preproc_06 #undef FOO2 #undef FOO2 #define FOO3 //Lexical_TestClass_preproc_07 #undef BAR3 #define TEST //Lexical_TestClass_preproc_15-25,32 #define TEST2 //Lexical_TestClass_preproc_17-23,32 #define for //Lexical_TestClass_preproc_39 using System; using System.Reflection; using Microsoft.SPOT.Platform.Test; namespace Microsoft.SPOT.Platform.Tests { public class LexicalTests2 : IMFTestInterface { [SetUp] public InitializeResult Initialize() { return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } //Lexical Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Lexical //Test Case Calls [TestMethod] public MFTestResults Lexical_pre_009_Test() { Log.Comment("Section 2.3Preprocessing"); Log.Comment("Verify #define and #undef"); if (Lexical_TestClass_pre_009.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_pre_012_Test() { Log.Comment("Section 2.3Preprocessing"); Log.Comment("Verify #if operators and parens"); if (Lexical_TestClass_pre_012.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_pre_013_Test() { Log.Comment("Section 2.3Preprocessing"); Log.Comment("Verify # commands with comments"); if (Lexical_TestClass_pre_013.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_03_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("#define/#undef - verify #define works"); if (Lexical_TestClass_preproc_03.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_04_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("#define/#undef - verify #undef works"); if (Lexical_TestClass_preproc_04.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_05_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Exact example used in spec definition - 2.3.1"); if (Lexical_TestClass_preproc_05.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_06_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Using #undef on a non-existing identifier compiles fine"); if (Lexical_TestClass_preproc_06.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_07_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Nested #if's"); if (Lexical_TestClass_preproc_07.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_15_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Verify the ! operator on #identifiers"); if (Lexical_TestClass_preproc_15.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_16_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Verify the ! operator on #identifiers with parenthesis"); if (Lexical_TestClass_preproc_16.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_17_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Verify the double ampersand operator works"); if (Lexical_TestClass_preproc_17.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_18_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Verify the double ampersand operator works with parentheses"); if (Lexical_TestClass_preproc_18.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_19_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Verify the || operator works "); if (Lexical_TestClass_preproc_19.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_20_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Verify the || operator works with parentheses"); if (Lexical_TestClass_preproc_20.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_21_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Verify the == operator works with/without parentheses"); if (Lexical_TestClass_preproc_21.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_22_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Verify the != operator works with/without parentheses"); if (Lexical_TestClass_preproc_22.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_23_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Grouping operators: ! double ampersand || != == true false"); if (Lexical_TestClass_preproc_23.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_24_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Verifying comments and #preprocessor items"); if (Lexical_TestClass_preproc_24.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_25_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Verifying comments and #preprocessor items"); if (Lexical_TestClass_preproc_25.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_31_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Verifying comments and #preprocessor items"); if (Lexical_TestClass_preproc_31.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_32_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Verify the usage of #elif"); if (Lexical_TestClass_preproc_32.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_39_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Verify that a # keyword (i.e. for) can be used as a #preprocessor identifier"); if (Lexical_TestClass_preproc_39.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } //Compiled Test Cases public class Lexical_TestClass_pre_009 { public static int Main_old(string[] args) { int i = 2; #if while while (--i > 0) ; #endif return(i > 0 ? 1 : 0); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Lexical_TestClass_pre_012 { public static int Main_old(string[] args) { int i = 6; #if True1 == true i--; #endif #if False1 == false i--; #endif #if false #error #elif True2 == True1 #elif True2 == True1 i--; #else #error #else #elif True2 == True1 #endif #if (True1 != false) && ((False1) == False2) && (true || false) i--; #else #error #if (True != false) && ((False1) == False2) && (true || false) #endif #if ((true == True1) != (false && true)) i--; #else #error ((true == True1) != (false && true)) #endif #if !(!(!!(true))) != false i--; #else #error !(!(!!(true))) != false #endif return(i > 0 ? 1 : 0); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Lexical_TestClass_pre_013 { public static int Main_old(string[] args) { int i = 0; return(i > 0 ? 1 : 0); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Lexical_TestClass_preproc_03 { public static void Main_old(String[] args) { Log.Comment("Starting!"); #if TESTDEF Log.Comment("Good"); #else Log.Comment("Bad"); #endif } public static bool testMethod() { Main_old(null); return true; } } public class Lexical_TestClass_preproc_04 { public static void Main_old(String[] args) { Log.Comment("Starting!"); #if TESTDEF3 Log.Comment("TESTDEF3 is defined"); #else Log.Comment("TESTDEF3 is not defined"); #endif #if TESTDEF2 Log.Comment("TESTDEF2 is defined"); #else Log.Comment("TESTDEF2 not defined"); #endif } public static bool testMethod() { Main_old(null); return true; } } #if BAR class Lexical_TestClass_preproc_05 { public static void Main_old(String[] args) { } public static bool testMethod() { Main_old(null); return true; } } #endif class Lexical_TestClass_preproc_06 { public static void Main_old(String[] args) { } public static bool testMethod() { Main_old(null); return true; } } class Lexical_TestClass_preproc_07 { public static void Main_old(String[] args) { Log.Comment("Starting:"); #if FOO3 Log.Comment("Inside FOO"); #if BAR3 Log.Comment("Inside BAR"); #else Log.Comment("Inside BAR's else"); #endif #endif } public static bool testMethod() { Main_old(null); return true; } } class Lexical_TestClass_preproc_15 { public static void Main_old(String[] args) { #if ! TEST Log.Comment("Problem"); #else Log.Comment("Good"); #endif } public static bool testMethod() { Main_old(null); return true; } } class Lexical_TestClass_preproc_16 { public static void Main_old(String[] args) { #if !(TEST) Log.Comment("Problem"); #else Log.Comment("Good"); #endif } public static bool testMethod() { Main_old(null); return true; } } class Lexical_TestClass_preproc_17 { public static void Main_old(String[] args) { #if TEST && TEST2 Log.Comment("Good"); #endif #if TEST && TEST3 Log.Comment("Problem"); #endif } public static bool testMethod() { Main_old(null); return true; } } class Lexical_TestClass_preproc_18 { public static void Main_old(String[] args) { #if (TEST && TEST2) Log.Comment("Good"); #endif #if (TEST && TEST3) Log.Comment("Problem"); #endif } public static bool testMethod() { Main_old(null); return true; } } class Lexical_TestClass_preproc_19 { public static void Main_old(String[] args) { #if TEST || TEST2 Log.Comment("Good"); #endif #if TEST3 || TEST2 Log.Comment("Good"); #endif #if TEST3 || TEST4 Log.Comment("Problem"); #endif } public static bool testMethod() { Main_old(null); return true; } } class Lexical_TestClass_preproc_20 { public static void Main_old(String[] args) { #if (TEST || TEST2) Log.Comment("Good"); #endif #if (TEST3 || TEST2) Log.Comment("Good"); #endif #if (TEST3 || TEST4) Log.Comment("Problem"); #endif } public static bool testMethod() { Main_old(null); return true; } } class Lexical_TestClass_preproc_21 { public static void Main_old(String[] args) { #if TEST == TEST2 Log.Comment("Good"); #endif #if (TEST == TEST2) Log.Comment("Good"); #endif #if TEST==TEST2 Log.Comment("Good"); #endif #if (TEST == TEST3) Log.Comment("Bad"); #endif #if TEST3 == TEST Log.Comment("Bad"); #endif } public static bool testMethod() { Main_old(null); return true; } } class Lexical_TestClass_preproc_22 { public static void Main_old(String[] args) { #if TEST != TEST2 Log.Comment("Bad"); #endif #if (TEST != TEST2) Log.Comment("Bad"); #endif #if TEST!=TEST2 Log.Comment("Bad"); #endif #if (TEST != TEST3) Log.Comment("Good"); #endif #if TEST3 != TEST Log.Comment("Good"); #endif #if TEST3!=TEST Log.Comment("Good"); #endif } public static bool testMethod() { Main_old(null); return true; } } class Lexical_TestClass_preproc_23 { public static void Main_old(String[] args) { #if (TEST && TEST2) || (TEST3 || TEST4) Log.Comment("1 - Good"); #endif #if (TEST3 == TEST4) || (TEST == TEST2) Log.Comment("2 - Good"); #endif #if (TEST != TEST3) && (TEST2 != TEST4) Log.Comment("3 - Good"); #endif #if (! TEST4) && (TEST2 == TEST) Log.Comment("4 - Good"); #endif #if (TEST == true) && (TEST2 != false) Log.Comment("5 - Good"); #endif } public static bool testMethod() { Main_old(null); return true; } } class Lexical_TestClass_preproc_24 { public static void Main_old(String[] args) { #if TEST Log.Comment("Good"); #endif } public static bool testMethod() { Main_old(null); return true; } } class Lexical_TestClass_preproc_25 { public static void Main_old(String[] args) { #if TEST Log.Comment("Good"); #endif } public static bool testMethod() { Main_old(null); return true; } } class Lexical_TestClass_preproc_31 { public static void Main_old(String[] args) { #if TEST Log.Comment("Bad"); #else Log.Comment("Good"); #endif } public static bool testMethod() { Main_old(null); return true; } } class Lexical_TestClass_preproc_32 { public static void Main_old(String[] args) { #if TEST3 Log.Comment("Bad"); #elif TEST2 && TEST Log.Comment("Good"); #endif } public static bool testMethod() { Main_old(null); return true; } } class Lexical_TestClass_preproc_39 { public static void Main_old(String[] args) { #if for for (int x = 0; x < 3; x++) Log.Comment("Worked"); #else Log.Comment("It should not be showing this!"); #endif } public static bool testMethod() { Main_old(null); return true; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Net.Test.Common; using System.Threading; using Xunit; using Xunit.Abstractions; namespace System.Net.Sockets.Tests { public class SendPacketsAsync { private readonly ITestOutputHelper _log; private IPAddress _serverAddress = IPAddress.IPv6Loopback; // In the current directory private const string TestFileName = "NCLTest.Socket.SendPacketsAsync.testpayload"; private static int s_testFileSize = 1024; #region Additional test attributes public SendPacketsAsync(ITestOutputHelper output) { _log = TestLogging.GetInstance(); byte[] buffer = new byte[s_testFileSize]; for (int i = 0; i < s_testFileSize; i++) { buffer[i] = (byte)(i % 255); } try { _log.WriteLine("Creating file {0} with size: {1}", TestFileName, s_testFileSize); using (FileStream fs = new FileStream(TestFileName, FileMode.CreateNew)) { fs.Write(buffer, 0, buffer.Length); } } catch (IOException) { // Test payload file already exists. _log.WriteLine("Payload file exists: {0}", TestFileName); } } #endregion Additional test attributes #region Basic Arguments [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [PlatformSpecific(TestPlatforms.AnyUnix)] // SendPacketAsync not supported on Unix public void Unix_NotSupported_ThrowsPlatformNotSupportedException(SocketImplementationType type) { int port; using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port)) using (var sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) using (var args = new SocketAsyncEventArgs()) { sock.Connect(new IPEndPoint(_serverAddress, port)); args.SendPacketsElements = new SendPacketsElement[1]; Assert.Throws<PlatformNotSupportedException>(() => sock.SendPacketsAsync(args)); } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void Disposed_Throw(SocketImplementationType type) { int port; using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port)) { using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { sock.Connect(new IPEndPoint(_serverAddress, port)); sock.Dispose(); Assert.Throws<ObjectDisposedException>(() => { sock.SendPacketsAsync(new SocketAsyncEventArgs()); }); } } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void NullArgs_Throw(SocketImplementationType type) { int port; using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port)) { using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { sock.Connect(new IPEndPoint(_serverAddress, port)); ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() => { sock.SendPacketsAsync(null); }); Assert.Equal("e", ex.ParamName); } } } [Fact] public void NotConnected_Throw() { Socket socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); // Needs to be connected before send ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() => { socket.SendPacketsAsync(new SocketAsyncEventArgs()); }); Assert.Equal("e.SendPacketsElements", ex.ParamName); } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void NullList_Throws(SocketImplementationType type) { ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() => { SendPackets(type, (SendPacketsElement[])null, SocketError.Success, 0); }); Assert.Equal("e.SendPacketsElements", ex.ParamName); } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [PlatformSpecific(TestPlatforms.Windows)] // SendPacketAsync not supported on Unix public void NullElement_Ignored(SocketImplementationType type) { SendPackets(type, (SendPacketsElement)null, 0); } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [PlatformSpecific(TestPlatforms.Windows)] // SendPacketAsync not supported on Unix public void EmptyList_Ignored(SocketImplementationType type) { SendPackets(type, new SendPacketsElement[0], SocketError.Success, 0); } [OuterLoop] // TODO: Issue #11345 [Fact] public void SocketAsyncEventArgs_DefaultSendSize_0() { SocketAsyncEventArgs args = new SocketAsyncEventArgs(); Assert.Equal(0, args.SendPacketsSendSize); } #endregion Basic Arguments #region Buffers [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [PlatformSpecific(TestPlatforms.Windows)] // SendPacketAsync not supported on Unix public void NormalBuffer_Success(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(new byte[10]), 10); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [PlatformSpecific(TestPlatforms.Windows)] // SendPacketAsync not supported on Unix public void NormalBufferRange_Success(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(new byte[10], 5, 5), 5); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [PlatformSpecific(TestPlatforms.Windows)] // SendPacketAsync not supported on Unix public void EmptyBuffer_Ignored(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(new byte[0]), 0); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [PlatformSpecific(TestPlatforms.Windows)] // SendPacketAsync not supported on Unix public void BufferZeroCount_Ignored(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(new byte[10], 4, 0), 0); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [PlatformSpecific(TestPlatforms.Windows)] // SendPacketAsync not supported on Unix public void BufferMixedBuffers_ZeroCountBufferIgnored(SocketImplementationType type) { SendPacketsElement[] elements = new SendPacketsElement[] { new SendPacketsElement(new byte[10], 4, 0), // Ignored new SendPacketsElement(new byte[10], 4, 4), new SendPacketsElement(new byte[10], 0, 4) }; SendPackets(type, elements, SocketError.Success, 8); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [PlatformSpecific(TestPlatforms.Windows)] // SendPacketAsync not supported on Unix public void BufferZeroCountThenNormal_ZeroCountIgnored(SocketImplementationType type) { Assert.True(Capability.IPv6Support()); EventWaitHandle completed = new ManualResetEvent(false); int port; using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port)) { using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { sock.Connect(new IPEndPoint(_serverAddress, port)); using (SocketAsyncEventArgs args = new SocketAsyncEventArgs()) { args.Completed += OnCompleted; args.UserToken = completed; // First do an empty send, ignored args.SendPacketsElements = new SendPacketsElement[] { new SendPacketsElement(new byte[5], 3, 0) }; if (sock.SendPacketsAsync(args)) { Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out"); } Assert.Equal(SocketError.Success, args.SocketError); Assert.Equal(0, args.BytesTransferred); completed.Reset(); // Now do a real send args.SendPacketsElements = new SendPacketsElement[] { new SendPacketsElement(new byte[5], 1, 4) }; if (sock.SendPacketsAsync(args)) { Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out"); } Assert.Equal(SocketError.Success, args.SocketError); Assert.Equal(4, args.BytesTransferred); } } } } #endregion Buffers #region TransmitFileOptions [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [PlatformSpecific(TestPlatforms.Windows)] // SendPacketAsync not supported on Unix public void SocketDisconnected_TransmitFileOptionDisconnect(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(new byte[10], 4, 4), TransmitFileOptions.Disconnect, 4); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [PlatformSpecific(TestPlatforms.Windows)] // SendPacketAsync not supported on Unix public void SocketDisconnectedAndReusable_TransmitFileOptionReuseSocket(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(new byte[10], 4, 4), TransmitFileOptions.Disconnect | TransmitFileOptions.ReuseSocket, 4); } #endregion #region Files [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [PlatformSpecific(TestPlatforms.Windows)] // SendPacketAsync not supported on Unix public void SendPacketsElement_EmptyFileName_Throws(SocketImplementationType type) { Assert.Throws<ArgumentException>(() => { SendPackets(type, new SendPacketsElement(String.Empty), 0); }); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [PlatformSpecific(TestPlatforms.Windows)] // SendPacketAsync not supported on Unix public void SendPacketsElement_BlankFileName_Throws(SocketImplementationType type) { Assert.Throws<ArgumentException>(() => { // Existence is validated on send SendPackets(type, new SendPacketsElement(" \t "), 0); }); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [PlatformSpecific(TestPlatforms.Windows)] // SendPacketAsync not supported on Unix public void SendPacketsElement_BadCharactersFileName_Throws(SocketImplementationType type) { Assert.Throws<ArgumentException>(() => { // Existence is validated on send SendPackets(type, new SendPacketsElement("blarkd@dfa?/sqersf"), 0); }); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [PlatformSpecific(TestPlatforms.Windows)] // SendPacketAsync not supported on Unix public void SendPacketsElement_MissingDirectoryName_Throws(SocketImplementationType type) { Assert.Throws<DirectoryNotFoundException>(() => { // Existence is validated on send SendPackets(type, new SendPacketsElement(Path.Combine("nodir", "nofile")), 0); }); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [PlatformSpecific(TestPlatforms.Windows)] // SendPacketAsync not supported on Unix public void SendPacketsElement_MissingFile_Throws(SocketImplementationType type) { Assert.Throws<FileNotFoundException>(() => { // Existence is validated on send SendPackets(type, new SendPacketsElement("DoesntExit"), 0); }); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [PlatformSpecific(TestPlatforms.Windows)] // SendPacketAsync not supported on Unix public void SendPacketsElement_File_Success(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(TestFileName), s_testFileSize); // Whole File } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [PlatformSpecific(TestPlatforms.Windows)] // SendPacketAsync not supported on Unix public void SendPacketsElement_FileZeroCount_Success(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(TestFileName, 0, 0), s_testFileSize); // Whole File } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [PlatformSpecific(TestPlatforms.Windows)] // SendPacketAsync not supported on Unix public void SendPacketsElement_FilePart_Success(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(TestFileName, 10, 20), 20); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [PlatformSpecific(TestPlatforms.Windows)] // SendPacketAsync not supported on Unix public void SendPacketsElement_FileMultiPart_Success(SocketImplementationType type) { SendPacketsElement[] elements = new SendPacketsElement[] { new SendPacketsElement(TestFileName, 10, 20), new SendPacketsElement(TestFileName, 30, 10), new SendPacketsElement(TestFileName, 0, 10), }; SendPackets(type, elements, SocketError.Success, 40); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [PlatformSpecific(TestPlatforms.Windows)] // SendPacketAsync not supported on Unix public void SendPacketsElement_FileLargeOffset_Throws(SocketImplementationType type) { // Length is validated on Send SendPackets(type, new SendPacketsElement(TestFileName, 11000, 1), SocketError.InvalidArgument, 0); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [PlatformSpecific(TestPlatforms.Windows)] // SendPacketAsync not supported on Unix public void SendPacketsElement_FileLargeCount_Throws(SocketImplementationType type) { // Length is validated on Send SendPackets(type, new SendPacketsElement(TestFileName, 5, 10000), SocketError.InvalidArgument, 0); } #endregion Files #region GC Finalizer test // This test assumes sequential execution of tests and that it is going to be executed after other tests // that used Sockets. [Fact] public void TestFinalizers() { // Making several passes through the FReachable list. for (int i = 0; i < 3; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); } } #endregion #region Helpers private void SendPackets(SocketImplementationType type, SendPacketsElement element, TransmitFileOptions flags, int bytesExpected) { Assert.True(Capability.IPv6Support()); EventWaitHandle completed = new ManualResetEvent(false); int port; using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port)) { using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { sock.Connect(new IPEndPoint(_serverAddress, port)); using (SocketAsyncEventArgs args = new SocketAsyncEventArgs()) { args.Completed += OnCompleted; args.UserToken = completed; args.SendPacketsElements = new[] { element }; args.SendPacketsFlags = flags; if (sock.SendPacketsAsync(args)) { Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out"); } Assert.Equal(SocketError.Success, args.SocketError); Assert.Equal(bytesExpected, args.BytesTransferred); } switch (flags) { case TransmitFileOptions.Disconnect: // Sending data again throws with socket shut down error. Assert.Throws<SocketException>(() => { sock.Send(new byte[1] { 01 }); }); break; case TransmitFileOptions.ReuseSocket & TransmitFileOptions.Disconnect: // Able to send data again with reuse socket flag set. Assert.Equal(1, sock.Send(new byte[1] { 01 })); break; } } } } private void SendPackets(SocketImplementationType type, SendPacketsElement element, int bytesExpected) { SendPackets(type, new SendPacketsElement[] { element }, SocketError.Success, bytesExpected); } private void SendPackets(SocketImplementationType type, SendPacketsElement element, SocketError expectedResut, int bytesExpected) { SendPackets(type, new SendPacketsElement[] { element }, expectedResut, bytesExpected); } private void SendPackets(SocketImplementationType type, SendPacketsElement[] elements, SocketError expectedResut, int bytesExpected) { Assert.True(Capability.IPv6Support()); EventWaitHandle completed = new ManualResetEvent(false); int port; using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port)) { using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { sock.Connect(new IPEndPoint(_serverAddress, port)); using (SocketAsyncEventArgs args = new SocketAsyncEventArgs()) { args.Completed += OnCompleted; args.UserToken = completed; args.SendPacketsElements = elements; if (sock.SendPacketsAsync(args)) { Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out"); } Assert.Equal(expectedResut, args.SocketError); Assert.Equal(bytesExpected, args.BytesTransferred); } } } } private void OnCompleted(object sender, SocketAsyncEventArgs e) { EventWaitHandle handle = (EventWaitHandle)e.UserToken; handle.Set(); } #endregion Helpers } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Bond.Expressions { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; internal class DeserializerTransform<R> { delegate Expression NewObject(Type type, Type schemaType); delegate Expression NewContainer(Type type, Type schemaType, Expression count); readonly NewObject newObject; readonly NewContainer newContainer; readonly bool inlineNested; TypeAlias typeAlias; readonly Expression<Func<R, int, object>> deferredDeserialize; readonly List<Expression<Func<R, object>>> deserializeFuncs = new List<Expression<Func<R, object>>>(); readonly Dictionary<Type, int> deserializeIndex = new Dictionary<Type, int>(); readonly Stack<Type> inProgress = new Stack<Type>(); static readonly MethodInfo bondedConvert = Reflection.GenericMethodInfoOf((IBonded bonded) => bonded.Convert<object>()); static readonly MethodInfo bondedDeserialize = Reflection.GenericMethodInfoOf((IBonded bonded) => bonded.Deserialize<object>()); static readonly MethodInfo arrayResize = Reflection.GenericMethodInfoOf((object[] o) => Array.Resize(ref o, default(int))); static readonly ConstructorInfo arraySegmentCtor = typeof(ArraySegment<byte>).GetConstructor(typeof(byte[]), typeof(int), typeof(int)); static readonly MethodInfo bufferBlockCopy = Reflection.MethodInfoOf((byte[] a) => Buffer.BlockCopy(a, default(int), a, default(int), default(int))); public DeserializerTransform( Expression<Func<R, int, object>> deferredDeserialize, bool inlineNested = true, Expression<Func<Type, Type, object>> createObject = null, Expression<Func<Type, Type, int, object>> createContainer = null) { this.deferredDeserialize = deferredDeserialize; if (createObject != null) { newObject = (t1, t2) => Expression.Convert( Expression.Invoke( createObject, Expression.Constant(t1), Expression.Constant(t2)), t1); } else { newObject = (t1, t2) => New(t1, t2); } if (createContainer != null) { newContainer = (t1, t2, count) => Expression.Convert( Expression.Invoke( createContainer, Expression.Constant(t1), Expression.Constant(t2), count), t1); } else { newContainer = (t1, t2, count) => New(t1, t2, count); } this.inlineNested = inlineNested; } public IEnumerable<Expression<Func<R, object>>> Generate(IParser parser, Type type) { Audit.ArgNotNull(type, "type"); typeAlias = new TypeAlias(type); Deserialize(parser, null, type, type, true); return deserializeFuncs; } Expression Deserialize(IParser parser, Expression var, Type objectType, Type schemaType, bool initialize) { var inline = inlineNested && inProgress.Count != 0 && !inProgress.Contains(schemaType) && var != null; Expression body; inProgress.Push(schemaType); if (inline) { body = Struct(parser, var, schemaType, initialize); if (parser.ReaderParam != parser.ReaderValue) { body = Expression.Block( new[] { parser.ReaderParam }, Expression.Assign(parser.ReaderParam, parser.ReaderValue), body); } } else { int index; if (!deserializeIndex.TryGetValue(schemaType, out index)) { index = deserializeFuncs.Count; deserializeIndex[schemaType] = index; deserializeFuncs.Add(null); var result = Expression.Variable(objectType, objectType.Name); deserializeFuncs[index] = Expression.Lambda<Func<R, object>>( Expression.Block( new[] { result }, Struct(parser, result, schemaType, true), result), parser.ReaderParam); } if (var == null) body = null; else body = Expression.Assign(var, Expression.Convert( Expression.Invoke( deferredDeserialize, parser.ReaderValue, Expression.Constant(index)), objectType)); } inProgress.Pop(); return body; } Expression Struct(IParser parser, Expression var, Type schemaType, bool initialize) { var body = new List<Expression>(); if (initialize) { body.Add(Expression.Assign(var, newObject(var.Type, schemaType))); } ITransform transform; if (parser.HierarchyDepth > schemaType.GetHierarchyDepth()) { // Parser inheritance hierarchy is deeper than the type we are deserializing. // Recurse until hierarchies align. transform = new Transform( Base: baseParser => Struct(baseParser, var, schemaType, initialize: false)); } else { var baseType = schemaType.GetBaseSchemaType(); transform = new Transform( Fields: from field in schemaType.GetSchemaFields() select new Field( Id: field.Id, Value: (fieldParser, fieldType) => CheckedValue( fieldParser, DataExpression.PropertyOrField(var, field.Name), fieldType, field.GetSchemaType(), field.GetDefaultValue() == null), Omitted: () => field.GetModifier() == Modifier.Required ? ThrowExpression.RequiredFieldMissingException( field.DeclaringType.Name, Expression.Constant(field.Name)) : Expression.Empty()), Base: baseParser => baseType != null ? Struct(baseParser, Expression.Convert(var, baseType.GetObjectType()), baseType, initialize: false) : Expression.Empty()); } body.Add(parser.Apply(transform)); return Expression.Block(body); } Expression Nullable(IParser parser, Expression var, Type schemaType, bool initialize) { return parser.Container(schemaType.GetBondDataType(), (valueParser, valueType, next, count) => { var body = new List<Expression>(); if (initialize) body.Add(Expression.Assign(var, Expression.Default(var.Type))); body.Add(ControlExpression.While(next, Value(valueParser, var, valueType, schemaType, initialize: true))); return Expression.Block(body); }); } Expression Container(IParser parser, Expression container, Type schemaType, bool initialize) { var itemSchemaType = schemaType.GetValueType(); return parser.Container(itemSchemaType.GetBondDataType(), (valueParser, elementType, next, count) => { Expression addItem; ParameterExpression[] parameters; Expression beforeLoop = Expression.Empty(); Expression afterLoop = Expression.Empty(); if (schemaType.IsBondBlob()) { var blob = parser.Blob(count); if (blob != null) return typeAlias.Assign(container, blob); // Parser doesn't provide optimized read for blob so we will have to read byte-by-byte. var index = Expression.Variable(typeof(int), "index"); var array = Expression.Variable(typeof(byte[]), "array"); beforeLoop = Expression.Block( Expression.Assign(index, Expression.Constant(0)), Expression.Assign(array, Expression.NewArrayBounds(typeof(byte), count))); // If parser didn't provide real item count we may need to resize the array var newSize = Expression.Condition( Expression.GreaterThan(index, Expression.Constant(512)), Expression.Multiply(index, Expression.Constant(2)), Expression.Constant(1024)); addItem = Expression.Block( Expression.IfThen( Expression.GreaterThanOrEqual(index, Expression.ArrayLength(array)), Expression.Call(null, arrayResize.MakeGenericMethod(typeof(byte)), array, newSize)), valueParser.Scalar(elementType, BondDataType.BT_INT8, value => Expression.Assign( Expression.ArrayAccess(array, Expression.PostIncrementAssign(index)), Expression.Convert(value, typeof(byte))))); afterLoop = typeAlias.Assign( container, Expression.New(arraySegmentCtor, array, Expression.Constant(0), index)); parameters = new[] { index, array }; } else if (container.Type.IsArray) { var arrayElemType = container.Type.GetValueType(); var containerResizeMethod = arrayResize.MakeGenericMethod(arrayElemType); if (initialize) { beforeLoop = Expression.Assign(container, newContainer(container.Type, schemaType, count)); } if (arrayElemType == typeof(byte)) { var parseBlob = parser.Blob(count); if (parseBlob != null) { var blob = Expression.Variable(typeof(ArraySegment<byte>), "blob"); return Expression.Block( new[] { blob }, beforeLoop, Expression.Assign(blob, parseBlob), Expression.Call(null, bufferBlockCopy, new[] { Expression.Property(blob, "Array"), Expression.Property(blob, "Offset"), container, Expression.Constant(0), count })); } } var i = Expression.Variable(typeof(int), "i"); beforeLoop = Expression.Block( beforeLoop, Expression.Assign(i, Expression.Constant(0))); // Resize the array if we've run out of room var maybeResize = Expression.IfThen( Expression.Equal(i, Expression.ArrayLength(container)), Expression.Call( containerResizeMethod, container, Expression.Multiply( Expression.Condition( Expression.LessThan(i, Expression.Constant(32)), Expression.Constant(32), i), Expression.Constant(2)))); // Puts a single element into the array. addItem = Expression.Block( maybeResize, Value( valueParser, Expression.ArrayAccess(container, i), elementType, itemSchemaType, initialize: true), Expression.PostIncrementAssign(i)); // Expanding the array potentially leaves many blank // entries; this resize will get rid of them. afterLoop = Expression.IfThen( Expression.GreaterThan(Expression.ArrayLength(container), i), Expression.Call(containerResizeMethod, container, i)); parameters = new[] { i }; } else { var item = Expression.Variable(container.Type.GetValueType(), container + "_item"); if (initialize) { beforeLoop = Expression.Assign(container, newContainer(container.Type, schemaType, count)); } else { var capacity = container.Type.GetDeclaredProperty("Capacity", count.Type); if (capacity != null) { beforeLoop = Expression.Assign(Expression.Property(container, capacity), count); } } var add = container.Type.GetMethod(typeof(ICollection<>), "Add", item.Type); addItem = Expression.Block( Value(valueParser, item, elementType, itemSchemaType, initialize: true), Expression.Call(container, add, item)); parameters = new[] { item }; } return Expression.Block( parameters, beforeLoop, ControlExpression.While(next, addItem), afterLoop); }); } Expression Map(IParser parser, Expression map, Type schemaType, bool initialize) { var itemSchemaType = schemaType.GetKeyValueType(); return parser.Map(itemSchemaType.Key.GetBondDataType(), itemSchemaType.Value.GetBondDataType(), (keyParser, valueParser, keyType, valueType, nextKey, nextValue, count) => { Expression init = Expression.Empty(); var itemType = map.Type.GetKeyValueType(); var key = Expression.Variable(itemType.Key, map + "_key"); var value = Expression.Variable(itemType.Value, map + "_value"); if (initialize) { // TODO: should we use non-default Comparer init = Expression.Assign(map, newContainer(map.Type, schemaType, count)); } var add = map.Type.GetDeclaredProperty(typeof(IDictionary<,>), "Item", value.Type); Expression addItem = Expression.Block( Value(keyParser, key, keyType, itemSchemaType.Key, initialize: true), nextValue, Value(valueParser, value, valueType, itemSchemaType.Value, initialize: true), Expression.Assign(Expression.Property(map, add, new Expression[] { key }), value)); return Expression.Block( new [] { key, value }, init, ControlExpression.While(nextKey, addItem)); }); } Expression CheckedValue(IParser parser, Expression var, Expression valueType, Type schemaType, bool initialize) { var body = Value(parser, var, valueType, schemaType, initialize); if (schemaType.IsBondContainer() || schemaType.IsBondStruct() || schemaType.IsBondNullable()) { var expectedType = Expression.Constant(schemaType.GetBondDataType()); return PrunedExpression.IfThenElse( Expression.Equal(valueType, expectedType), body, ThrowExpression.InvalidTypeException(expectedType, valueType)); } return body; } Expression Value(IParser parser, Expression var, Expression valueType, Type schemaType, bool initialize) { if (schemaType.IsBondNullable()) return Nullable(parser, var, schemaType.GetValueType(), initialize); if (schemaType.IsBonded()) { var convert = bondedConvert.MakeGenericMethod(var.Type.GetValueType()); return parser.Bonded(value => Expression.Assign(var, Expression.Call(value, convert))); } if (schemaType.IsBondStruct()) { if (parser.IsBonded) { var deserialize = bondedDeserialize.MakeGenericMethod(schemaType); return parser.Bonded(value => Expression.Assign(var, Expression.Call(value, deserialize))); } return Deserialize(parser, var, var.Type, schemaType, initialize); } if (schemaType.IsBondMap()) return Map(parser, var, schemaType, initialize); if (schemaType.IsBondContainer()) return Container(parser, var, schemaType, initialize); return parser.Scalar(valueType, schemaType.GetBondDataType(), value => typeAlias.Assign(var, PrunedExpression.Convert(value, schemaType))); } static Expression New(Type type, Type schemaType, params Expression[] arguments) { if (schemaType.IsGenericType()) { schemaType = schemaType.GetGenericTypeDefinition().MakeGenericType(type.GetGenericArguments()); } else if (schemaType.IsArray) { var rank = schemaType.GetArrayRank(); schemaType = rank == 1 ? type.GetElementType().MakeArrayType() : type.GetElementType().MakeArrayType(rank); } var ctor = schemaType.GetConstructor(arguments.Select(a => a.Type).ToArray()); if (ctor != null) { return Expression.New(ctor, arguments); } return Expression.New(schemaType); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Net.Sockets.Tests { public class SendPacketsElementTest { #region Buffer [Fact] public void NullBufferCtor_Throws() { Assert.Throws<ArgumentNullException>(() => { SendPacketsElement element = new SendPacketsElement((byte[])null); }); } [Fact] public void NullBufferCtorWithOffset_Throws() { Assert.Throws<ArgumentNullException>(() => { SendPacketsElement element = new SendPacketsElement((byte[])null, 0, 0); }); } [Fact] public void NullBufferCtorWithEndOfPacket_Throws() { Assert.Throws<ArgumentNullException>(() => { // Elements with null Buffers are ignored on Send SendPacketsElement element = new SendPacketsElement((byte[])null, 0, 0, true); }); } [Fact] public void EmptyBufferCtor_Success() { // Elements with empty Buffers are ignored on Send SendPacketsElement element = new SendPacketsElement(new byte[0]); Assert.NotNull(element.Buffer); Assert.Equal(0, element.Buffer.Length); Assert.Equal(0, element.Offset); Assert.Equal(0, element.Count); Assert.False(element.EndOfPacket); Assert.Null(element.FilePath); } [Fact] public void BufferCtorNormal_Success() { SendPacketsElement element = new SendPacketsElement(new byte[10]); Assert.NotNull(element.Buffer); Assert.Equal(10, element.Buffer.Length); Assert.Equal(0, element.Offset); Assert.Equal(10, element.Count); Assert.False(element.EndOfPacket); Assert.Null(element.FilePath); } [Fact] public void BufferCtorNegOffset_ArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>(() => { SendPacketsElement element = new SendPacketsElement(new byte[10], -1, 11); }); } [Fact] public void BufferCtorNegCount_ArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>(() => { SendPacketsElement element = new SendPacketsElement(new byte[10], 0, -1); }); } [Fact] public void BufferCtorLargeOffset_ArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>(() => { SendPacketsElement element = new SendPacketsElement(new byte[10], 11, 1); }); } [Fact] public void BufferCtorLargeCount_ArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>(() => { SendPacketsElement element = new SendPacketsElement(new byte[10], 5, 10); }); } [Fact] public void BufferCtorEndOfBufferTrue_Success() { SendPacketsElement element = new SendPacketsElement(new byte[10], 2, 8, true); Assert.NotNull(element.Buffer); Assert.Equal(10, element.Buffer.Length); Assert.Equal(2, element.Offset); Assert.Equal(8, element.Count); Assert.True(element.EndOfPacket); Assert.Null(element.FilePath); } [Fact] public void BufferCtorEndOfBufferFalse_Success() { SendPacketsElement element = new SendPacketsElement(new byte[10], 6, 4, false); Assert.NotNull(element.Buffer); Assert.Equal(10, element.Buffer.Length); Assert.Equal(6, element.Offset); Assert.Equal(4, element.Count); Assert.False(element.EndOfPacket); Assert.Null(element.FilePath); } [Fact] public void BufferCtorZeroCount_Success() { // Elements with empty Buffers are ignored on Send SendPacketsElement element = new SendPacketsElement(new byte[0], 0, 0); Assert.NotNull(element.Buffer); Assert.Equal(0, element.Buffer.Length); Assert.Equal(0, element.Offset); Assert.Equal(0, element.Count); Assert.False(element.EndOfPacket); Assert.Null(element.FilePath); } #endregion Buffer #region File [Fact] public void FileCtorNull_Throws() { Assert.Throws<ArgumentNullException>(() => { SendPacketsElement element = new SendPacketsElement((string)null); }); } [Fact] public void FileCtorEmpty_Success() { // An exception will happen on send if this file doesn't exist SendPacketsElement element = new SendPacketsElement(String.Empty); Assert.Null(element.Buffer); Assert.Equal(0, element.Offset); Assert.Equal(0, element.Count); Assert.False(element.EndOfPacket); Assert.Equal(String.Empty, element.FilePath); } [Fact] public void FileCtorWhiteSpace_Success() { // An exception will happen on send if this file doesn't exist SendPacketsElement element = new SendPacketsElement(" \t "); Assert.Null(element.Buffer); Assert.Equal(0, element.Offset); Assert.Equal(0, element.Count); Assert.False(element.EndOfPacket); Assert.Equal(" \t ", element.FilePath); } [Fact] public void FileCtorNormal_Success() { // An exception will happen on send if this file doesn't exist SendPacketsElement element = new SendPacketsElement("SomeFileName"); // Send whole file Assert.Null(element.Buffer); Assert.Equal(0, element.Offset); Assert.Equal(0, element.Count); Assert.False(element.EndOfPacket); Assert.Equal("SomeFileName", element.FilePath); } [Fact] public void FileCtorZeroCountLength_Success() { // An exception will happen on send if this file doesn't exist SendPacketsElement element = new SendPacketsElement("SomeFileName", 0, 0); // Send whole file Assert.Null(element.Buffer); Assert.Equal(0, element.Offset); Assert.Equal(0, element.Count); Assert.False(element.EndOfPacket); Assert.Equal("SomeFileName", element.FilePath); } [Fact] public void FileCtorNegOffset_ArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>(() => { SendPacketsElement element = new SendPacketsElement("SomeFileName", -1, 11); }); } [Fact] public void FileCtorNegCount_ArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>(() => { SendPacketsElement element = new SendPacketsElement("SomeFileName", 0, -1); }); } // File lengths are validated on send [Fact] public void FileCtorEndOfBufferTrue_Success() { SendPacketsElement element = new SendPacketsElement("SomeFileName", 2, 8, true); Assert.Null(element.Buffer); Assert.Equal(2, element.Offset); Assert.Equal(8, element.Count); Assert.True(element.EndOfPacket); Assert.Equal("SomeFileName", element.FilePath); } [Fact] public void FileCtorEndOfBufferFalse_Success() { SendPacketsElement element = new SendPacketsElement("SomeFileName", 6, 4, false); Assert.Null(element.Buffer); Assert.Equal(6, element.Offset); Assert.Equal(4, element.Count); Assert.False(element.EndOfPacket); Assert.Equal("SomeFileName", element.FilePath); } #endregion File } }
using Duende.IdentityServer.Configuration; using Duende.IdentityServer.Events; using Duende.IdentityServer.Extensions; using Duende.IdentityServer.Models; using Duende.IdentityServer.Services; using Duende.IdentityServer.Validation; using DuendeDynamicProviders.Pages.Consent; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Options; namespace DuendeDynamicProviders.Pages.Device; [SecurityHeaders] [Authorize] public class Index : PageModel { private readonly IDeviceFlowInteractionService _interaction; private readonly IEventService _events; private readonly IOptions<IdentityServerOptions> _options; private readonly ILogger<Index> _logger; public Index( IDeviceFlowInteractionService interaction, IEventService eventService, IOptions<IdentityServerOptions> options, ILogger<Index> logger) { _interaction = interaction; _events = eventService; _options = options; _logger = logger; } public ViewModel View { get; set; } [BindProperty] public InputModel Input { get; set; } public async Task<IActionResult> OnGet(string userCode) { if (String.IsNullOrWhiteSpace(userCode)) { View = new ViewModel(); Input = new InputModel(); return Page(); } View = await BuildViewModelAsync(userCode); if (View == null) { ModelState.AddModelError("", DeviceOptions.InvalidUserCode); View = new ViewModel(); Input = new InputModel(); return Page(); } Input = new InputModel { UserCode = userCode, }; return Page(); } public async Task<IActionResult> OnPost() { var request = await _interaction.GetAuthorizationContextAsync(Input.UserCode); if (request == null) return RedirectToPage("/Error/Index"); ConsentResponse grantedConsent = null; // user clicked 'no' - send back the standard 'access_denied' response if (Input.Button == "no") { grantedConsent = new ConsentResponse { Error = AuthorizationError.AccessDenied }; // emit event await _events.RaiseAsync(new ConsentDeniedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues)); } // user clicked 'yes' - validate the data else if (Input.Button == "yes") { // if the user consented to some scope, build the response model if (Input.ScopesConsented != null && Input.ScopesConsented.Any()) { var scopes = Input.ScopesConsented; if (ConsentOptions.EnableOfflineAccess == false) { scopes = scopes.Where(x => x != Duende.IdentityServer.IdentityServerConstants.StandardScopes.OfflineAccess); } grantedConsent = new ConsentResponse { RememberConsent = Input.RememberConsent, ScopesValuesConsented = scopes.ToArray(), Description = Input.Description }; // emit event await _events.RaiseAsync(new ConsentGrantedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues, grantedConsent.ScopesValuesConsented, grantedConsent.RememberConsent)); } else { ModelState.AddModelError("", ConsentOptions.MustChooseOneErrorMessage); } } else { ModelState.AddModelError("", ConsentOptions.InvalidSelectionErrorMessage); } if (grantedConsent != null) { // communicate outcome of consent back to identityserver await _interaction.HandleRequestAsync(Input.UserCode, grantedConsent); // indicate that's it ok to redirect back to authorization endpoint return RedirectToPage("/Device/Success"); } // we need to redisplay the consent UI View = await BuildViewModelAsync(Input.UserCode, Input); return Page(); } private async Task<ViewModel> BuildViewModelAsync(string userCode, InputModel model = null) { var request = await _interaction.GetAuthorizationContextAsync(userCode); if (request != null) { return CreateConsentViewModel(model, request); } return null; } private ViewModel CreateConsentViewModel(InputModel model, DeviceFlowAuthorizationRequest request) { var vm = new ViewModel { ClientName = request.Client.ClientName ?? request.Client.ClientId, ClientUrl = request.Client.ClientUri, ClientLogoUrl = request.Client.LogoUri, AllowRememberConsent = request.Client.AllowRememberConsent }; vm.IdentityScopes = request.ValidatedResources.Resources.IdentityResources.Select(x => CreateScopeViewModel(x, model == null || model.ScopesConsented?.Contains(x.Name) == true)).ToArray(); var apiScopes = new List<ScopeViewModel>(); foreach (var parsedScope in request.ValidatedResources.ParsedScopes) { var apiScope = request.ValidatedResources.Resources.FindApiScope(parsedScope.ParsedName); if (apiScope != null) { var scopeVm = CreateScopeViewModel(parsedScope, apiScope, model == null || model.ScopesConsented?.Contains(parsedScope.RawValue) == true); apiScopes.Add(scopeVm); } } if (DeviceOptions.EnableOfflineAccess && request.ValidatedResources.Resources.OfflineAccess) { apiScopes.Add(GetOfflineAccessScope(model == null || model.ScopesConsented?.Contains(Duende.IdentityServer.IdentityServerConstants.StandardScopes.OfflineAccess) == true)); } vm.ApiScopes = apiScopes; return vm; } private ScopeViewModel CreateScopeViewModel(IdentityResource identity, bool check) { return new ScopeViewModel { Value = identity.Name, DisplayName = identity.DisplayName ?? identity.Name, Description = identity.Description, Emphasize = identity.Emphasize, Required = identity.Required, Checked = check || identity.Required }; } public ScopeViewModel CreateScopeViewModel(ParsedScopeValue parsedScopeValue, ApiScope apiScope, bool check) { return new ScopeViewModel { Value = parsedScopeValue.RawValue, // todo: use the parsed scope value in the display? DisplayName = apiScope.DisplayName ?? apiScope.Name, Description = apiScope.Description, Emphasize = apiScope.Emphasize, Required = apiScope.Required, Checked = check || apiScope.Required }; } private ScopeViewModel GetOfflineAccessScope(bool check) { return new ScopeViewModel { Value = Duende.IdentityServer.IdentityServerConstants.StandardScopes.OfflineAccess, DisplayName = DeviceOptions.OfflineAccessDisplayName, Description = DeviceOptions.OfflineAccessDescription, Emphasize = true, Checked = check }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Data.Common; namespace System.Data.OleDb { public sealed partial class OleDbParameter : DbParameter { // V1.2.3300 private object _value; private object _parent; private ParameterDirection _direction; private int _size; private string _sourceColumn; private DataRowVersion _sourceVersion; private bool _sourceColumnNullMapping; private bool _isNullable; private object _coercedValue; private OleDbParameter(OleDbParameter source) : this() { // V1.2.3300, Clone ADP.CheckArgumentNull(source, "source"); source.CloneHelper(this); ICloneable cloneable = (_value as ICloneable); if (null != cloneable) { _value = cloneable.Clone(); } } private object CoercedValue { // V1.2.3300 get { return _coercedValue; } set { _coercedValue = value; } } [RefreshProperties(RefreshProperties.All)] public override ParameterDirection Direction { // V1.2.3300, XXXParameter V1.0.3300 get { ParameterDirection direction = _direction; return ((0 != direction) ? direction : ParameterDirection.Input); } set { if (_direction != value) { switch (value) { // @perfnote: Enum.IsDefined case ParameterDirection.Input: case ParameterDirection.Output: case ParameterDirection.InputOutput: case ParameterDirection.ReturnValue: PropertyChanging(); _direction = value; break; default: throw ADP.InvalidParameterDirection(value); } } } } public override bool IsNullable { // V1.2.3300, XXXParameter V1.0.3300 get { return _isNullable; } set { _isNullable = value; } } internal int Offset { get { return 0; } } public override int Size { // V1.2.3300, XXXParameter V1.0.3300 get { int size = _size; if (0 == size) { size = ValueSize(Value); } return size; } set { if (_size != value) { if (value < -1) { throw ADP.InvalidSizeValue(value); } PropertyChanging(); _size = value; } } } private void ResetSize() { if (0 != _size) { PropertyChanging(); _size = 0; } } private bool ShouldSerializeSize() { // V1.2.3300 return (0 != _size); } public override string SourceColumn { // V1.2.3300, XXXParameter V1.0.3300 get { string sourceColumn = _sourceColumn; return ((null != sourceColumn) ? sourceColumn : string.Empty); } set { _sourceColumn = value; } } public override bool SourceColumnNullMapping { get { return _sourceColumnNullMapping; } set { _sourceColumnNullMapping = value; } } public override DataRowVersion SourceVersion { // V1.2.3300, XXXParameter V1.0.3300 get { DataRowVersion sourceVersion = _sourceVersion; return ((0 != sourceVersion) ? sourceVersion : DataRowVersion.Current); } set { switch (value) { // @perfnote: Enum.IsDefined case DataRowVersion.Original: case DataRowVersion.Current: case DataRowVersion.Proposed: case DataRowVersion.Default: _sourceVersion = value; break; default: throw ADP.InvalidDataRowVersion(value); } } } private void CloneHelperCore(OleDbParameter destination) { destination._value = _value; // NOTE: _parent is not cloned destination._direction = _direction; destination._size = _size; destination._sourceColumn = _sourceColumn; destination._sourceVersion = _sourceVersion; destination._sourceColumnNullMapping = _sourceColumnNullMapping; destination._isNullable = _isNullable; } internal void CopyTo(DbParameter destination) { ADP.CheckArgumentNull(destination, "destination"); CloneHelper((OleDbParameter)destination); } internal object CompareExchangeParent(object value, object comparand) { // the interlock guarantees same parameter won't belong to multiple collections // at the same time, but to actually occur the user must really try // since we never declared thread safety, we don't care at this time //return System.Threading.Interlocked.CompareExchange(ref _parent, value, comparand); object parent = _parent; if (comparand == parent) { _parent = value; } return parent; } internal void ResetParent() { _parent = null; } public override string ToString() { // V1.2.3300, XXXParameter V1.0.3300 return ParameterName; } private byte ValuePrecisionCore(object value) { // V1.2.3300 if (value is decimal) { return ((System.Data.SqlTypes.SqlDecimal)(decimal)value).Precision; } return 0; } private byte ValueScaleCore(object value) { // V1.2.3300 if (value is decimal) { return (byte)((decimal.GetBits((decimal)value)[3] & 0x00ff0000) >> 0x10); } return 0; } private int ValueSizeCore(object value) { // V1.2.3300 if (!ADP.IsNull(value)) { string svalue = (value as string); if (null != svalue) { return svalue.Length; } byte[] bvalue = (value as byte[]); if (null != bvalue) { return bvalue.Length; } char[] cvalue = (value as char[]); if (null != cvalue) { return cvalue.Length; } if ((value is byte) || (value is char)) { return 1; } } return 0; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.CSharp; namespace Microsoft.DotNet.CodeFormatting { [Export(typeof(IFormattingEngine))] internal sealed class FormattingEngineImplementation : IFormattingEngine { /// <summary> /// Developers who want to opt out of the code formatter for items like unicode /// tables can surround them with #if !DOTNET_FORMATTER. /// </summary> internal const string TablePreprocessorSymbolName = "DOTNET_FORMATTER"; private readonly Options _options; private readonly IEnumerable<IFormattingFilter> _filters; private readonly IEnumerable<ISyntaxFormattingRule> _syntaxRules; private readonly IEnumerable<ILocalSemanticFormattingRule> _localSemanticRules; private readonly IEnumerable<IGlobalSemanticFormattingRule> _globalSemanticRules; private readonly Stopwatch _watch = new Stopwatch(); private bool _allowTables; private bool _verbose; public ImmutableArray<string> CopyrightHeader { get { return _options.CopyrightHeader; } set { _options.CopyrightHeader = value; } } public ImmutableArray<string[]> PreprocessorConfigurations { get { return _options.PreprocessorConfigurations; } set { _options.PreprocessorConfigurations = value; } } public ImmutableArray<string> FileNames { get { return _options.FileNames; } set { _options.FileNames = value; } } public IFormatLogger FormatLogger { get { return _options.FormatLogger; } set { _options.FormatLogger = value; } } public bool AllowTables { get { return _allowTables; } set { _allowTables = value; } } public bool Verbose { get { return _verbose; } set { _verbose = value; } } public bool ConvertUnicodeCharacters { get { return _options.ConvertUnicodeCharacters; } set { _options.ConvertUnicodeCharacters = value; } } [ImportingConstructor] internal FormattingEngineImplementation( Options options, [ImportMany] IEnumerable<IFormattingFilter> filters, [ImportMany] IEnumerable<Lazy<ISyntaxFormattingRule, IOrderMetadata>> syntaxRules, [ImportMany] IEnumerable<Lazy<ILocalSemanticFormattingRule, IOrderMetadata>> localSemanticRules, [ImportMany] IEnumerable<Lazy<IGlobalSemanticFormattingRule, IOrderMetadata>> globalSemanticRules) { _options = options; _filters = filters; _syntaxRules = syntaxRules.OrderBy(r => r.Metadata.Order).Select(r => r.Value).ToList(); _localSemanticRules = localSemanticRules.OrderBy(r => r.Metadata.Order).Select(r => r.Value).ToList(); _globalSemanticRules = globalSemanticRules.OrderBy(r => r.Metadata.Order).Select(r => r.Value).ToList(); } public Task FormatSolutionAsync(Solution solution, CancellationToken cancellationToken) { var documentIds = solution.Projects.SelectMany(x => x.DocumentIds).ToList(); return FormatAsync(solution.Workspace, documentIds, cancellationToken); } public Task FormatProjectAsync(Project project, CancellationToken cancellationToken) { return FormatAsync(project.Solution.Workspace, project.DocumentIds, cancellationToken); } private async Task FormatAsync(Workspace workspace, IReadOnlyList<DocumentId> documentIds, CancellationToken cancellationToken) { var watch = new Stopwatch(); watch.Start(); var originalSolution = workspace.CurrentSolution; var solution = await FormatCoreAsync(originalSolution, documentIds, cancellationToken); watch.Stop(); if (!workspace.TryApplyChanges(solution)) { FormatLogger.WriteErrorLine("Unable to save changes to disk"); } FormatLogger.WriteLine("Total time {0}", watch.Elapsed); } private Solution AddTablePreprocessorSymbol(Solution solution) { var projectIds = solution.ProjectIds; foreach (var projectId in projectIds) { var project = solution.GetProject(projectId); var parseOptions = project.ParseOptions as CSharpParseOptions; if (parseOptions != null) { var list = new List<string>(); list.AddRange(parseOptions.PreprocessorSymbolNames); list.Add(TablePreprocessorSymbolName); parseOptions = parseOptions.WithPreprocessorSymbols(list); solution = project.WithParseOptions(parseOptions).Solution; } } return solution; } /// <summary> /// Remove the added table preprocessor symbol. Don't want that saved into the project /// file as a change. /// </summary> private Solution RemoveTablePreprocessorSymbol(Solution newSolution, Solution oldSolution) { var projectIds = newSolution.ProjectIds; foreach (var projectId in projectIds) { var oldProject = oldSolution.GetProject(projectId); var newProject = newSolution.GetProject(projectId); newSolution = newProject.WithParseOptions(oldProject.ParseOptions).Solution; } return newSolution; } internal async Task<Solution> FormatCoreAsync(Solution originalSolution, IReadOnlyList<DocumentId> documentIds, CancellationToken cancellationToken) { var solution = originalSolution; if (_allowTables) { solution = AddTablePreprocessorSymbol(originalSolution); } solution = await RunSyntaxPass(solution, documentIds, cancellationToken); solution = await RunLocalSemanticPass(solution, documentIds, cancellationToken); solution = await RunGlobalSemanticPass(solution, documentIds, cancellationToken); if (_allowTables) { solution = RemoveTablePreprocessorSymbol(solution, originalSolution); } return solution; } private bool ShouldBeProcessed(Document document) { foreach (var filter in _filters) { var shouldBeProcessed = filter.ShouldBeProcessed(document); if (!shouldBeProcessed) return false; } return true; } private Task<SyntaxNode> GetSyntaxRootAndFilter(Document document, CancellationToken cancellationToken) { if (!ShouldBeProcessed(document)) { return Task.FromResult<SyntaxNode>(null); } return document.GetSyntaxRootAsync(cancellationToken); } private Task<SyntaxNode> GetSyntaxRootAndFilter(IFormattingRule formattingRule, Document document, CancellationToken cancellationToken) { if (!formattingRule.SupportsLanguage(document.Project.Language)) { return Task.FromResult<SyntaxNode>(null); } return GetSyntaxRootAndFilter(document, cancellationToken); } private void StartDocument() { _watch.Restart(); } private void EndDocument(Document document) { _watch.Stop(); if (_verbose) { FormatLogger.WriteLine(" {0} {1} seconds", document.Name, _watch.Elapsed.TotalSeconds); } } /// <summary> /// Semantics is not involved in this pass at all. It is just a straight modification of the /// parse tree so there are no issues about ensuring the version of <see cref="SemanticModel"/> and /// the <see cref="SyntaxNode"/> line up. Hence we do this by iteraning every <see cref="Document"/> /// and processing all rules against them at once /// </summary> private async Task<Solution> RunSyntaxPass(Solution originalSolution, IReadOnlyList<DocumentId> documentIds, CancellationToken cancellationToken) { FormatLogger.WriteLine("\tSyntax Pass"); var currentSolution = originalSolution; foreach (var documentId in documentIds) { var document = originalSolution.GetDocument(documentId); var syntaxRoot = await GetSyntaxRootAndFilter(document, cancellationToken); if (syntaxRoot == null) { continue; } StartDocument(); var newRoot = RunSyntaxPass(syntaxRoot, document.Project.Language); EndDocument(document); if (newRoot != syntaxRoot) { currentSolution = currentSolution.WithDocumentSyntaxRoot(document.Id, newRoot); } } return currentSolution; } private SyntaxNode RunSyntaxPass(SyntaxNode root, string languageName) { foreach (var rule in _syntaxRules) { if (rule.SupportsLanguage(languageName)) { root = rule.Process(root, languageName); } } return root; } private async Task<Solution> RunLocalSemanticPass(Solution solution, IReadOnlyList<DocumentId> documentIds, CancellationToken cancellationToken) { FormatLogger.WriteLine("\tLocal Semantic Pass"); foreach (var localSemanticRule in _localSemanticRules) { solution = await RunLocalSemanticPass(solution, documentIds, localSemanticRule, cancellationToken); } return solution; } private async Task<Solution> RunLocalSemanticPass(Solution originalSolution, IReadOnlyList<DocumentId> documentIds, ILocalSemanticFormattingRule localSemanticRule, CancellationToken cancellationToken) { if (_verbose) { FormatLogger.WriteLine(" {0}", localSemanticRule.GetType().Name); } var currentSolution = originalSolution; foreach (var documentId in documentIds) { var document = originalSolution.GetDocument(documentId); var syntaxRoot = await GetSyntaxRootAndFilter(localSemanticRule, document, cancellationToken); if (syntaxRoot == null) { continue; } StartDocument(); var newRoot = await localSemanticRule.ProcessAsync(document, syntaxRoot, cancellationToken); EndDocument(document); if (syntaxRoot != newRoot) { currentSolution = currentSolution.WithDocumentSyntaxRoot(documentId, newRoot); } } return currentSolution; } private async Task<Solution> RunGlobalSemanticPass(Solution solution, IReadOnlyList<DocumentId> documentIds, CancellationToken cancellationToken) { FormatLogger.WriteLine("\tGlobal Semantic Pass"); foreach (var globalSemanticRule in _globalSemanticRules) { solution = await RunGlobalSemanticPass(solution, documentIds, globalSemanticRule, cancellationToken); } return solution; } private async Task<Solution> RunGlobalSemanticPass(Solution solution, IReadOnlyList<DocumentId> documentIds, IGlobalSemanticFormattingRule globalSemanticRule, CancellationToken cancellationToken) { if (_verbose) { FormatLogger.WriteLine(" {0}", globalSemanticRule.GetType().Name); } foreach (var documentId in documentIds) { var document = solution.GetDocument(documentId); var syntaxRoot = await GetSyntaxRootAndFilter(globalSemanticRule, document, cancellationToken); if (syntaxRoot == null) { continue; } StartDocument(); solution = await globalSemanticRule.ProcessAsync(document, syntaxRoot, cancellationToken); EndDocument(document); } return solution; } } }
/***************************************************************************** The MIT License (MIT) Copyright (c) 2014 [email protected] 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. ****************************************************************************** LightInject.Annotation version 1.0.0.4 http://www.lightinject.net/ http://twitter.com/bernhardrichter ******************************************************************************/ [module: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1126:PrefixCallsCorrectly", Justification = "Reviewed")] [module: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1101:PrefixLocalCallsWithThis", Justification = "No inheritance")] [module: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleClass", Justification = "Single source file deployment.")] [module: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1403:FileMayOnlyContainASingleNamespace", Justification = "Extension methods must be visible")] [module: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1633:FileMustHaveHeader", Justification = "Custom header.")] [module: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "All public members are documented.")] namespace Raft.LightInject { using System; using LightInject.Annotation; /// <summary> /// Indicates a required property dependency or a named constructor dependency. /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)] [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] public class InjectAttribute : Attribute { /// <summary> /// Initializes a new instance of the <see cref="InjectAttribute"/> class. /// </summary> public InjectAttribute() : this(string.Empty) { } /// <summary> /// Initializes a new instance of the <see cref="InjectAttribute"/> class. /// </summary> /// <param name="serviceName">The name of the service to be injected.</param> public InjectAttribute(string serviceName) { ServiceName = serviceName; } /// <summary> /// Gets the name of the service to be injected. /// </summary> public string ServiceName { get; private set; } } /// <summary> /// Extends the <see cref="ServiceContainer"/> class with methods for enabling /// annotated property/constructor injection. /// </summary> [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] internal static class AnnotationExtension { /// <summary> /// Enables annotated property injection. /// </summary> /// <param name="serviceContainer">The target <see cref="ServiceContainer"/> /// for which to enable annotated property injection.</param> public static void EnableAnnotatedPropertyInjection(this ServiceContainer serviceContainer) { var propertySelector = new PropertySelector(); serviceContainer.PropertyDependencySelector = new AnnotatedPropertyDependencySelector(propertySelector); } /// <summary> /// Enables annotated constructor injection. /// </summary> /// <param name="serviceContainer">The target <see cref="ServiceContainer"/> /// for which to enable annotated constructor injection.</param> public static void EnableAnnotatedConstructorInjection(this ServiceContainer serviceContainer) { serviceContainer.ConstructorDependencySelector = new AnnotatedConstructorDependencySelector(); serviceContainer.ConstructorSelector = new AnnotatedConstructorSelector(serviceContainer.CanGetInstance); } } } namespace Raft.LightInject.Annotation { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; /// <summary> /// An <see cref="IPropertyDependencySelector"/> that uses the <see cref="InjectAttribute"/> /// to determine which properties to inject dependencies. /// </summary> [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] internal class AnnotatedPropertyDependencySelector : PropertyDependencySelector { /// <summary> /// Initializes a new instance of the <see cref="AnnotatedPropertyDependencySelector"/> class. /// </summary> /// <param name="propertySelector">The <see cref="IPropertySelector"/> that is /// responsible for selecting a list of injectable properties.</param> public AnnotatedPropertyDependencySelector(IPropertySelector propertySelector) : base(propertySelector) { } /// <summary> /// Selects the property dependencies for the given <paramref name="type"/> /// that is annotated with the <see cref="InjectAttribute"/>. /// </summary> /// <param name="type">The <see cref="Type"/> for which to select the property dependencies.</param> /// <returns>A list of <see cref="PropertyDependency"/> instances that represents the property /// dependencies for the given <paramref name="type"/>.</returns> public override IEnumerable<PropertyDependency> Execute(Type type) { var properties = PropertySelector.Execute(type).Where(p => p.IsDefined(typeof(InjectAttribute), true)).ToArray(); foreach (var propertyInfo in properties) { var injectAttribute = (InjectAttribute)propertyInfo.GetCustomAttributes(typeof(InjectAttribute), true).FirstOrDefault(); if (injectAttribute != null) { yield return new PropertyDependency { Property = propertyInfo, ServiceName = injectAttribute.ServiceName, ServiceType = propertyInfo.PropertyType, IsRequired = true }; } } } } /// <summary> /// A <see cref="ConstructorDependencySelector"/> that looks for the <see cref="InjectAttribute"/> /// to determine the name of service to be injected. /// </summary> [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] internal class AnnotatedConstructorDependencySelector : ConstructorDependencySelector { /// <summary> /// Selects the constructor dependencies for the given <paramref name="constructor"/>. /// </summary> /// <param name="constructor">The <see cref="ConstructionInfo"/> for which to select the constructor dependencies.</param> /// <returns>A list of <see cref="ConstructorDependency"/> instances that represents the constructor /// dependencies for the given <paramref name="constructor"/>.</returns> public override IEnumerable<ConstructorDependency> Execute(ConstructorInfo constructor) { var constructorDependencies = base.Execute(constructor).ToArray(); foreach (var constructorDependency in constructorDependencies) { var injectAttribute = (InjectAttribute) constructorDependency.Parameter.GetCustomAttributes(typeof(InjectAttribute), true).FirstOrDefault(); if (injectAttribute != null) { constructorDependency.ServiceName = injectAttribute.ServiceName; } } return constructorDependencies; } } /// <summary> /// A <see cref="IConstructorSelector"/> implementation that uses information /// from the <see cref="InjectAttribute"/> to determine if a given service can be resolved. /// </summary> [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] internal class AnnotatedConstructorSelector : MostResolvableConstructorSelector { /// <summary> /// Initializes a new instance of the <see cref="AnnotatedConstructorSelector"/> class. /// </summary> /// <param name="canGetInstance">A function delegate that determines if a service type can be resolved.</param> public AnnotatedConstructorSelector(Func<Type, string, bool> canGetInstance) : base(canGetInstance) { } /// <summary> /// Gets the service name based on the given <paramref name="parameter"/>. /// </summary> /// <param name="parameter">The <see cref="ParameterInfo"/> for which to get the service name.</param> /// <returns>The name of the service for the given <paramref name="parameter"/>.</returns> protected override string GetServiceName(ParameterInfo parameter) { var injectAttribute = (InjectAttribute) parameter.GetCustomAttributes(typeof(InjectAttribute), true).FirstOrDefault(); return injectAttribute != null ? injectAttribute.ServiceName : base.GetServiceName(parameter); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; /// <summary> /// Convert.ToUInt16(object) /// </summary> public class ConvertToUInt1613 { public static int Main() { ConvertToUInt1613 convertToUInt1613 = new ConvertToUInt1613(); TestLibrary.TestFramework.BeginTestCase("ConvertToUInt1613"); if (convertToUInt1613.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; return retVal; } #region PositiveTest public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1:Convert to UInt16 from object 1"); try { TestClass2 objVal = new TestClass2(); ushort unshortVal = Convert.ToUInt16(objVal); if (unshortVal != UInt16.MaxValue) { TestLibrary.TestFramework.LogError("001", "the ExpectResult 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:Convert to UInt16 from object 2"); try { object objVal = true; ushort unshortVal = Convert.ToUInt16(objVal); if (unshortVal != 1) { TestLibrary.TestFramework.LogError("003", "the ExpectResult 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:Convert to UInt16 from object 3"); try { object objVal = false; ushort unshortVal = Convert.ToUInt16(objVal); if (unshortVal != 0) { TestLibrary.TestFramework.LogError("005", "the ExpectResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4:Convert to UInt16 from object 4"); try { object objVal = null; ushort unshortVal = Convert.ToUInt16(objVal); if (unshortVal != 0) { TestLibrary.TestFramework.LogError("007", "the ExpectResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpect exception:" + e); retVal = false; } return retVal; } #endregion #region NegativeTest public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1:The object does not implement IConvertible"); try { TestClass1 objVal = new TestClass1(); ushort unshortVal = Convert.ToUInt16(objVal); TestLibrary.TestFramework.LogError("N001", "The object does not implement IConvertible but not throw exception"); retVal = false; } catch (InvalidCastException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N002", "Unexpect exception:" + e); retVal = false; } return retVal; } #endregion #region ForTestClass public class TestClass1 { } public class TestClass2 : IConvertible { public TypeCode GetTypeCode() { throw new Exception("The method or operation is not implemented."); } public bool ToBoolean(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public byte ToByte(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public char ToChar(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public DateTime ToDateTime(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public decimal ToDecimal(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public double ToDouble(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public short ToInt16(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public int ToInt32(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public long ToInt64(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public sbyte ToSByte(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public float ToSingle(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public string ToString(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public object ToType(Type conversionType, IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public ushort ToUInt16(IFormatProvider provider) { return UInt16.MaxValue; } public uint ToUInt32(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public ulong ToUInt64(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } } #endregion #region HelpMethod private Int32 GetInt32(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } #endregion }
// // Author: // Jb Evain ([email protected]) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using Mono.Collections.Generic; using Mono.Cecil.Metadata; namespace Mono.Cecil { public sealed class GenericParameter : TypeReference, ICustomAttributeProvider { internal int position; internal GenericParameterType type; internal IGenericParameterProvider owner; ushort attributes; Collection<TypeReference> constraints; Collection<CustomAttribute> custom_attributes; public GenericParameterAttributes Attributes { get { return (GenericParameterAttributes) attributes; } set { attributes = (ushort) value; } } public int Position { get { return position; } } public GenericParameterType Type { get { return type; } } public IGenericParameterProvider Owner { get { return owner; } } public bool HasConstraints { get { if (constraints != null) return constraints.Count > 0; return HasImage && Module.Read (this, (generic_parameter, reader) => reader.HasGenericConstraints (generic_parameter)); } } public Collection<TypeReference> Constraints { get { if (constraints != null) return constraints; if (HasImage) return Module.Read (ref constraints, this, (generic_parameter, reader) => reader.ReadGenericConstraints (generic_parameter)); return constraints = new Collection<TypeReference> (); } } public bool HasCustomAttributes { get { if (custom_attributes != null) return custom_attributes.Count > 0; return this.GetHasCustomAttributes (Module); } } public Collection<CustomAttribute> CustomAttributes { get { return custom_attributes ?? (this.GetCustomAttributes (ref custom_attributes, Module)); } } public override IMetadataScope Scope { get { if (owner == null) return null; return owner.GenericParameterType == GenericParameterType.Method ? ((MethodReference) owner).DeclaringType.Scope : ((TypeReference) owner).Scope; } set { throw new InvalidOperationException (); } } public override TypeReference DeclaringType { get { return owner as TypeReference; } set { throw new InvalidOperationException (); } } public MethodReference DeclaringMethod { get { return owner as MethodReference; } } public override ModuleDefinition Module { get { return module ?? owner.Module; } } public override string Name { get { if (!string.IsNullOrEmpty (base.Name)) return base.Name; return base.Name = (type == GenericParameterType.Method ? "!!" : "!") + position; } } public override string Namespace { get { return string.Empty; } set { throw new InvalidOperationException (); } } public override string FullName { get { return Name; } } public override bool IsGenericParameter { get { return true; } } public override bool ContainsGenericParameter { get { return true; } } public override MetadataType MetadataType { get { return (MetadataType) etype; } } #region GenericParameterAttributes public bool IsNonVariant { get { return attributes.GetMaskedAttributes ((ushort) GenericParameterAttributes.VarianceMask, (ushort) GenericParameterAttributes.NonVariant); } set { attributes = attributes.SetMaskedAttributes ((ushort) GenericParameterAttributes.VarianceMask, (ushort) GenericParameterAttributes.NonVariant, value); } } public bool IsCovariant { get { return attributes.GetMaskedAttributes ((ushort) GenericParameterAttributes.VarianceMask, (ushort) GenericParameterAttributes.Covariant); } set { attributes = attributes.SetMaskedAttributes ((ushort) GenericParameterAttributes.VarianceMask, (ushort) GenericParameterAttributes.Covariant, value); } } public bool IsContravariant { get { return attributes.GetMaskedAttributes ((ushort) GenericParameterAttributes.VarianceMask, (ushort) GenericParameterAttributes.Contravariant); } set { attributes = attributes.SetMaskedAttributes ((ushort) GenericParameterAttributes.VarianceMask, (ushort) GenericParameterAttributes.Contravariant, value); } } public bool HasReferenceTypeConstraint { get { return attributes.GetAttributes ((ushort) GenericParameterAttributes.ReferenceTypeConstraint); } set { attributes = attributes.SetAttributes ((ushort) GenericParameterAttributes.ReferenceTypeConstraint, value); } } public bool HasNotNullableValueTypeConstraint { get { return attributes.GetAttributes ((ushort) GenericParameterAttributes.NotNullableValueTypeConstraint); } set { attributes = attributes.SetAttributes ((ushort) GenericParameterAttributes.NotNullableValueTypeConstraint, value); } } public bool HasDefaultConstructorConstraint { get { return attributes.GetAttributes ((ushort) GenericParameterAttributes.DefaultConstructorConstraint); } set { attributes = attributes.SetAttributes ((ushort) GenericParameterAttributes.DefaultConstructorConstraint, value); } } #endregion public GenericParameter (IGenericParameterProvider owner) : this (string.Empty, owner) { } public GenericParameter (string name, IGenericParameterProvider owner) : base (string.Empty, name) { if (owner == null) throw new ArgumentNullException (); this.position = -1; this.owner = owner; this.type = owner.GenericParameterType; this.etype = ConvertGenericParameterType (this.type); this.token = new MetadataToken (TokenType.GenericParam); } internal GenericParameter (int position, GenericParameterType type, ModuleDefinition module) : base (string.Empty, string.Empty) { Mixin.CheckModule (module); this.position = position; this.type = type; this.etype = ConvertGenericParameterType (type); this.module = module; this.token = new MetadataToken (TokenType.GenericParam); } static ElementType ConvertGenericParameterType (GenericParameterType type) { switch (type) { case GenericParameterType.Type: return ElementType.Var; case GenericParameterType.Method: return ElementType.MVar; } throw new ArgumentOutOfRangeException (); } public override TypeDefinition Resolve () { return null; } } sealed class GenericParameterCollection : Collection<GenericParameter> { readonly IGenericParameterProvider owner; internal GenericParameterCollection (IGenericParameterProvider owner) { this.owner = owner; } internal GenericParameterCollection (IGenericParameterProvider owner, int capacity) : base (capacity) { this.owner = owner; } protected override void OnAdd (GenericParameter item, int index) { UpdateGenericParameter (item, index); } protected override void OnInsert (GenericParameter item, int index) { UpdateGenericParameter (item, index); for (int i = index; i < size; i++) items[i].position = i + 1; } protected override void OnSet (GenericParameter item, int index) { UpdateGenericParameter (item, index); } void UpdateGenericParameter (GenericParameter item, int index) { item.owner = owner; item.position = index; item.type = owner.GenericParameterType; } protected override void OnRemove (GenericParameter item, int index) { item.owner = null; item.position = -1; item.type = GenericParameterType.Type; for (int i = index + 1; i < size; i++) items[i].position = i - 1; } } }
using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace Orleans.Runtime.Messaging { internal class MessageCenter : IMessageCenter, IDisposable { private readonly ISiloStatusOracle siloStatusOracle; private readonly MessageFactory messageFactory; private readonly ConnectionManager connectionManager; private readonly MessagingTrace messagingTrace; private readonly SiloAddress _siloAddress; private readonly ILogger log; private Dispatcher dispatcher; private bool stopped; private HostedClient hostedClient; private Action<Message> sniffIncomingMessageHandler; public MessageCenter( ILocalSiloDetails siloDetails, MessageFactory messageFactory, Factory<MessageCenter, Gateway> gatewayFactory, ILogger<MessageCenter> logger, ISiloStatusOracle siloStatusOracle, ConnectionManager senderManager, MessagingTrace messagingTrace) { this.siloStatusOracle = siloStatusOracle; this.connectionManager = senderManager; this.messagingTrace = messagingTrace; this.log = logger; this.messageFactory = messageFactory; this._siloAddress = siloDetails.SiloAddress; if (siloDetails.GatewayAddress != null) { Gateway = gatewayFactory(this); Gateway.Start(); } } public Gateway Gateway { get; } internal Dispatcher Dispatcher { get { return this.dispatcher ?? ThrowNullReferenceException(); [MethodImpl(MethodImplOptions.NoInlining)] static Dispatcher ThrowNullReferenceException() => throw new NullReferenceException("MessageCenter.Dispatcher is null"); } set => dispatcher = value; } internal bool IsBlockingApplicationMessages { get; private set; } public void SetHostedClient(HostedClient client) => this.hostedClient = client; public bool TryDeliverToProxy(Message msg) { if (!msg.TargetGrain.IsClient()) return false; if (this.Gateway is Gateway gateway && gateway.TryDeliverToProxy(msg)) return true; return this.hostedClient is HostedClient client && client.TryDispatchToClient(msg); } public void Start() { } public void Stop() { BlockApplicationMessages(); StopAcceptingClientMessages(); stopped = true; } /// <summary> /// Indicates that application messages should be blocked from being sent or received. /// This method is used by the "fast stop" process. /// <para> /// Specifically, all outbound application messages are dropped, except for rejections and messages to the membership table grain. /// Inbound application requests are rejected, and other inbound application messages are dropped. /// </para> /// </summary> public void BlockApplicationMessages() { if (log.IsEnabled(LogLevel.Debug)) { log.LogDebug("BlockApplicationMessages"); } IsBlockingApplicationMessages = true; } public void StopAcceptingClientMessages() { if (log.IsEnabled(LogLevel.Debug)) { log.LogDebug("StopClientMessages"); } try { Gateway?.Stop(); } catch (Exception exc) { log.LogError((int)ErrorCode.Runtime_Error_100109, exc, "Stop failed"); } } public void DispatchLocalMessage(Message message) => this.Dispatcher.ReceiveMessage(message); public void RerouteMessage(Message message) => this.Dispatcher.RerouteMessage(message); public Action<Message> SniffIncomingMessage { set { if (this.sniffIncomingMessageHandler != null) { throw new InvalidOperationException("MessageCenter.SniffIncomingMessage already set"); } this.sniffIncomingMessageHandler = value; } get => this.sniffIncomingMessageHandler; } public void SendMessage(Message msg) { // Note that if we identify or add other grains that are required for proper stopping, we will need to treat them as we do the membership table grain here. if (IsBlockingApplicationMessages && (msg.Category == Message.Categories.Application) && (msg.Result != Message.ResponseTypes.Rejection) && !Constants.SystemMembershipTableType.Equals(msg.TargetGrain)) { // Drop the message on the floor if it's an application message that isn't a rejection this.messagingTrace.OnDropBlockedApplicationMessage(msg); } else { msg.SendingSilo ??= _siloAddress; if (stopped) { log.LogInformation((int)ErrorCode.Runtime_Error_100115, "Message was queued for sending after outbound queue was stopped: {Message}", msg); SendRejection(msg, Message.RejectionTypes.Unrecoverable, "Message was queued for sending after outbound queue was stopped"); return; } // Don't process messages that have already timed out if (msg.IsExpired) { this.messagingTrace.OnDropExpiredMessage(msg, MessagingStatisticsGroup.Phase.Send); return; } // First check to see if it's really destined for a proxied client, instead of a local grain. if (TryDeliverToProxy(msg)) { // Message was successfully delivered to the proxy. return; } if (msg.TargetSilo is not { } targetSilo) { log.LogError((int)ErrorCode.Runtime_Error_100113, "Message does not have a target silo: " + msg + " -- Call stack is: " + Utils.GetStackTrace()); SendRejection(msg, Message.RejectionTypes.Unrecoverable, "Message to be sent does not have a target silo"); return; } messagingTrace.OnSendMessage(msg); if (targetSilo.Matches(_siloAddress)) { if (log.IsEnabled(LogLevel.Trace)) { log.LogTrace("Message has been looped back to this silo: {Message}", msg); } MessagingStatisticsGroup.LocalMessagesSent.Increment(); this.DispatchLocalMessage(msg); } else { if (stopped) { log.LogInformation((int)ErrorCode.Runtime_Error_100115, "Message was queued for sending after outbound queue was stopped: {Message}", msg); SendRejection(msg, Message.RejectionTypes.Unrecoverable, "Message was queued for sending after outbound queue was stopped"); return; } if (this.connectionManager.TryGetConnection(targetSilo, out var existingConnection)) { existingConnection.Send(msg); return; } else if (this.siloStatusOracle.IsDeadSilo(targetSilo)) { // Do not try to establish this.messagingTrace.OnRejectSendMessageToDeadSilo(_siloAddress, msg); this.SendRejection(msg, Message.RejectionTypes.Transient, "Target silo is known to be dead"); return; } else { var connectionTask = this.connectionManager.GetConnection(targetSilo); if (connectionTask.IsCompletedSuccessfully) { var sender = connectionTask.Result; sender.Send(msg); } else { _ = SendAsync(this, connectionTask, msg); static async Task SendAsync(MessageCenter messageCenter, ValueTask<Connection> connectionTask, Message msg) { try { var sender = await connectionTask; sender.Send(msg); } catch (Exception exception) { messageCenter.SendRejection(msg, Message.RejectionTypes.Transient, $"Exception while sending message: {exception}"); } } } } } } } internal void SendRejection(Message msg, Message.RejectionTypes rejectionType, string reason) { MessagingStatisticsGroup.OnRejectedMessage(msg); if (msg.Direction == Message.Directions.Response && msg.Result == Message.ResponseTypes.Rejection) { // Do not send reject a rejection locally, it will create a stack overflow MessagingStatisticsGroup.OnDroppedSentMessage(msg); if (this.log.IsEnabled(LogLevel.Debug)) log.Debug("Dropping rejection {msg}", msg); } else { if (string.IsNullOrEmpty(reason)) reason = $"Rejection from silo {this._siloAddress} - Unknown reason."; var error = this.messageFactory.CreateRejectionResponse(msg, rejectionType, reason); // rejection msgs are always originated in the local silo, they are never remote. this.DispatchLocalMessage(error); } } public void Dispose() { Stop(); } } }
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://github.com/jskeet/dotnet-protobufs/ // Original C++/Java/Python code: // http://code.google.com/p/protobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using Google.ProtocolBuffers.Descriptors; namespace Google.ProtocolBuffers { /// <summary> /// Provides ASCII text formatting support for messages. /// TODO(jonskeet): Support for alternative line endings. /// (Easy to print, via TextGenerator. Not sure about parsing.) /// </summary> public static class TextFormat { /// <summary> /// Outputs a textual representation of the Protocol Message supplied into /// the parameter output. /// </summary> public static void Print(IMessage message, TextWriter output) { TextGenerator generator = new TextGenerator(output, "\n"); Print(message, generator); } /// <summary> /// Outputs a textual representation of the Protocol Message builder supplied into /// the parameter output. /// </summary> public static void Print(IBuilder builder, TextWriter output) { TextGenerator generator = new TextGenerator(output, "\n"); Print(builder, generator); } /// <summary> /// Outputs a textual representation of <paramref name="fields" /> to <paramref name="output"/>. /// </summary> public static void Print(UnknownFieldSet fields, TextWriter output) { TextGenerator generator = new TextGenerator(output, "\n"); PrintUnknownFields(fields, generator); } public static string PrintToString(IMessage message) { StringWriter text = new StringWriter(); Print(message, text); return text.ToString(); } public static string PrintToString(IBuilder builder) { StringWriter text = new StringWriter(); Print(builder, text); return text.ToString(); } public static string PrintToString(UnknownFieldSet fields) { StringWriter text = new StringWriter(); Print(fields, text); return text.ToString(); } private static void Print(IMessage message, TextGenerator generator) { foreach (KeyValuePair<FieldDescriptor, object> entry in message.AllFields) { PrintField(entry.Key, entry.Value, generator); } PrintUnknownFields(message.UnknownFields, generator); } private static void Print(IBuilder message, TextGenerator generator) { foreach (KeyValuePair<FieldDescriptor, object> entry in message.AllFields) { PrintField(entry.Key, entry.Value, generator); } PrintUnknownFields(message.UnknownFields, generator); } internal static void PrintField(FieldDescriptor field, object value, TextGenerator generator) { if (field.IsRepeated) { // Repeated field. Print each element. foreach (object element in (IEnumerable) value) { PrintSingleField(field, element, generator); } } else { PrintSingleField(field, value, generator); } } private static void PrintSingleField(FieldDescriptor field, Object value, TextGenerator generator) { if (field.IsExtension) { generator.Print("["); // We special-case MessageSet elements for compatibility with proto1. if (field.ContainingType.Options.MessageSetWireFormat && field.FieldType == FieldType.Message && field.IsOptional // object equality (TODO(jonskeet): Work out what this comment means!) && field.ExtensionScope == field.MessageType) { generator.Print(field.MessageType.FullName); } else { generator.Print(field.FullName); } generator.Print("]"); } else { if (field.FieldType == FieldType.Group) { // Groups must be serialized with their original capitalization. generator.Print(field.MessageType.Name); } else { generator.Print(field.Name); } } if (field.MappedType == MappedType.Message) { generator.Print(" {\n"); generator.Indent(); } else { generator.Print(": "); } PrintFieldValue(field, value, generator); if (field.MappedType == MappedType.Message) { generator.Outdent(); generator.Print("}"); } generator.Print("\n"); } private static void PrintFieldValue(FieldDescriptor field, object value, TextGenerator generator) { switch (field.FieldType) { // The Float and Double types must specify the "r" format to preserve their precision, otherwise, // the double to/from string will trim the precision to 6 places. As with other numeric formats // below, always use the invariant culture so it's predictable. case FieldType.Float: generator.Print(((float)value).ToString("r", FrameworkPortability.InvariantCulture)); break; case FieldType.Double: generator.Print(((double)value).ToString("r", FrameworkPortability.InvariantCulture)); break; case FieldType.Int32: case FieldType.Int64: case FieldType.SInt32: case FieldType.SInt64: case FieldType.SFixed32: case FieldType.SFixed64: case FieldType.UInt32: case FieldType.UInt64: case FieldType.Fixed32: case FieldType.Fixed64: // The simple Object.ToString converts using the current culture. // We want to always use the invariant culture so it's predictable. generator.Print(((IConvertible)value).ToString(FrameworkPortability.InvariantCulture)); break; case FieldType.Bool: // Explicitly use the Java true/false generator.Print((bool) value ? "true" : "false"); break; case FieldType.String: generator.Print("\""); generator.Print(EscapeText((string) value)); generator.Print("\""); break; case FieldType.Bytes: { generator.Print("\""); generator.Print(EscapeBytes((ByteString) value)); generator.Print("\""); break; } case FieldType.Enum: { if (value is IEnumLite && !(value is EnumValueDescriptor)) { throw new NotSupportedException("Lite enumerations are not supported."); } generator.Print(((EnumValueDescriptor) value).Name); break; } case FieldType.Message: case FieldType.Group: if (value is IMessageLite && !(value is IMessage)) { throw new NotSupportedException("Lite messages are not supported."); } Print((IMessage) value, generator); break; } } private static void PrintUnknownFields(UnknownFieldSet unknownFields, TextGenerator generator) { foreach (KeyValuePair<int, UnknownField> entry in unknownFields.FieldDictionary) { String prefix = entry.Key.ToString() + ": "; UnknownField field = entry.Value; foreach (ulong value in field.VarintList) { generator.Print(prefix); generator.Print(value.ToString()); generator.Print("\n"); } foreach (uint value in field.Fixed32List) { generator.Print(prefix); generator.Print(string.Format("0x{0:x8}", value)); generator.Print("\n"); } foreach (ulong value in field.Fixed64List) { generator.Print(prefix); generator.Print(string.Format("0x{0:x16}", value)); generator.Print("\n"); } foreach (ByteString value in field.LengthDelimitedList) { generator.Print(entry.Key.ToString()); generator.Print(": \""); generator.Print(EscapeBytes(value)); generator.Print("\"\n"); } foreach (UnknownFieldSet value in field.GroupList) { generator.Print(entry.Key.ToString()); generator.Print(" {\n"); generator.Indent(); PrintUnknownFields(value, generator); generator.Outdent(); generator.Print("}\n"); } } } [CLSCompliant(false)] public static ulong ParseUInt64(string text) { return (ulong) ParseInteger(text, false, true); } public static long ParseInt64(string text) { return ParseInteger(text, true, true); } [CLSCompliant(false)] public static uint ParseUInt32(string text) { return (uint) ParseInteger(text, false, false); } public static int ParseInt32(string text) { return (int) ParseInteger(text, true, false); } public static float ParseFloat(string text) { switch (text) { case "-inf": case "-infinity": case "-inff": case "-infinityf": return float.NegativeInfinity; case "inf": case "infinity": case "inff": case "infinityf": return float.PositiveInfinity; case "nan": case "nanf": return float.NaN; default: return float.Parse(text, FrameworkPortability.InvariantCulture); } } public static double ParseDouble(string text) { switch (text) { case "-inf": case "-infinity": return double.NegativeInfinity; case "inf": case "infinity": return double.PositiveInfinity; case "nan": return double.NaN; default: return double.Parse(text, FrameworkPortability.InvariantCulture); } } /// <summary> /// Parses an integer in hex (leading 0x), decimal (no prefix) or octal (leading 0). /// Only a negative sign is permitted, and it must come before the radix indicator. /// </summary> private static long ParseInteger(string text, bool isSigned, bool isLong) { string original = text; bool negative = false; if (text.StartsWith("-")) { if (!isSigned) { throw new FormatException("Number must be positive: " + original); } negative = true; text = text.Substring(1); } int radix = 10; if (text.StartsWith("0x")) { radix = 16; text = text.Substring(2); } else if (text.StartsWith("0")) { radix = 8; } ulong result; try { // Workaround for https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=278448 // We should be able to use Convert.ToUInt64 for all cases. result = radix == 10 ? ulong.Parse(text) : Convert.ToUInt64(text, radix); } catch (OverflowException) { // Convert OverflowException to FormatException so there's a single exception type this method can throw. string numberDescription = string.Format("{0}-bit {1}signed integer", isLong ? 64 : 32, isSigned ? "" : "un"); throw new FormatException("Number out of range for " + numberDescription + ": " + original); } if (negative) { ulong max = isLong ? 0x8000000000000000UL : 0x80000000L; if (result > max) { string numberDescription = string.Format("{0}-bit signed integer", isLong ? 64 : 32); throw new FormatException("Number out of range for " + numberDescription + ": " + original); } return -((long) result); } else { ulong max = isSigned ? (isLong ? (ulong) long.MaxValue : int.MaxValue) : (isLong ? ulong.MaxValue : uint.MaxValue); if (result > max) { string numberDescription = string.Format("{0}-bit {1}signed integer", isLong ? 64 : 32, isSigned ? "" : "un"); throw new FormatException("Number out of range for " + numberDescription + ": " + original); } return (long) result; } } /// <summary> /// Tests a character to see if it's an octal digit. /// </summary> private static bool IsOctal(char c) { return '0' <= c && c <= '7'; } /// <summary> /// Tests a character to see if it's a hex digit. /// </summary> private static bool IsHex(char c) { return ('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F'); } /// <summary> /// Interprets a character as a digit (in any base up to 36) and returns the /// numeric value. /// </summary> private static int ParseDigit(char c) { if ('0' <= c && c <= '9') { return c - '0'; } else if ('a' <= c && c <= 'z') { return c - 'a' + 10; } else { return c - 'A' + 10; } } /// <summary> /// Unescapes a text string as escaped using <see cref="EscapeText(string)" />. /// Two-digit hex escapes (starting with "\x" are also recognised. /// </summary> public static string UnescapeText(string input) { return UnescapeBytes(input).ToStringUtf8(); } /// <summary> /// Like <see cref="EscapeBytes" /> but escapes a text string. /// The string is first encoded as UTF-8, then each byte escaped individually. /// The returned value is guaranteed to be entirely ASCII. /// </summary> public static string EscapeText(string input) { return EscapeBytes(ByteString.CopyFromUtf8(input)); } /// <summary> /// Escapes bytes in the format used in protocol buffer text format, which /// is the same as the format used for C string literals. All bytes /// that are not printable 7-bit ASCII characters are escaped, as well as /// backslash, single-quote, and double-quote characters. Characters for /// which no defined short-hand escape sequence is defined will be escaped /// using 3-digit octal sequences. /// The returned value is guaranteed to be entirely ASCII. /// </summary> public static String EscapeBytes(ByteString input) { StringBuilder builder = new StringBuilder(input.Length); foreach (byte b in input) { switch (b) { // C# does not use \a or \v case 0x07: builder.Append("\\a"); break; case (byte) '\b': builder.Append("\\b"); break; case (byte) '\f': builder.Append("\\f"); break; case (byte) '\n': builder.Append("\\n"); break; case (byte) '\r': builder.Append("\\r"); break; case (byte) '\t': builder.Append("\\t"); break; case 0x0b: builder.Append("\\v"); break; case (byte) '\\': builder.Append("\\\\"); break; case (byte) '\'': builder.Append("\\\'"); break; case (byte) '"': builder.Append("\\\""); break; default: if (b >= 0x20 && b < 128) { builder.Append((char) b); } else { builder.Append('\\'); builder.Append((char) ('0' + ((b >> 6) & 3))); builder.Append((char) ('0' + ((b >> 3) & 7))); builder.Append((char) ('0' + (b & 7))); } break; } } return builder.ToString(); } /// <summary> /// Performs string unescaping from C style (octal, hex, form feeds, tab etc) into a byte string. /// </summary> public static ByteString UnescapeBytes(string input) { byte[] result = new byte[input.Length]; int pos = 0; for (int i = 0; i < input.Length; i++) { char c = input[i]; if (c > 127 || c < 32) { throw new FormatException("Escaped string must only contain ASCII"); } if (c != '\\') { result[pos++] = (byte) c; continue; } if (i + 1 >= input.Length) { throw new FormatException("Invalid escape sequence: '\\' at end of string."); } i++; c = input[i]; if (c >= '0' && c <= '7') { // Octal escape. int code = ParseDigit(c); if (i + 1 < input.Length && IsOctal(input[i + 1])) { i++; code = code*8 + ParseDigit(input[i]); } if (i + 1 < input.Length && IsOctal(input[i + 1])) { i++; code = code*8 + ParseDigit(input[i]); } result[pos++] = (byte) code; } else { switch (c) { case 'a': result[pos++] = 0x07; break; case 'b': result[pos++] = (byte) '\b'; break; case 'f': result[pos++] = (byte) '\f'; break; case 'n': result[pos++] = (byte) '\n'; break; case 'r': result[pos++] = (byte) '\r'; break; case 't': result[pos++] = (byte) '\t'; break; case 'v': result[pos++] = 0x0b; break; case '\\': result[pos++] = (byte) '\\'; break; case '\'': result[pos++] = (byte) '\''; break; case '"': result[pos++] = (byte) '\"'; break; case 'x': // hex escape int code; if (i + 1 < input.Length && IsHex(input[i + 1])) { i++; code = ParseDigit(input[i]); } else { throw new FormatException("Invalid escape sequence: '\\x' with no digits"); } if (i + 1 < input.Length && IsHex(input[i + 1])) { ++i; code = code*16 + ParseDigit(input[i]); } result[pos++] = (byte) code; break; default: throw new FormatException("Invalid escape sequence: '\\" + c + "'"); } } } return ByteString.CopyFrom(result, 0, pos); } public static void Merge(string text, IBuilder builder) { Merge(text, ExtensionRegistry.Empty, builder); } public static void Merge(TextReader reader, IBuilder builder) { Merge(reader, ExtensionRegistry.Empty, builder); } public static void Merge(TextReader reader, ExtensionRegistry registry, IBuilder builder) { Merge(reader.ReadToEnd(), registry, builder); } public static void Merge(string text, ExtensionRegistry registry, IBuilder builder) { TextTokenizer tokenizer = new TextTokenizer(text); while (!tokenizer.AtEnd) { MergeField(tokenizer, registry, builder); } } /// <summary> /// Parses a single field from the specified tokenizer and merges it into /// the builder. /// </summary> private static void MergeField(TextTokenizer tokenizer, ExtensionRegistry extensionRegistry, IBuilder builder) { FieldDescriptor field; MessageDescriptor type = builder.DescriptorForType; ExtensionInfo extension = null; if (tokenizer.TryConsume("[")) { // An extension. StringBuilder name = new StringBuilder(tokenizer.ConsumeIdentifier()); while (tokenizer.TryConsume(".")) { name.Append("."); name.Append(tokenizer.ConsumeIdentifier()); } extension = extensionRegistry.FindByName(type, name.ToString()); if (extension == null) { throw tokenizer.CreateFormatExceptionPreviousToken("Extension \"" + name + "\" not found in the ExtensionRegistry."); } else if (extension.Descriptor.ContainingType != type) { throw tokenizer.CreateFormatExceptionPreviousToken("Extension \"" + name + "\" does not extend message type \"" + type.FullName + "\"."); } tokenizer.Consume("]"); field = extension.Descriptor; } else { String name = tokenizer.ConsumeIdentifier(); field = type.FindDescriptor<FieldDescriptor>(name); // Group names are expected to be capitalized as they appear in the // .proto file, which actually matches their type names, not their field // names. if (field == null) { // Explicitly specify the invariant culture so that this code does not break when // executing in Turkey. #if PORTABLE_LIBRARY String lowerName = name.ToLowerInvariant(); #else String lowerName = name.ToLower(FrameworkPortability.InvariantCulture); #endif field = type.FindDescriptor<FieldDescriptor>(lowerName); // If the case-insensitive match worked but the field is NOT a group, // TODO(jonskeet): What? Java comment ends here! if (field != null && field.FieldType != FieldType.Group) { field = null; } } // Again, special-case group names as described above. if (field != null && field.FieldType == FieldType.Group && field.MessageType.Name != name) { field = null; } if (field == null) { throw tokenizer.CreateFormatExceptionPreviousToken( "Message type \"" + type.FullName + "\" has no field named \"" + name + "\"."); } } object value = null; if (field.MappedType == MappedType.Message) { tokenizer.TryConsume(":"); // optional String endToken; if (tokenizer.TryConsume("<")) { endToken = ">"; } else { tokenizer.Consume("{"); endToken = "}"; } IBuilder subBuilder; if (extension == null) { subBuilder = builder.CreateBuilderForField(field); } else { subBuilder = extension.DefaultInstance.WeakCreateBuilderForType() as IBuilder; if (subBuilder == null) { throw new NotSupportedException("Lite messages are not supported."); } } while (!tokenizer.TryConsume(endToken)) { if (tokenizer.AtEnd) { throw tokenizer.CreateFormatException("Expected \"" + endToken + "\"."); } MergeField(tokenizer, extensionRegistry, subBuilder); } value = subBuilder.WeakBuild(); } else { tokenizer.Consume(":"); switch (field.FieldType) { case FieldType.Int32: case FieldType.SInt32: case FieldType.SFixed32: value = tokenizer.ConsumeInt32(); break; case FieldType.Int64: case FieldType.SInt64: case FieldType.SFixed64: value = tokenizer.ConsumeInt64(); break; case FieldType.UInt32: case FieldType.Fixed32: value = tokenizer.ConsumeUInt32(); break; case FieldType.UInt64: case FieldType.Fixed64: value = tokenizer.ConsumeUInt64(); break; case FieldType.Float: value = tokenizer.ConsumeFloat(); break; case FieldType.Double: value = tokenizer.ConsumeDouble(); break; case FieldType.Bool: value = tokenizer.ConsumeBoolean(); break; case FieldType.String: value = tokenizer.ConsumeString(); break; case FieldType.Bytes: value = tokenizer.ConsumeByteString(); break; case FieldType.Enum: { EnumDescriptor enumType = field.EnumType; if (tokenizer.LookingAtInteger()) { int number = tokenizer.ConsumeInt32(); value = enumType.FindValueByNumber(number); if (value == null) { throw tokenizer.CreateFormatExceptionPreviousToken( "Enum type \"" + enumType.FullName + "\" has no value with number " + number + "."); } } else { String id = tokenizer.ConsumeIdentifier(); value = enumType.FindValueByName(id); if (value == null) { throw tokenizer.CreateFormatExceptionPreviousToken( "Enum type \"" + enumType.FullName + "\" has no value named \"" + id + "\"."); } } break; } case FieldType.Message: case FieldType.Group: throw new InvalidOperationException("Can't get here."); } } if (field.IsRepeated) { builder.WeakAddRepeatedField(field, value); } else { builder.SetField(field, value); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsHttp { using Microsoft.Rest; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// MultipleResponses operations. /// </summary> public partial interface IMultipleResponses { /// <summary> /// Send a 200 response with valid payload: {'statusCode': '200'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<HttpOperationResponse<A>> Get200Model204NoModelDefaultError200ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 204 response with no payload /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<HttpOperationResponse<A>> Get200Model204NoModelDefaultError204ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 201 response with valid payload: {'statusCode': '201'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<HttpOperationResponse<A>> Get200Model204NoModelDefaultError201InvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 202 response with no payload: /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<HttpOperationResponse<A>> Get200Model204NoModelDefaultError202NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with valid error payload: {'status': 400, /// 'message': 'client error'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<HttpOperationResponse<A>> Get200Model204NoModelDefaultError400ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with valid payload: {'statusCode': '200'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<HttpOperationResponse<A>> Get200Model201ModelDefaultError200ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 201 response with valid payload: {'statusCode': '201', /// 'textStatusCode': 'Created'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<HttpOperationResponse<A>> Get200Model201ModelDefaultError201ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with valid payload: {'code': '400', 'message': /// 'client error'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<HttpOperationResponse<A>> Get200Model201ModelDefaultError400ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with valid payload: {'statusCode': '200'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<HttpOperationResponse<object>> Get200ModelA201ModelC404ModelDDefaultError200ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with valid payload: {'httpCode': '201'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<HttpOperationResponse<object>> Get200ModelA201ModelC404ModelDDefaultError201ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with valid payload: {'httpStatusCode': '404'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<HttpOperationResponse<object>> Get200ModelA201ModelC404ModelDDefaultError404ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with valid payload: {'code': '400', 'message': /// 'client error'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<HttpOperationResponse<object>> Get200ModelA201ModelC404ModelDDefaultError400ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 202 response with no payload /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse> Get202None204NoneDefaultError202NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 204 response with no payload /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse> Get202None204NoneDefaultError204NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with valid payload: {'code': '400', 'message': /// 'client error'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse> Get202None204NoneDefaultError400ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 202 response with an unexpected payload {'property': /// 'value'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse> Get202None204NoneDefaultNone202InvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 204 response with no payload /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse> Get202None204NoneDefaultNone204NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with no payload /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse> Get202None204NoneDefaultNone400NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with an unexpected payload {'property': /// 'value'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse> Get202None204NoneDefaultNone400InvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with valid payload: {'statusCode': '200'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="MyException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse<A>> GetDefaultModelA200ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with no payload /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="MyException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse<A>> GetDefaultModelA200NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with valid payload: {'statusCode': '400'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="MyException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse<A>> GetDefaultModelA400ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with no payload /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="MyException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse<A>> GetDefaultModelA400NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with invalid payload: {'statusCode': '200'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse> GetDefaultNone200InvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with no payload /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse> GetDefaultNone200NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with valid payload: {'statusCode': '400'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse> GetDefaultNone400InvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with no payload /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse> GetDefaultNone400NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with no payload, when a payload is expected - /// client should return a null object of thde type for model A /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<HttpOperationResponse<A>> Get200ModelA200NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with payload {'statusCode': '200'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<HttpOperationResponse<A>> Get200ModelA200ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with invalid payload {'statusCodeInvalid': /// '200'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<HttpOperationResponse<A>> Get200ModelA200InvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with no payload client should treat as an http /// error with no error model /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<HttpOperationResponse<A>> Get200ModelA400NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with payload {'statusCode': '400'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<HttpOperationResponse<A>> Get200ModelA400ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with invalid payload {'statusCodeInvalid': /// '400'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<HttpOperationResponse<A>> Get200ModelA400InvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 202 response with payload {'statusCode': '202'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<HttpOperationResponse<A>> Get200ModelA202ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
using System; using System.Collections.Generic; using System.Text; namespace ICSimulator { public class Router_Bridge : Router { int bufferDepth_G2L = Config.G2LBufferDepth; int bufferDepth_L2G = Config.L2GBufferDepth; Queue<Flit>[] Q_G2L; Queue<Flit>[] Q_L2G; int Local = 0; int Global = 1; public int GWidth; public int LWidth; int localRR; int globalRR; Flit [] local_observer; Flit [] global_observer; int [] local_obCounter; int [] global_obCounter; int [] local_loopCounter; int [] global_loopCounter; Flit [] local_preserve; Flit [] global_preserve; int local_loopCycle = -1; int global_loopCycle = -1; int [] local_starveCounter; int [] global_starveCounter; public Router_Bridge(int ID, int GlobalRingWidth, int LocalRingWidth = 1, int L2GBufferDepth = -1, int G2LBufferDepth = -1) : base() { if (GlobalRingWidth == 4) RouterType = 2; else if (GlobalRingWidth == 2) RouterType = 1; enable = true; m_n = null; coord.ID = ID; if (L2GBufferDepth != -1) bufferDepth_L2G = L2GBufferDepth; if (G2LBufferDepth != -1) bufferDepth_G2L = G2LBufferDepth; LLinkIn = new Link[LocalRingWidth * 2]; LLinkOut = new Link[LocalRingWidth * 2]; GLinkIn = new Link[2 * GlobalRingWidth]; GLinkOut = new Link[2 * GlobalRingWidth]; Q_G2L = new Queue<Flit>[2 * GlobalRingWidth]; Q_L2G = new Queue<Flit>[LocalRingWidth * 2]; this.GWidth = GlobalRingWidth; this.LWidth = LocalRingWidth; // for livelock freedom local_observer = new Flit[2 * LWidth]; global_observer = new Flit[2 * GWidth]; local_preserve = new Flit[2 * LWidth]; global_preserve = new Flit[2 * GWidth]; local_obCounter = new int[2 * LWidth]; global_obCounter = new int[2 * GWidth]; local_loopCounter = new int[2 * LWidth]; global_loopCounter = new int [2 * GWidth]; local_starveCounter = new int[2 * LWidth]; global_starveCounter = new int[2 * GWidth]; localRR = 0; globalRR = 0; for (int n = 0; n < 2 * LWidth; n++) { Q_L2G[n] = new Queue<Flit>(); local_starveCounter[n] = 0; } for (int n = 0; n < 2 * GlobalRingWidth; n++) { Q_G2L[n] = new Queue<Flit>(); global_starveCounter[n] = 0; } if (Config.simpleLivelock) switch (Config.topology) { case Topology.HR_4drop : {local_loopCycle = 5; global_loopCycle = 8; break;} case Topology.HR_8drop : {local_loopCycle = 6; global_loopCycle = 16; break;} case Topology.HR_16drop : {local_loopCycle = 8; global_loopCycle = 16; break;} } } public override bool productive(Flit f, int level) { int RingID = -1; switch (Config.topology) { case Topology.HR_4drop : {RingID = ID; break;} case Topology.HR_8drop : {RingID = ID / 2; break;} case Topology.HR_16drop : {RingID = ID / 4; break;} case Topology.HR_8_16drop : {RingID = ID / 4; break;} case Topology.HR_8_8drop : {RingID = ID / 2; break;} case Topology.HR_16_8drop : {RingID = ID / 2; break;} case Topology.HR_32_8drop : {RingID = ID / 2; break;} } if (Config.N == 16 || GWidth == 2) { // 1) Local ring: if its dest is not in the // current ring, send it onto the global ring. // 2) Global ring: if its dest is in the // current ring, drop it into the local ring. if (level == Local) return f.packet.dest.ID / 4 != RingID; else if (level == Global) return f.packet.dest.ID / 4 == RingID; else throw new Exception("undefined level!"); } else if (GWidth >= 4) { if (level == Local) return f.packet.dest.ID / GWidth / GWidth != ID / 2; else return f.packet.dest.ID / GWidth / GWidth == ID / 2; } else throw new Exception("Topology not supported!"); } protected override void _doStep() { localRR = (localRR == LWidth * 2 - 1)? 0 : localRR + 1; globalRR = (globalRR == GWidth * 2 - 1)? 0 : globalRR + 1; /* int RingID = -1; switch (Config.topology) { case Topology.HR_4drop: {RingID = ID; break; } case Topology.HR_8drop: {RingID = ID / 2; break;} case Topology.HR_16drop : {RingID = ID / 4; break;} case Topology.HR_8_16drop : {RingID = ID / 4; break;} case Topology.HR_8_8drop : {RingID = ID / 2; break;} } for (int i = 0; i < LWidth * 2; i++) { if (LLinkIn[i].Out != null && LLinkIn[i].Out.packet.src.ID / 4 == RingID) LLinkIn[i].Out.timeInTheSourceRing ++; else if (LLinkIn[i].Out != null && LLinkIn[i].Out.packet.dest.ID != ID && Config.RingEjectTrial == 2 && Config.topology == Topology.HR_4drop) throw new Exception("In the dest Ring, should not pass the bridgeRouter"); if (Config.SingleDirRing && LLinkIn[1].Out != null) throw new Exception("CCW shouldn't be used in SingleDirRing"); } for (int i = 0; i < 2 * GWidth; i++) { if (GLinkIn[i].Out != null) GLinkIn[i].Out.timeInGR += 2; if (Config.SingleDirRing && GLinkIn[2* (i/2) + 1].Out != null) throw new Exception("CCW shouldn't be used in SingleDirRing"); } */ // the observer, for livelock freedom if (Config.simpleLivelock) { for (int n = 0; n < 2 * LWidth; n++) { if (Config.topology != Topology.HR_8drop) throw new Exception("The observer algorithm only support 8 drop topology"); if (ID % 2 == 1) // the odd bridge routers dont observe traffic break; if (local_observer[n] != null && local_obCounter[n] != local_loopCycle) local_obCounter[n] ++; else if (local_observer[n] != null && local_obCounter[n] == local_loopCycle && local_observer[n] == LLinkIn[n].Out) { local_loopCounter[n] ++; local_obCounter[n] = 1; if (local_loopCounter[n] == Config.observerThreshold) { local_preserve[n] = local_observer[n]; } } else if (local_observer[n] != null && local_obCounter[n] == local_loopCycle && local_observer[n] != LLinkIn[n].Out) { local_observer[n] = null; local_preserve[n] = null; } else if (local_observer[n] == null && LLinkIn[n].Out != null && productive(LLinkIn[n].Out, Local)) { local_preserve[n] = null; local_observer[n] = LLinkIn[n].Out; local_obCounter[n] = 1; local_loopCounter[n] = 0; } } for (int n = 0; n < 2*GWidth; n++) { if (Config.topology != Topology.HR_8drop) throw new Exception("The observer algorithm only support 8 drop topology"); if (ID % 2 == 1) break; if (global_observer[n] != null && global_obCounter[n] != global_loopCycle) global_obCounter[n] ++; else if (global_observer[n] != null && global_obCounter[n] == global_loopCycle && global_observer[n] == GLinkIn[n].Out) { global_loopCounter[n] ++; global_obCounter[n] = 1; if (global_loopCounter[n] == Config.observerThreshold) { global_preserve[n] = global_observer[n]; } } else if (global_observer[n] != null && global_obCounter[n] == global_loopCycle && global_observer[n] != GLinkIn[n].Out) { global_observer[n] = null; global_preserve[n] = null; } else if (global_observer[n] == null && GLinkIn[n].Out != null && productive(GLinkIn[n].Out, Global)) { global_preserve[n] = null; global_observer[n] = GLinkIn[n].Out; global_obCounter[n] = 1; global_loopCounter[n] = 0; } } } ulong Ldeflected = 0; ulong Gdeflected = 0; ulong G2Lcrossed = 0; ulong L2Gcrossed = 0; for (int n = 0; n < 2 * LWidth; n++) // load local traffic into buffer if productive { Flit f = LLinkIn[n].Out; if (f != null && productive(f, Local) && Q_L2G[n].Count < bufferDepth_L2G && (local_preserve[n] == null || local_preserve[n] == LLinkIn[n].Out || Q_L2G[n].Count < bufferDepth_L2G - 1)) { Q_L2G[n].Enqueue(f); L2Gcrossed ++; if (local_preserve[n] == LLinkIn[n].Out) { // Simulator.stats.observerTriggered.Add(1); local_preserve[n] = null; local_observer[n] = null; } LLinkIn[n].Out = null; } else { if (f != null && productive(f, Local)) Ldeflected ++; LLinkOut[n].In = f; LLinkIn[n].Out = null; } } for (int n = 0; n < GWidth * 2; n++) // load global traffic into buffer if productive { Flit f = GLinkIn[n].Out; if (f != null && productive(f, Global) && Q_G2L[n].Count < bufferDepth_G2L && (global_preserve[n] == null || global_preserve[n] == GLinkIn[n].Out || Q_G2L[n].Count < bufferDepth_G2L - 1)) { G2Lcrossed ++; Q_G2L[n].Enqueue(f); if (global_preserve[n] == GLinkIn[n].Out) { // Simulator.stats.observerTriggered.Add(1); global_preserve[n] = null; global_observer[n] = null; } GLinkIn[n].Out = null; } else { if (f != null && productive(f, Global)) Gdeflected ++; GLinkOut[n].In = f; GLinkIn[n].Out = null; } } // If 2 flits want to enter each others' ring, put both into the buffer and swap the flits in the buffer for (int n = 0; n < 2 * LWidth; n++) { int Qnum = (n + localRR) % (LWidth * 2); Flit f = LLinkOut[Qnum].In; if (f == null || !productive(f, Local)) continue; //int preference = L2G_preference(f); bool flag = false; int iter = 2; for (int i = 0; i < iter; i++) { for (int j = 0; j < GWidth; j++) { int k = j;//(j + globalRR) % GWidth; int gport = k*2 + i; Flit fg = GLinkOut[gport].In; if (fg != null && flag == false && productive(fg, Global) && Q_L2G[Qnum].Count > 0 && Q_G2L[gport].Count > 0) { flag = true; GLinkOut[gport].In = Q_L2G[Qnum].Dequeue(); Q_L2G[Qnum].Enqueue(f); LLinkOut[Qnum].In = Q_G2L[gport].Dequeue(); Q_G2L[gport].Enqueue(fg); local_starveCounter[Qnum] = 0; global_starveCounter[gport] = 0; Gdeflected --; Ldeflected --; G2Lcrossed ++; L2Gcrossed ++; } } } } Simulator.stats.GdeflectedFlit.Add(Gdeflected); Simulator.stats.LdeflectedFlit.Add(Ldeflected); Simulator.stats.G2LcrossFlit.Add(G2Lcrossed); Simulator.stats.L2GcrossFlit.Add(L2Gcrossed); // flits from local buffer to global ring for (int n = 0; n < 2 * LWidth; n++) { int Qnum = (localRR + n) % (LWidth * 2); if (Q_L2G[Qnum].Count == 0) continue; // The shorter distance is always preffered Flit f = Q_L2G[Qnum].Peek(); int preference = L2G_preference(f); bool flag = false; int iter = (Config.SingleDirRing || Config.forcePreference)? 1 : 2; for (int i = 0; i < iter; i++) { for (int j = 0; j < GWidth; j++) { int k = (j + globalRR) % GWidth; int gport = Config.SingleDirRing? k*2 : k*2+(preference+i)%2; Flit fg = GLinkOut[gport].In; if (fg == null && flag == false) { GLinkOut[gport].In = Q_L2G[Qnum].Dequeue(); flag = true; local_starveCounter[Qnum] = 0; // if (Q_L2G[Qnum].Count == 0) // Simulator.stats.L2GBufferBypass.Add(1); } } } } //flits from global buffer to local ring for (int n = 0; n < GWidth * 2; n ++) { int Qnum = (n + globalRR) % (GWidth * 2); if (Q_G2L[Qnum].Count == 0) continue; Flit f = Q_G2L[Qnum].Peek(); int preference = G2L_preference(f); bool flag = false; int iter = (Config.SingleDirRing || Config.forcePreference)? 1:2; if (Config.SingleDirRing) preference = 0; for (int i = 0; i < iter; i ++) { for (int j = 0; j < LWidth; j++) { int k = (j + localRR) % LWidth; int r = Config.SingleDirRing? k*2 : k * 2 + (preference+i) % 2; //Console.WriteLine("LW{0}, GW{1}, Qnum{2},QCount:{3}, r:{4}", LWidth, GWidth, Qnum,Q_G2L[Qnum].Count, r); if (LLinkOut[r].In == null && flag == false) { LLinkOut[r].In = Q_G2L[Qnum].Dequeue(); flag = true; global_starveCounter[Qnum] = 0; // if (Q_G2L[Qnum].Count == 0) // Simulator.stats.G2LBufferBypass.Add(1); } } } } if (Config.simpleLivelock) { bool portStarve = false; for (int n = 0; n < 2 * LWidth; n++) { if (Q_L2G[n].Count > 0) local_starveCounter[n] ++; if (local_starveCounter[n] > Config.starveThreshold) portStarve = true; } for (int n = 0; n < 2 * GWidth; n++) { if (Q_G2L[n].Count > 0) global_starveCounter[n] ++; if (global_starveCounter[n] > Config.starveThreshold) portStarve = true; } if (portStarve) starved[ID + Config.N] = true; else starved[ID + Config.N] = false; } } private int G2L_preference(Flit f) { if (Config.NoPreference) return Simulator.rand.Next(2); int preference = -1; int dest = f.packet.dest.ID; if (Config.topology == Topology.HR_4drop) { if (dest == 0 || dest == 3 || dest == 4 || dest == 7 || dest == 9 || dest == 10 || dest == 13 || dest == 14) preference = 0; else preference = 1; } else if (Config.topology == Topology.HR_8drop) { if (dest == 3 || dest == 0 || dest == 5 || dest == 6 || dest == 9 || dest == 10 || dest == 12 || dest == 15) preference = ID % 2; else preference = (1 + ID) % 2; } else if (Config.topology == Topology.HR_16drop) { if (dest == ID || dest == ID + 1 || dest == ID - 3) preference = 0; else preference = 1; } else if (Config.topology == Topology.HR_8_16drop) { int start = ID * 2; int end = (ID * 2 + 3) % 8 + ID / 4 * 8; if (end > start) { if (dest >= start && dest <= end) preference = 0; else preference = 1; } else { if (dest > end && dest < start) preference = 1; else preference = 0; } } else if (Config.topology == Topology.HR_8_8drop || Config.topology == Topology.HR_16_8drop || Config.topology == Topology.HR_32_8drop) { if (dest / LWidth / LWidth % 4 == 0 || dest / LWidth / LWidth % 4 == 3) preference = ((ID % 8 == 0) || (ID % 8 == 3) || (ID % 8 == 5) || (ID % 8 == 6)) ? 0 : 1; else preference = ((ID % 8 == 0) || (ID % 8 == 3) || (ID % 8 == 5) || (ID % 8 == 6)) ? 1 : 0; } else throw new Exception("topology not suported!!!"); return preference; } private int L2G_preference(Flit f) { if (Config.NoPreference) return Simulator.rand.Next(2); int preference = -1; int src = f.packet.src.ID; // int dest = f.packet.dest.ID; if (f.packet.dest.ID / GWidth / GWidth / 4 == f.packet.src.ID / GWidth / GWidth / 4) { // src and dest are now on the same same level of rings if ((f.packet.dest.ID/GWidth/GWidth - f.packet.src.ID/GWidth/GWidth + 4) % 4 < 2) preference = 0; else if ((f.packet.dest.ID/GWidth/GWidth - f.packet.src.ID/GWidth/GWidth + 4) % 4 > 2) preference = 1; } else { if ((src/GWidth/GWidth) % 2 == 0) preference = 0; else preference = 1; } if (preference == -1) preference = Simulator.rand.Next(2); return preference; } public override bool canInjectFlit(Flit f) { return false; } public override void InjectFlit(Flit f) { return; } } }
// // EnumExtensions.cs // // Author: // Craig Fowler <[email protected]> // // Copyright (c) 2015 CSF Software Limited // // 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.Linq; using System.Reflection; using CSF.Resources; using System.Collections.Generic; namespace CSF { /// <summary> /// Type containing extension methods that are useful to enumerated types. /// </summary> /// <remarks> /// <para> /// These extension methods are somewhat general for enumerations and do not live in any special namespace. /// </para> /// </remarks> public static class EnumExtensions { #region extension methods /// <summary> /// Determines whether the given enumeration value is a defined value of its parent enumeration. /// </summary> /// <c>true</c> if the given value is a defined value of its associated enumeration; otherwise, <c>false</c>. /// <param name="value">The enumeration value to analyse.</param> /// <typeparam name="TEnum">The enumeration type.</typeparam> public static bool IsDefinedValue<TEnum>(this TEnum value) where TEnum : struct { var type = typeof(TEnum); RequireEnum(type); return Enum.IsDefined(typeof(TEnum), value); } /// <summary> /// Asserts that the given enumeration value is a defined value of its parent enumeration and raises an /// exception if it is not. /// </summary> /// <exception cref="RequiresDefinedEnumerationConstantException">If the assertion fails.</exception> /// <param name="value">The enumeration value upon which to perform the assertion.</param> /// <param name="name">An object name, to aid in identifying the object should an exception be raised.</param> /// <typeparam name="TEnum">The enumeration type.</typeparam> public static void RequireDefinedValue<TEnum>(this TEnum value, string name) where TEnum : struct { var type = typeof(TEnum); RequireEnum(type); if(!Enum.IsDefined(typeof(TEnum), value)) { throw new RequiresDefinedEnumerationConstantException(value.GetType(), name); } } /// <summary> /// Combines a flags-based enumerated value with the given flags, returning the result. /// </summary> /// <returns> /// The original value, with the given flags added. /// </returns> /// <param name='original'> /// The original value (unmodified in this process). /// </param> /// <param name='addedFlags'> /// A collection of the flags to add. /// </param> /// <typeparam name='TEnum'> /// The type of the enumerated value. /// </typeparam> public static TEnum WithFlags<TEnum>(this TEnum original, params TEnum[] addedFlags) where TEnum : struct { Type enumType = typeof(TEnum); RequireEnum(enumType); RequireFlagsAttribute(enumType); Type underlyingType = Enum.GetUnderlyingType(enumType); ulong numericOriginal = GetEnumValue(original, underlyingType), numericAdded = addedFlags.Aggregate((ulong) 0, (acc,next) => acc += GetEnumValue(next, underlyingType)), output = numericOriginal | numericAdded; return (TEnum) Enum.ToObject(enumType, output); } /// <summary> /// Excludes the given flags from a flags-based enumerated value, returning the result. /// </summary> /// <returns> /// The original value, with the given flags removed. /// </returns> /// <param name='original'> /// The original value (unmodified in this process). /// </param> /// <param name='removedFlags'> /// A collection of the flags to remove. /// </param> /// <typeparam name='TEnum'> /// The type of the enumerated value. /// </typeparam> public static TEnum WithoutFlags<TEnum>(this TEnum original, params TEnum[] removedFlags) where TEnum : struct { Type enumType = typeof(TEnum); RequireEnum(enumType); RequireFlagsAttribute(enumType); Type underlyingType = Enum.GetUnderlyingType(enumType); ulong numericOriginal = GetEnumValue(original, underlyingType), numericRemoved = removedFlags.Aggregate((ulong) 0, (acc,next) => acc += GetEnumValue(next, underlyingType)), output = numericOriginal & (~numericRemoved); return (TEnum) Enum.ToObject(enumType, output); } /// <summary> /// Breaks a <see cref="FlagsAttribute"/>-decorated enumeration value down into its component parts and returns /// them, /// </summary> /// <returns>The individual enumeration values.</returns> /// <param name="combinedValue">The combined enumeration value.</param> /// <typeparam name="TEnum">The type of enumeration.</typeparam> public static IEnumerable<TEnum> GetIndividualValues<TEnum>(this TEnum combinedValue) where TEnum : struct { var enumType = typeof(TEnum); RequireEnum(enumType); RequireFlagsAttribute(enumType); var numericEnumValue = GetEnumValue(combinedValue, enumType); for(int exponent = 0; exponent < 64; exponent++) { if(numericEnumValue == 0) { yield break; } var testValue = (ulong) Math.Pow(2, exponent); if((numericEnumValue & testValue) == testValue) { numericEnumValue -= testValue; yield return (TEnum) Enum.ToObject(enumType, testValue); } } } /// <summary> /// Gets a <c>System.Reflection.FieldInfo</c> instance from an enumeration value. /// </summary> /// <returns> /// Information about the member that represents the enumeration value. /// </returns> /// <param name='value'> /// The enumeration value. /// </param> public static FieldInfo GetFieldInfo<TEnum>(this TEnum value) where TEnum : struct { var enumType = typeof(TEnum); RequireDefinedValue(value, nameof(value)); return enumType.GetField(value.ToString()); } #endregion #region methods /// <summary> /// Gets the numeric equivalent of an enumeration value, given that the enumeration uses the given underlying type. /// </summary> /// <returns> /// The numeric equivalent of the enumeration value. /// </returns> /// <param name='value'> /// The enumeration value. /// </param> /// <param name='underlyingTypeCode'> /// The <c>System.TypeCode</c> of the underlying type of the enumeration. /// </param> internal static ulong GetEnumValue(object value, TypeCode underlyingTypeCode) { ulong output; switch(underlyingTypeCode) { case TypeCode.SByte: output = (ulong) ((byte) ((sbyte) value)); break; case TypeCode.Byte: output = (ulong) ((byte) value); break; case TypeCode.Int16: output = (ulong) ((ushort) ((short) value)); break; case TypeCode.UInt16: output = (ulong) ((ushort) value); break; case TypeCode.Int32: output = (ulong) ((int) value); break; case TypeCode.UInt32: output = (ulong) ((uint) value); break; case TypeCode.Int64: output = (ulong) ((long) value); break; case TypeCode.UInt64: output = (ulong) value; break; default: string message = String.Format(ExceptionMessages.TypeCodeMustBeValid, typeof(TypeCode).Name); throw new ArgumentException(message, nameof(underlyingTypeCode)); } return output; } /// <summary> /// Gets the numeric equivalent of an enumeration value, given that the enumeration uses the given underlying type. /// </summary> /// <returns> /// The numeric equivalent of the enumeration value. /// </returns> /// <param name='value'> /// The enumeration value. /// </param> /// <param name='underlyingType'> /// The underlying type of the enumeration. /// </param> internal static ulong GetEnumValue(object value, Type underlyingType) { if(underlyingType == null) { throw new ArgumentNullException(nameof(underlyingType)); } return GetEnumValue(value, Type.GetTypeCode(underlyingType)); } /// <summary> /// Asserts that the given type is an enumeration. /// </summary> /// <param name="type">The type to analyse.</param> internal static void RequireEnum(Type type) { if(!type.IsEnum) { string message = String.Format(ExceptionMessages.OnlySupportedForEnumTypesFormat, type.FullName); throw new ArgumentException(message, nameof(type)); } } /// <summary> /// Asserts that the given type is decorated with <c>FlagsAttribute</c>. /// </summary> /// <param name="type">The type to analyse.</param> internal static void RequireFlagsAttribute(Type type) { if(type.GetCustomAttribute<FlagsAttribute>() == null) { string message = String.Format(ExceptionMessages.MustBeDecoratedWithFlagsAttribute, typeof(FlagsAttribute).Name, type.FullName); throw new NotSupportedException(message); } } #endregion } }
// Author: abi // Project: DungeonQuest // Path: C:\code\Xna\DungeonQuest // Creation date: 28.03.2007 01:01 // Last modified: 31.07.2007 04:47 #region Using directives using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Storage; using DungeonQuest.Game; using DungeonQuest.Helpers; using DungeonQuest.GameScreens; using DungeonQuest.Sounds; using DungeonQuest.Graphics; using DungeonQuest.Properties; using Texture = DungeonQuest.Graphics.Texture; using DungeonQuest.GameLogic; #endregion namespace DungeonQuest { /// <summary> /// DungeonQuestGame main class /// </summary> public class DungeonQuestGame : BaseGame { #region Variables /// <summary> /// Game screens stack. We can easily add and remove game screens /// and they follow the game logic automatically. Very cool. /// </summary> private static Stack<IGameScreen> gameScreens = new Stack<IGameScreen>(); /// <summary> /// Background landscape models and ship models. /// </summary> public GameManager gameManager = null; /*obs /// <summary> /// Explosion texture, displayed when any ship is exploding. /// </summary> public AnimatedTexture explosionTexture = null; */ /// <summary> /// ShowMouseCursor /// </summary> /// <returns>Bool</returns> public static bool ShowMouseCursor { get { // Only if not in Game, not in logo or splash screen! return gameScreens.Count > 0 && gameScreens.Peek().GetType() != typeof(GameScreen); } // get } // ShowMouseCursor #endregion #region Constructor /// <summary> /// Create your game /// </summary> public DungeonQuestGame() { // Disable mouse, we use our own mouse texture in the menu // and don't use any mouse cursor in the game anyway. this.IsMouseVisible = false; } // DungeonQuestGame() #endregion #region Initialize /// <summary> /// Allows the game to perform any initialization it needs. /// </summary> protected override void Initialize() { base.Initialize(); // Make sure mouse is centered Input.Update(); Input.MousePos = new Point( Window.ClientBounds.X + width / 2, Window.ClientBounds.Y + height / 2); Input.Update(); // Load explosion effect //explosionTexture = new AnimatedTexture("Destroy"); gameManager = new GameManager(); // Create main menu screen //gameScreens.Push(new MainMenu()); // Start game //gameScreens.Push(new Mission()); //inGame = true; // Show end screen after quitting the game gameScreens.Push(new EndScreen()); gameScreens.Push(new GameScreen()); // Start music if (GameSettings.Default.MusicOn) Sound.StartMusic(); // Start background athmosphere sound (loops) Sound.Play(Sound.Sounds.Athmosphere); } // Initialize() #endregion #region Dispose protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) GameSettings.Save(); } // Dispose(disposing) #endregion #region Toggle music on/off /// <summary> /// Toggle music on off /// </summary> public void ToggleMusicOnOff() { if (GameSettings.Default.MusicOn) Sound.StopMusic(); else Sound.StartMusic(); } // ToggleMusicOnOff() #endregion #region Add game screen //always! static bool inGame = false; /// <summary> /// In game /// </summary> /// <returns>Bool</returns> public static bool InGame { get { return true;// inGame; } // get } // InGame /// <summary> /// Add game screen, which will be used until we quit it or add /// another game screen on top of it. /// </summary> /// <param name="newGameScreen">New game screen</param> public static void AddGameScreen(IGameScreen newGameScreen) { gameScreens.Push(newGameScreen); //always! inGame = newGameScreen.GetType() == typeof(Mission); } // AddGameScreen(newGameScreen) #endregion #region Remove current game screen /// <summary> /// Remove current game screen /// </summary> public void RemoveCurrentGameScreen() { gameScreens.Pop(); //always: inGame = gameScreens.Count > 0 && // gameScreens.Peek().GetType() == typeof(Mission); } // RemoveCurrentGameScreen() #endregion #region Render menu background /// <summary> /// Render menu background /// </summary> public void RenderMenuBackground() { gameManager.Run(false); /*unused // Make sure alpha blending is enabled. BaseGame.EnableAlphaBlending(); mainMenuTexture.RenderOnScreen( BaseGame.ResolutionRect, new Rectangle(0, 0, 1024, 768)); */ } // RenderMenuBackground() #endregion #region Render button /*TODO? /// <summary> /// Render button /// </summary> /// <param name="buttonType">Button type</param> /// <param name="rect">Rectangle</param> public bool RenderMenuButton( MenuButton buttonType, Point pos) { // Calc screen rect for rendering (recalculate relative screen position // from 1024x768 to actual screen resolution, just in case ^^). Rectangle rect = new Rectangle( pos.X * BaseGame.Width / 1024, pos.Y * BaseGame.Height / 768, 200 * BaseGame.Width / 1024, 77 * BaseGame.Height / 768); // Is button highlighted? Rectangle innerRect = new Rectangle( rect.X, rect.Y + rect.Height / 5, rect.Width, rect.Height * 3 / 5); bool highlight = Input.MouseInBox( //rect); // Just use inner rect innerRect); /*unused // Was not highlighted last frame? if (highlight && Input.MouseWasNotInRectLastFrame(innerRect)) Sound.Play(Sound.Sounds.Highlight); * // See MainMenu.dds for pixel locations int buttonNum = (int)buttonType; // Correct last 2 button numbers (exit and back) //if (buttonNum >= (int)MenuButton.Exit) // buttonNum -= 2; Rectangle pixelRect = new Rectangle(3 + 204 * buttonNum, 840 + 80 * (highlight ? 1 : 0), 200, 77); // Render mainMenuTexture.RenderOnScreen(rect, pixelRect); // Play click sound if button was just clicked bool ret = (Input.MouseLeftButtonJustPressed || Input.GamePadAJustPressed) && this.IsActive && highlight; if (buttonType == MenuButton.Back && (Input.GamePadBackJustPressed || Input.KeyboardEscapeJustPressed)) ret = true; if (buttonType == MenuButton.Missions && Input.GamePadStartPressed) ret = true; if (ret == true) Sound.Play(Sound.Sounds.Click); // Return true if button was pressed, false otherwise return ret; } // RenderButton(buttonType, rect) */ #endregion #region Render mouse cursor /// <summary> /// Render mouse cursor /// </summary> public void RenderMouseCursor() { /* #if !XBOX360 // We got 4 animation steps, rotate them by the current time int mouseAnimationStep = (int)(BaseGame.TotalTimeMs / 100) % 4; // And render mouse on screen. mouseCursorTexture.RenderOnScreen( new Rectangle(Input.MousePos.X, Input.MousePos.Y, 60*2/3, 64*2/3), new Rectangle(64 * mouseAnimationStep, 0, 60, 64)); // Draw all sprites (just the mouse cursor) SpriteHelper.DrawSprites(width, height); #endif */ } // RenderMouseCursor() #endregion #region Update /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // If that game screen should be quitted, remove it from stack! if (gameScreens.Count > 0 && gameScreens.Peek().Quit) RemoveCurrentGameScreen(); // If no more game screens are left, it is time to quit! if (gameScreens.Count == 0) { #if DEBUG // Don't exit if this is just a unit test if (this.GetType() != typeof(TestGame)) #endif Exit(); } // if base.Update(gameTime); } // Update(gameTime) #endregion #region Draw /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { // Kill background (including z buffer, which is important for 3D) ClearBackground(); /* // Start post screen glow shader, will be shown in BaseGame.Draw BaseGame.GlowShader.Start(); */ // Disable z buffer, mostly now only 2d content is rendered now. //BaseGame.Device.RenderState.DepthBufferEnable = false; try { // Execute the game screen on top. if (gameScreens.Count > 0) gameScreens.Peek().Run(this); } // try catch (Exception ex) { Log.Write("Failed to execute " + gameScreens.Peek().Name + "\nError: " + ex.ToString()); } // catch base.Draw(gameTime); // Show mouse cursor (in all modes except in the game) if (gameScreens.Peek().GetType() != typeof(GameScreen) && gameScreens.Count > 0) RenderMouseCursor(); else { // In game always center mouse Input.CenterMouse(); } // else // Add scene glow on top of everything (2d and 3d!) glowShader.Show(); } // Draw(gameTime) #endregion } // class DungeonQuestGame } // namespace DungeonQuest
using System; using System.Collections.Generic; using System.Linq; // Needed for StringBuilder using System.Text; using System.Threading.Tasks; // For culture specific formating using System.Globalization; namespace CSharpTutA.cs { class Program { static void Main(string[] args) { // ----- IMPLICIT TYPING ----- // You can use var to have C# figure out the // data type var intVal = 1234; Console.WriteLine("intVal Type : {0}", intVal.GetType()); // ----- ARRAYS ----- // Arrays are just boxes inside of a bigger box // that can contain many values of the same // data type // Each item is assigned a key starting at 0 // and incrementing up from there // Define an array which holds 3 values // Arrays have fixed sizes int[] favNums = new int[3]; // Add a value to the array favNums[0] = 23; // Retrieve a value Console.WriteLine("favNum 0 : {0}", favNums[0]); // Create and fill array string[] customers = { "Bob", "Sally", "Sue" }; // You can use var to create arrays, but the // values must be of the same type var employees = new[] { "Mike", "Paul", "Rick" }; // Create an array of base objects which is the // base type of all other types object[] randomArray = { "Paul", 45, 1.234 }; // GetType knows its true type Console.WriteLine("randomArray 0 : {0}", randomArray[0].GetType()); // Get number of items in array Console.WriteLine("Array Size : {0}", randomArray.Length); // Use for loop to cycle through the array for(int i = 0; i < randomArray.Length; i++) { Console.WriteLine("Array {0} : Value : {1}", i, randomArray[i]); } // Multidimensional arrays // When you define an array like arrName[5] you // are saying you want to create boxes stacked // vertically // If you define arrName[2,2] you are saying // you want to have 2 rows high and 2 across string[,] custNames = new string[2,2] { { "Bob", "Smith" }, { "Sally", "Smith" } }; // Get value in MD array Console.WriteLine("MD Value : {0}", custNames.GetValue(1,1)); // Cycle through the multidimensional array // Get length of multidimensional array column for (int i = 0; i < custNames.GetLength(0); i++) { // Get length of multidimensional array row for(int j = 0; j < custNames.GetLength(1); j++) { Console.Write("{0} ",custNames[i,j]); } Console.WriteLine(); } // An array like arrName[2,2,3] would be like a // stack of 3 spread sheets with 2 rows and 2 // columns worth of data on each page // foreach can be used to cycle through an array int[] randNums = { 1, 4, 9, 2 }; // You can pass an array to a function PrintArray(randNums, "ForEach"); // Sort array Array.Sort(randNums); // Reverse array Array.Reverse(randNums); // Get index of match or return -1 Console.WriteLine("1 at index : {0} ", Array.IndexOf(randNums, 1)); // Change value at index 1 to 0 randNums.SetValue(0, 1); // Copy part of an array to another int[] srcArray = { 1, 2, 3 }; int[] destArray = new int[2]; int startInd = 0; int length = 2; Array.Copy(srcArray, startInd, destArray, startInd, length); PrintArray(destArray, "Copy"); // Create an array with CreateInstance Array anotherArray = Array.CreateInstance(typeof(int), 10); // Copy values in srcArray to destArray starting // at index 5 in destination srcArray.CopyTo(anotherArray, 5); foreach (int m in anotherArray) { Console.WriteLine("CopyTo : {0} ", m); } // Search for an element that matches the conditions // defined by the specified predicate int[] numArray = { 1, 11, 22 }; Console.WriteLine("> 10 : {0}", Array.Find(numArray, GT10)); // FindAll returns an array with all values that // match // FindIndex returns the index of the match // ----- STRINGBUILDER ----- // Each time you change a string you are actually // creating a new string which is inefficient // when you are working with large blocks of text // StringBuilders actually change the text // rather then make a copy // Create a StringBuilder with a default size // of 16 characters, but it grows automatically StringBuilder sb = new StringBuilder("Random Text"); // Create a StringBuilder with a size of 256 StringBuilder sb2 = new StringBuilder("More Stuff that is very important", 256); // Get max size Console.WriteLine("Capacity : {0}", sb2.Capacity); // Get length Console.WriteLine("Length : {0}", sb2.Length); // Add text to StringBuilder sb2.AppendLine("\nMore important text"); // Define culture specific formating CultureInfo enUS = CultureInfo.CreateSpecificCulture("en-US"); // Append a format string string bestCust = "Bob Smith"; sb2.AppendFormat(enUS, "Best Customer : {0}", bestCust); // Output StringBuilder Console.WriteLine(sb2.ToString()); // Replace a string sb2.Replace("text", "characters"); Console.WriteLine(sb2.ToString()); // Clear a string builder sb2.Clear(); sb2.Append("Random Text"); // Are objects equal Console.WriteLine(sb.Equals(sb2)); // Insert at an index sb2.Insert(11, " that's Great"); Console.WriteLine("Insert : {0}", sb2.ToString()); // Remove number of characters starting at index sb2.Remove(11, 7); Console.WriteLine("Remove : {0}", sb2.ToString()); // ----- CASTING ----- // If you want to cast from one type to another long num1 = 1234; int num2 = (int)num1; Console.WriteLine("Orig : {0} Cast : {1}", num1.GetType(), num2.GetType()); Console.ReadLine(); } static void PrintArray(int[] intArray, string mess) { foreach (int k in intArray) { Console.WriteLine("{0} : {1} ", mess, k); } } private static bool GT10(int val) { return val > 10; } } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // // Description: AnchoredBlock element. // AnchoredBlock element - an abstract class used as a base for // TextElements incorporated (anchored) into text flow on inline level, // but appearing visually in separate block. // Derived concrete classes are: Floater and Figure. // //--------------------------------------------------------------------------- using System.ComponentModel; // TypeConverter using System.Windows.Media; // Brush using System.Windows.Markup; // ContentProperty using MS.Internal; namespace System.Windows.Documents { /// <summary> /// AnchoredBlock element - an abstract class used as a base for /// TextElements incorporated (anchored) into text flow on inline level, /// but appearing visually in separate block. /// Derived concrete classes are: Flowter and Figure. /// </summary> [ContentProperty("Blocks")] public abstract class AnchoredBlock : Inline { //------------------------------------------------------------------- // // Constructors // //------------------------------------------------------------------- #region Constructors /// <summary> /// Creates a new AnchoredBlock instance. /// </summary> /// <param name="block"> /// Optional child of the new AnchoredBlock, may be null. /// </param> /// <param name="insertionPosition"> /// Optional position at which to insert the new AnchoredBlock. May /// be null. /// </param> protected AnchoredBlock(Block block, TextPointer insertionPosition) { if (insertionPosition != null) { insertionPosition.TextContainer.BeginChange(); } try { if (insertionPosition != null) { // This will throw InvalidOperationException if schema validity is violated. insertionPosition.InsertInline(this); } if (block != null) { this.Blocks.Add(block); } } finally { if (insertionPosition != null) { insertionPosition.TextContainer.EndChange(); } } } #endregion Constructors //------------------------------------------------------------------- // // Public Properties // //------------------------------------------------------------------- #region Public Properties /// <value> /// Collection of Blocks contained in this element /// </value> [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public BlockCollection Blocks { get { return new BlockCollection(this, /*isOwnerParent*/true); } } /// <summary> /// DependencyProperty for <see cref="Margin" /> property. /// </summary> public static readonly DependencyProperty MarginProperty = Block.MarginProperty.AddOwner( typeof(AnchoredBlock), new FrameworkPropertyMetadata( new Thickness(Double.NaN), FrameworkPropertyMetadataOptions.AffectsMeasure)); /// <summary> /// The Margin property specifies the margin of the element. /// </summary> public Thickness Margin { get { return (Thickness)GetValue(MarginProperty); } set { SetValue(MarginProperty, value); } } /// <summary> /// DependencyProperty for <see cref="Padding" /> property. /// </summary> public static readonly DependencyProperty PaddingProperty = Block.PaddingProperty.AddOwner( typeof(AnchoredBlock), new FrameworkPropertyMetadata( new Thickness(Double.NaN), FrameworkPropertyMetadataOptions.AffectsMeasure)); /// <summary> /// The Padding property specifies the padding of the element. /// </summary> public Thickness Padding { get { return (Thickness)GetValue(PaddingProperty); } set { SetValue(PaddingProperty, value); } } /// <summary> /// DependencyProperty for <see cref="BorderThickness" /> property. /// </summary> public static readonly DependencyProperty BorderThicknessProperty = Block.BorderThicknessProperty.AddOwner( typeof(AnchoredBlock), new FrameworkPropertyMetadata( new Thickness(), FrameworkPropertyMetadataOptions.AffectsMeasure)); /// <summary> /// The BorderThickness property specifies the border of the element. /// </summary> public Thickness BorderThickness { get { return (Thickness)GetValue(BorderThicknessProperty); } set { SetValue(BorderThicknessProperty, value); } } /// <summary> /// DependencyProperty for <see cref="BorderBrush" /> property. /// </summary> public static readonly DependencyProperty BorderBrushProperty = Block.BorderBrushProperty.AddOwner( typeof(AnchoredBlock), new FrameworkPropertyMetadata( null, FrameworkPropertyMetadataOptions.AffectsRender)); /// <summary> /// The BorderBrush property specifies the brush of the border. /// </summary> public Brush BorderBrush { get { return (Brush)GetValue(BorderBrushProperty); } set { SetValue(BorderBrushProperty, value); } } /// <summary> /// DependencyProperty for <see cref="TextAlignment" /> property. /// </summary> public static readonly DependencyProperty TextAlignmentProperty = Block.TextAlignmentProperty.AddOwner(typeof(AnchoredBlock)); /// <summary> /// /// </summary> public TextAlignment TextAlignment { get { return (TextAlignment)GetValue(TextAlignmentProperty); } set { SetValue(TextAlignmentProperty, value); } } /// <summary> /// DependencyProperty for <see cref="LineHeight" /> property. /// </summary> public static readonly DependencyProperty LineHeightProperty = Block.LineHeightProperty.AddOwner(typeof(AnchoredBlock)); /// <summary> /// The LineHeight property specifies the height of each generated line box. /// </summary> [TypeConverter(typeof(LengthConverter))] public double LineHeight { get { return (double)GetValue(LineHeightProperty); } set { SetValue(LineHeightProperty, value); } } /// <summary> /// DependencyProperty for <see cref="LineStackingStrategy" /> property. /// </summary> public static readonly DependencyProperty LineStackingStrategyProperty = Block.LineStackingStrategyProperty.AddOwner(typeof(AnchoredBlock)); /// <summary> /// The LineStackingStrategy property specifies how lines are placed /// </summary> public LineStackingStrategy LineStackingStrategy { get { return (LineStackingStrategy)GetValue(LineStackingStrategyProperty); } set { SetValue(LineStackingStrategyProperty, value); } } #endregion Public Proterties #region Internal Methods /// <summary> /// This method is used by TypeDescriptor to determine if this property should /// be serialized. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public bool ShouldSerializeBlocks(XamlDesignerSerializationManager manager) { return manager != null && manager.XmlWriter == null; } #endregion //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties /// <summary> /// Marks this element's left edge as visible to IMEs. /// This means element boundaries will act as word breaks. /// </summary> internal override bool IsIMEStructuralElement { get { return true; } } #endregion Internal Properties } }
using System; using System.Collections.Generic; using System.Linq; using System.Data; using System.Runtime.Serialization; using Signum.Utilities; using Signum.Entities.Reflection; using Signum.Utilities.ExpressionTrees; using Signum.Entities.Basics; using NpgsqlTypes; namespace Signum.Entities { [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class UniqueIndexAttribute : Attribute { public bool AllowMultipleNulls { get; set; } public bool AvoidAttachToUniqueIndexes { get; set; } } [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class AttachToUniqueIndexesAttribute : Attribute { } [Serializable] public struct Implementations : IEquatable<Implementations>, ISerializable { object? arrayOrType; public bool IsByAll { get { return arrayOrType == null; } } public IEnumerable<Type> Types { get { if (arrayOrType == null) throw new InvalidOperationException("ImplementedByAll"); return Enumerate(); } } private IEnumerable<Type> Enumerate() { if (arrayOrType is Type t) { yield return t; } else if (arrayOrType is Type[] ts) { foreach (var item in ts) yield return item; } else throw new InvalidOperationException("IsByAll"); } public static Implementations? TryFromAttributes(Type t, PropertyRoute route, ImplementedByAttribute? ib, ImplementedByAllAttribute? iba) { if (ib != null && iba != null) throw new NotSupportedException("Route {0} contains both {1} and {2}".FormatWith(route, ib.GetType().Name, iba.GetType().Name)); if (ib != null) return Implementations.By(ib.ImplementedTypes); if (iba != null) return Implementations.ByAll; if (Error(t) == null) return Implementations.By(t); return null; } public static Implementations FromAttributes(Type t, PropertyRoute route, ImplementedByAttribute? ib, ImplementedByAllAttribute? iba) { Implementations? imp = TryFromAttributes(t, route, ib, iba); if (imp == null) { var message = Error(t) + @". Set implementations for {0}.".FormatWith(route); if (t.IsInterface || t.IsAbstract) { message += @"\r\n" + ConsiderMessage(route, "typeof(YourConcrete" + t.TypeName() + ")"); } throw new InvalidOperationException(message); } return imp.Value; } internal static string ConsiderMessage(PropertyRoute route, string targetTypes) { return $@"Consider writing something like this in your Starter class: sb.Schema.Settings.FieldAttributes(({route.RootType.TypeName()} a) => a.{route.PropertyString().Replace("/", ".First().")}).Replace(new ImplementedByAttribute({targetTypes}))"; } public static Implementations ByAll { get { return new Implementations(); } } public static Implementations By(Type type) { var error = Error(type); if (error.HasText()) throw new InvalidOperationException(error); return new Implementations { arrayOrType = type }; } public static Implementations By(params Type[] types) { if (types == null || types.Length == 0) return new Implementations { arrayOrType = types ?? new Type[0] }; if (types.Length == 1) return By(types[0]); var error = types.Select(Error).NotNull().ToString("\r\n"); if (error.HasText()) throw new InvalidOperationException(error); return new Implementations { arrayOrType = types.OrderBy(a => a.FullName).ToArray() }; } static string? Error(Type type) { if (type.IsInterface) return "{0} is an interface".FormatWith(type.Name); if (type.IsAbstract) return "{0} is abstract".FormatWith(type.Name); if (!type.IsEntity()) return "{0} is not {1}".FormatWith(type.Name, typeof(Entity).Name); return null; } public string Key() { if (IsByAll) return "[ALL]"; return Types.ToString(TypeEntity.GetCleanName, ", "); } public override string ToString() { if (IsByAll) return "ImplementedByAll"; return "ImplementedBy({0})".FormatWith(Types.ToString(t => t.Name, ", ")); } public override bool Equals(object? obj) { return obj is Implementations imp && Equals(imp); } public bool Equals(Implementations other) { return IsByAll && other.IsByAll || arrayOrType == other.arrayOrType || Enumerable.SequenceEqual(Types, other.Types); } public override int GetHashCode() { return arrayOrType == null ? 0 : Types.Aggregate(0, (acum, type) => acum ^ type.GetHashCode()); } Implementations(SerializationInfo info, StreamingContext context) { string str = info.GetString("arrayOrType")!; arrayOrType = str == "ALL" ? null : str.Split('|').Select(Type.GetType).ToArray(); if (arrayOrType is Type[] array && array.Length == 1) arrayOrType = array[0]; } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("arrayOrType", arrayOrType == null ? "ALL" : arrayOrType is Type t ? t.AssemblyQualifiedName : arrayOrType is Type[] ts ? ts.ToString(a => a.AssemblyQualifiedName, "|") : null); } public static bool operator ==(Implementations left, Implementations right) { return left.Equals(right); } public static bool operator !=(Implementations left, Implementations right) { return !(left == right); } } [Serializable, AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class ImplementedByAttribute : Attribute { Type[] implementedTypes; public Type[] ImplementedTypes { get { return implementedTypes; } } public ImplementedByAttribute(params Type[] types) { implementedTypes = types; } } [Serializable, AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class ImplementedByAllAttribute : Attribute { public ImplementedByAllAttribute() { } } /// <summary> /// Avoids that an Entity field has database representation (column or MList table) /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class IgnoreAttribute : Attribute { } [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class FieldWithoutPropertyAttribute : Attribute { } [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class ForceNotNullableAttribute : Attribute { } /// <summary> /// Very rare. Reference types (classes) or Nullable are already nullable in the database. /// This attribute is only necessary in the case an entity field is not-nullable but you can not make the DB column nullable because of legacy data, or cycles in a graph of entities. /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class ForceNullableAttribute: Attribute { } [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class DbTypeAttribute : Attribute { SqlDbType? sqlDbType; public bool HasSqlDbType => sqlDbType.HasValue; public SqlDbType SqlDbType { get { return sqlDbType!.Value; } set { sqlDbType = value; } } NpgsqlDbType? npgsqlDbType; public bool HasNpgsqlDbType => npgsqlDbType.HasValue; public NpgsqlDbType NpgsqlDbType { get { return npgsqlDbType!.Value; } set { npgsqlDbType = value; } } int? size; public bool HasSize => size.HasValue; public int Size { get { return size!.Value; } set { size = value; } } int? scale; public bool HasScale => scale.HasValue; public int Scale { get { return scale!.Value; } set { scale = value; } } public string? UserDefinedTypeName { get; set; } public string? Default { get; set; } public string? DefaultSqlServer { get; set; } public string? DefaultPostgres { get; set; } public string? GetDefault(bool isPostgres) { return (isPostgres ? DefaultPostgres : DefaultSqlServer) ?? Default; } public string? Collation { get; set; } public const string SqlServer_NewId = "NEWID()"; public const string SqlServer_NewSequentialId = "NEWSEQUENTIALID()"; public const string Postgres_UuidGenerateV1= "uuid_generate_v1()"; } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Property /*MList fields*/, Inherited = true, AllowMultiple = false)] public sealed class PrimaryKeyAttribute : DbTypeAttribute { public Type Type { get; set; } public string Name { get; set; } public bool Identity { get; set; } bool identityBehaviour; public bool IdentityBehaviour { get { return identityBehaviour; } set { identityBehaviour = value; if (Type == typeof(Guid) && identityBehaviour) { this.DefaultSqlServer = SqlServer_NewId; this.DefaultPostgres = Postgres_UuidGenerateV1; } } } public PrimaryKeyAttribute(Type type, string name = "ID") { this.Type = type; this.Name = name; this.Identity = type == typeof(Guid) ? false : true; this.IdentityBehaviour = true; } } [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, Inherited = true, AllowMultiple = false)] public sealed class ColumnNameAttribute : Attribute { public string Name { get; set; } public ColumnNameAttribute(string name) { this.Name = name; } } [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, Inherited = true, AllowMultiple = false)] public sealed class BackReferenceColumnNameAttribute : Attribute { public string Name { get; set; } public BackReferenceColumnNameAttribute(string name) { this.Name = name; } } [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class ViewPrimaryKeyAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class)] public sealed class CacheViewMetadataAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Property /*MList fields*/, Inherited = true, AllowMultiple = false)] public sealed class TableNameAttribute : Attribute { public string Name { get; set; } public string? SchemaName { get; set; } public string? DatabaseName { get; set; } public string? ServerName { get; set; } public TableNameAttribute(string fullName) { var parts = fullName.Split('.'); this.Name = parts.ElementAtOrDefault(parts.Length - 1).Trim('[', ']'); this.SchemaName = parts.ElementAtOrDefault(parts.Length - 2)?.Trim('[', ']'); this.DatabaseName = parts.ElementAtOrDefault(parts.Length - 3)?.Trim('[', ']'); this.ServerName = parts.ElementAtOrDefault(parts.Length - 4)?.Trim('[', ']'); } } [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)] public sealed class TicksColumnAttribute : DbTypeAttribute { public bool HasTicks { get; private set; } public string? Name { get; set; } public Type? Type { get; set; } public TicksColumnAttribute(bool hasTicks = true) { this.HasTicks = hasTicks; } } /// <summary> /// Activates SQL Server 2016 Temporal Tables /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Field | AttributeTargets.Property /*MList fields*/, Inherited = true, AllowMultiple = false)] public sealed class SystemVersionedAttribute : Attribute { public string? TemporalTableName { get; set; } public string StartDateColumnName { get; set; } = "SysStartDate"; public string EndDateColumnName { get; set; } = "SysEndDate"; public string PostgreeSysPeriodColumname { get; set; } = "sys_period"; } [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class AvoidForeignKeyAttribute : Attribute { } [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class AvoidExpandQueryAttribute : Attribute { } [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class CombineStrategyAttribute : Attribute { public readonly CombineStrategy Strategy; public CombineStrategyAttribute(CombineStrategy strategy) { this.Strategy = strategy; } } public enum CombineStrategy { Union, Case, } public static class LinqHintEntities { public static T CombineCase<T>(this T value) where T : IEntity { return value; } public static T CombineUnion<T>(this T value) where T : IEntity { return value; } } }
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System.Linq; using NLog.Conditions; using NLog.Config; using NLog.Internal; using NLog.LayoutRenderers; using NLog.Layouts; using NLog.Targets.Wrappers; using NLog.UnitTests.Targets.Wrappers; using NSubstitute; using NSubstitute.ExceptionExtensions; namespace NLog.UnitTests.Targets { using System; using System.Collections.Generic; using System.Threading; using NLog.Common; using NLog.Targets; using Xunit; public class TargetTests : NLogTestBase { /// <summary> /// Test the following things: /// - Target has default ctor /// - Target has ctor with name (string) arg. /// - Both ctors are creating the same instances /// </summary> [Fact] public void TargetContructorWithNameTest() { var targetTypes = typeof(Target).Assembly.GetTypes().Where(t => !t.IsAbstract && t.IsSubclassOf(typeof(Target))).ToList(); int neededCheckCount = targetTypes.Count; int checkCount = 0; Target fileTarget = new FileTarget(); Target memoryTarget = new MemoryTarget(); foreach (Type targetType in targetTypes) { string lastPropertyName = null; try { // Check if the Target can be created using a default constructor var name = targetType + "_name"; var isWrapped = targetType.IsSubclassOf(typeof(WrapperTargetBase)); var isCompound = targetType.IsSubclassOf(typeof(CompoundTargetBase)); if (isWrapped) { neededCheckCount++; var args = new List<object> { fileTarget }; //default ctor var defaultConstructedTarget = (WrapperTargetBase)Activator.CreateInstance(targetType); defaultConstructedTarget.Name = name; defaultConstructedTarget.WrappedTarget = fileTarget; //specials cases if (targetType == typeof(FilteringTargetWrapper)) { ConditionLoggerNameExpression cond = null; args.Add(cond); var target = (FilteringTargetWrapper)defaultConstructedTarget; target.Condition = cond; } else if (targetType == typeof(RepeatingTargetWrapper)) { var repeatCount = 5; args.Add(repeatCount); var target = (RepeatingTargetWrapper)defaultConstructedTarget; target.RepeatCount = repeatCount; } else if (targetType == typeof(RetryingTargetWrapper)) { var retryCount = 10; var retryDelayMilliseconds = 100; args.Add(retryCount); args.Add(retryDelayMilliseconds); var target = (RetryingTargetWrapper)defaultConstructedTarget; target.RetryCount = retryCount; target.RetryDelayMilliseconds = retryDelayMilliseconds; } //ctor: target var targetConstructedTarget = (WrapperTargetBase)Activator.CreateInstance(targetType, args.ToArray()); targetConstructedTarget.Name = name; args.Insert(0, name); //ctor: target+name var namedConstructedTarget = (WrapperTargetBase)Activator.CreateInstance(targetType, args.ToArray()); CheckEquals(targetType, targetConstructedTarget, namedConstructedTarget, ref lastPropertyName, ref checkCount); CheckEquals(targetType, defaultConstructedTarget, namedConstructedTarget, ref lastPropertyName, ref checkCount); } else if (isCompound) { neededCheckCount++; //multiple targets var args = new List<object> { fileTarget, memoryTarget }; //specials cases //default ctor var defaultConstructedTarget = (CompoundTargetBase)Activator.CreateInstance(targetType); defaultConstructedTarget.Name = name; defaultConstructedTarget.Targets.Add(fileTarget); defaultConstructedTarget.Targets.Add(memoryTarget); //ctor: target var targetConstructedTarget = (CompoundTargetBase)Activator.CreateInstance(targetType, args.ToArray()); targetConstructedTarget.Name = name; args.Insert(0, name); //ctor: target+name var namedConstructedTarget = (CompoundTargetBase)Activator.CreateInstance(targetType, args.ToArray()); CheckEquals(targetType, targetConstructedTarget, namedConstructedTarget, ref lastPropertyName, ref checkCount); CheckEquals(targetType, defaultConstructedTarget, namedConstructedTarget, ref lastPropertyName, ref checkCount); } else { //default ctor var targetConstructedTarget = (Target)Activator.CreateInstance(targetType); targetConstructedTarget.Name = name; // ctor: name var namedConstructedTarget = (Target)Activator.CreateInstance(targetType, name); CheckEquals(targetType, targetConstructedTarget, namedConstructedTarget, ref lastPropertyName, ref checkCount); } } catch (Exception ex) { var constructionFailed = true; string failureMessage = $"Error testing constructors for '{targetType}.{lastPropertyName}`\n{ex.ToString()}"; Assert.False(constructionFailed, failureMessage); } } Assert.Equal(neededCheckCount, checkCount); } private static void CheckEquals(Type targetType, Target defaultConstructedTarget, Target namedConstructedTarget, ref string lastPropertyName, ref int @checked) { var checkedAtLeastOneProperty = false; var properties = targetType.GetProperties( System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.FlattenHierarchy | System.Reflection.BindingFlags.Default | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static); foreach (System.Reflection.PropertyInfo pi in properties) { lastPropertyName = pi.Name; if (pi.CanRead && !pi.Name.Equals("SyncRoot")) { var value1 = pi.GetValue(defaultConstructedTarget, null); var value2 = pi.GetValue(namedConstructedTarget, null); if (value1 != null && value2 != null) { if (value1 is IRenderable) { Assert.Equal((IRenderable)value1, (IRenderable)value2, new RenderableEq()); } else if (value1 is AsyncRequestQueue) { Assert.Equal((AsyncRequestQueue)value1, (AsyncRequestQueue)value2, new AsyncRequestQueueEq()); } else { Assert.Equal(value1, value2); } } else { Assert.Null(value1); Assert.Null(value2); } checkedAtLeastOneProperty = true; } } if (checkedAtLeastOneProperty) { @checked++; } } private class RenderableEq : EqualityComparer<IRenderable> { /// <summary> /// Determines whether the specified objects are equal. /// </summary> /// <returns> /// true if the specified objects are equal; otherwise, false. /// </returns> /// <param name="x">The first object of type <paramref name="T"/> to compare.</param><param name="y">The second object of type <paramref name="T"/> to compare.</param> public override bool Equals(IRenderable x, IRenderable y) { if (x == null) return y == null; var nullEvent = LogEventInfo.CreateNullEvent(); return x.Render(nullEvent) == y.Render(nullEvent); } /// <summary> /// Returns a hash code for the specified object. /// </summary> /// <returns> /// A hash code for the specified object. /// </returns> /// <param name="obj">The <see cref="T:System.Object"/> for which a hash code is to be returned.</param><exception cref="T:System.ArgumentNullException">The type of <paramref name="obj"/> is a reference type and <paramref name="obj"/> is null.</exception> public override int GetHashCode(IRenderable obj) { return obj.ToString().GetHashCode(); } } private class AsyncRequestQueueEq : EqualityComparer<AsyncRequestQueue> { /// <summary> /// Determines whether the specified objects are equal. /// </summary> /// <returns> /// true if the specified objects are equal; otherwise, false. /// </returns> /// <param name="x">The first object of type <paramref name="T"/> to compare.</param><param name="y">The second object of type <paramref name="T"/> to compare.</param> public override bool Equals(AsyncRequestQueue x, AsyncRequestQueue y) { if (x == null) return y == null; return x.RequestLimit == y.RequestLimit && x.OnOverflow == y.OnOverflow; } /// <summary> /// Returns a hash code for the specified object. /// </summary> /// <returns> /// A hash code for the specified object. /// </returns> /// <param name="obj">The <see cref="T:System.Object"/> for which a hash code is to be returned.</param><exception cref="T:System.ArgumentNullException">The type of <paramref name="obj"/> is a reference type and <paramref name="obj"/> is null.</exception> public override int GetHashCode(AsyncRequestQueue obj) { unchecked { return (obj.RequestLimit * 397) ^ (int)obj.OnOverflow; } } } [Fact] public void InitializeTest() { var target = new MyTarget(); target.Initialize(null); // initialize was called once Assert.Equal(1, target.InitializeCount); Assert.Equal(1, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); } [Fact] public void WriteAsyncLogEvent_InitializeThrowsException_LogContinuationCalledWithCorrectExceptions() { // Arrange var target = new ThrowingInitializeTarget(true); Exception retrievedException = null; var logevent = LogEventInfo.CreateNullEvent().WithContinuation(ex => { retrievedException = ex; }); LogManager.ThrowExceptions = false; target.Initialize(new LoggingConfiguration()); LogManager.ThrowExceptions = true; // Act target.WriteAsyncLogEvent(logevent); // Assert Assert.NotNull(retrievedException); var runtimeException = Assert.IsType<NLogRuntimeException>(retrievedException); var innerException = Assert.IsType<TestException>(runtimeException.InnerException); Assert.Equal("Initialize says no", innerException.Message); } [Fact] public void Flush_ThrowsException_LogContinuationCalledWithCorrectExceptions() { // Arrange var target = new ThrowingInitializeTarget(false); Exception retrievedException = null; AsyncContinuation asyncContinuation = ex => { retrievedException = ex; }; target.Initialize(new LoggingConfiguration()); LogManager.ThrowExceptions = false; // Act target.Flush(asyncContinuation); // Assert Assert.NotNull(retrievedException); //note: not wrapped in NLogRuntimeException, not sure if by design. Assert.IsType<TestException>(retrievedException); } [Fact] public void WriteAsyncLogEvent_WriteAsyncLogEventThrowsException_LogContinuationCalledWithCorrectExceptions() { // Arrange var target = new ThrowingInitializeTarget(false); Exception retrievedException = null; var logevent = LogEventInfo.CreateNullEvent().WithContinuation(ex => { retrievedException = ex; }); target.Initialize(new LoggingConfiguration()); LogManager.ThrowExceptions = false; // Act target.WriteAsyncLogEvent(logevent); // Assert Assert.NotNull(retrievedException); //note: not wrapped in NLogRuntimeException, not sure if by design. Assert.IsType<TestException>(retrievedException); Assert.Equal("Write oops", retrievedException.Message); } private class ThrowingInitializeTarget : Target { private readonly bool _throwsOnInit; #region Overrides of Target /// <inheritdoc /> public ThrowingInitializeTarget(bool throwsOnInit) { _throwsOnInit = throwsOnInit; } /// <inheritdoc /> protected override void InitializeTarget() { if (_throwsOnInit) throw new TestException("Initialize says no"); } /// <inheritdoc /> protected override void FlushAsync(AsyncContinuation asyncContinuation) { throw new TestException("No flush"); } /// <inheritdoc /> protected override void WriteAsyncThreadSafe(AsyncLogEventInfo logEvent) { throw new TestException("Write oops"); } #endregion } private class TestException : Exception { /// <inheritdoc /> public TestException(string message) : base(message) { } } [Fact] public void InitializeFailedTest() { var target = new MyTarget(); target.ThrowOnInitialize = true; LogManager.ThrowExceptions = true; Assert.Throws<InvalidOperationException>(() => target.Initialize(null)); // after exception in Initialize(), the target becomes non-functional and all Write() operations var exceptions = new List<Exception>(); target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); Assert.Equal(0, target.WriteCount); Assert.Single(exceptions); Assert.NotNull(exceptions[0]); Assert.Equal("Target " + target + " failed to initialize.", exceptions[0].Message); Assert.Equal("Init error.", exceptions[0].InnerException.Message); } [Fact] public void DoubleInitializeTest() { var target = new MyTarget(); target.Initialize(null); target.Initialize(null); // initialize was called once Assert.Equal(1, target.InitializeCount); Assert.Equal(1, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); } [Fact] public void DoubleCloseTest() { var target = new MyTarget(); target.Initialize(null); target.Close(); target.Close(); // initialize and close were called once each Assert.Equal(1, target.InitializeCount); Assert.Equal(1, target.CloseCount); Assert.Equal(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); } [Fact] public void CloseWithoutInitializeTest() { var target = new MyTarget(); target.Close(); // nothing was called Assert.Equal(0, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); } [Fact] public void WriteWithoutInitializeTest() { var target = new MyTarget(); List<Exception> exceptions = new List<Exception>(); target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); target.WriteAsyncLogEvents(new[] { LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), }); // write was not called Assert.Equal(0, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); Assert.Equal(4, exceptions.Count); exceptions.ForEach(Assert.Null); } [Fact] public void WriteOnClosedTargetTest() { var target = new MyTarget(); target.Initialize(null); target.Close(); var exceptions = new List<Exception>(); target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); target.WriteAsyncLogEvents( LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); Assert.Equal(1, target.InitializeCount); Assert.Equal(1, target.CloseCount); // write was not called Assert.Equal(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); // but all callbacks were invoked with null values Assert.Equal(4, exceptions.Count); exceptions.ForEach(Assert.Null); } [Fact] public void FlushTest() { var target = new MyTarget(); List<Exception> exceptions = new List<Exception>(); target.Initialize(null); target.Flush(exceptions.Add); // flush was called Assert.Equal(1, target.FlushCount); Assert.Equal(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); Assert.Single(exceptions); exceptions.ForEach(Assert.Null); } [Fact] public void FlushWithoutInitializeTest() { var target = new MyTarget(); List<Exception> exceptions = new List<Exception>(); target.Flush(exceptions.Add); Assert.Single(exceptions); exceptions.ForEach(Assert.Null); // flush was not called Assert.Equal(0, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); } [Fact] public void FlushOnClosedTargetTest() { var target = new MyTarget(); target.Initialize(null); target.Close(); Assert.Equal(1, target.InitializeCount); Assert.Equal(1, target.CloseCount); List<Exception> exceptions = new List<Exception>(); target.Flush(exceptions.Add); Assert.Single(exceptions); exceptions.ForEach(Assert.Null); // flush was not called Assert.Equal(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); } [Fact] public void LockingTest() { var target = new MyTarget(); target.Initialize(null); var mre = new ManualResetEvent(false); Exception backgroundThreadException = null; Thread t = new Thread(() => { try { target.BlockingOperation(500); } catch (Exception ex) { backgroundThreadException = ex; } finally { mre.Set(); } }); target.Initialize(null); t.Start(); Thread.Sleep(50); List<Exception> exceptions = new List<Exception>(); target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); target.WriteAsyncLogEvents(new[] { LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), }); target.Flush(exceptions.Add); target.Close(); exceptions.ForEach(Assert.Null); mre.WaitOne(); if (backgroundThreadException != null) { Assert.True(false, backgroundThreadException.ToString()); } } [Fact] public void GivenNullEvents_WhenWriteAsyncLogEvents_ThenNoExceptionAreThrown() { var target = new MyTarget(); try { target.WriteAsyncLogEvents(null); } catch (Exception e) { Assert.True(false, "Exception thrown: " + e); } } [Fact] public void WriteFormattedStringEvent_WithNullArgument() { var target = new MyTarget(); SimpleConfigurator.ConfigureForTargetLogging(target); var logger = LogManager.GetLogger("WriteFormattedStringEvent_EventWithNullArguments"); string t = null; logger.Info("Testing null:{0}", t); Assert.Equal(1, target.WriteCount); } public class MyTarget : Target { private int inBlockingOperation; public int InitializeCount { get; set; } public int CloseCount { get; set; } public int FlushCount { get; set; } public int WriteCount { get; set; } public int WriteCount2 { get; set; } public bool ThrowOnInitialize { get; set; } public int WriteCount3 { get; set; } public MyTarget() : base() { } public MyTarget(string name) : this() { Name = name; } protected override void InitializeTarget() { if (ThrowOnInitialize) { throw new InvalidOperationException("Init error."); } Assert.Equal(0, inBlockingOperation); InitializeCount++; base.InitializeTarget(); } protected override void CloseTarget() { Assert.Equal(0, inBlockingOperation); CloseCount++; base.CloseTarget(); } protected override void FlushAsync(AsyncContinuation asyncContinuation) { Assert.Equal(0, inBlockingOperation); FlushCount++; base.FlushAsync(asyncContinuation); } protected override void Write(LogEventInfo logEvent) { Assert.Equal(0, inBlockingOperation); WriteCount++; } protected override void Write(AsyncLogEventInfo logEvent) { Assert.Equal(0, inBlockingOperation); WriteCount2++; base.Write(logEvent); } protected override void Write(IList<AsyncLogEventInfo> logEvents) { Assert.Equal(0, inBlockingOperation); WriteCount3++; base.Write(logEvents); } public void BlockingOperation(int millisecondsTimeout) { lock (SyncRoot) { inBlockingOperation++; Thread.Sleep(millisecondsTimeout); inBlockingOperation--; } } } [Fact] public void WrongMyTargetShouldNotThrowExceptionWhenThrowExceptionsIsFalse() { using (new NoThrowNLogExceptions()) { var target = new WrongMyTarget(); SimpleConfigurator.ConfigureForTargetLogging(target); var logger = LogManager.GetLogger("WrongMyTargetShouldThrowException"); logger.Info("Testing"); } } public class WrongMyTarget : Target { public WrongMyTarget() : base() { } public WrongMyTarget(string name) : this() { Name = name; } /// <summary> /// Initializes the target. Can be used by inheriting classes /// to initialize logging. /// </summary> protected override void InitializeTarget() { //base.InitializeTarget() should be called } } } }
// // Copyright 2014-2015 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // Licensed under the Amazon Software License (the "License"). // You may not use this file except in compliance with the // License. A copy of the License is located at // // http://aws.amazon.com/asl/ // // or in the "license" file accompanying this file. This file is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, express or implied. See the License // for the specific language governing permissions and // limitations under the License. // /* * Do not modify this file. This file is generated from the dynamodb-2012-08-10.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.DynamoDBv2.Model { /// <summary> /// Represents the properties of a table. /// </summary> public partial class TableDescription { private List<AttributeDefinition> _attributeDefinitions = new List<AttributeDefinition>(); private DateTime? _creationDateTime; private List<GlobalSecondaryIndexDescription> _globalSecondaryIndexes = new List<GlobalSecondaryIndexDescription>(); private long? _itemCount; private List<KeySchemaElement> _keySchema = new List<KeySchemaElement>(); private List<LocalSecondaryIndexDescription> _localSecondaryIndexes = new List<LocalSecondaryIndexDescription>(); private ProvisionedThroughputDescription _provisionedThroughput; private string _tableName; private long? _tableSizeBytes; private TableStatus _tableStatus; /// <summary> /// Empty constructor used to set properties independently even when a simple constructor is available /// </summary> public TableDescription() { } /// <summary> /// Gets and sets the property AttributeDefinitions. /// <para> /// An array of <i>AttributeDefinition</i> objects. Each of these objects describes one /// attribute in the table and index key schema. /// </para> /// /// <para> /// Each <i>AttributeDefinition</i> object in this array is composed of: /// </para> /// <ul> <li> /// <para> /// <i>AttributeName</i> - The name of the attribute. /// </para> /// </li> <li> /// <para> /// <i>AttributeType</i> - The data type for the attribute. /// </para> /// </li> </ul> /// </summary> public List<AttributeDefinition> AttributeDefinitions { get { return this._attributeDefinitions; } set { this._attributeDefinitions = value; } } // Check to see if AttributeDefinitions property is set internal bool IsSetAttributeDefinitions() { return this._attributeDefinitions != null && this._attributeDefinitions.Count > 0; } /// <summary> /// Gets and sets the property CreationDateTime. /// <para> /// The date and time when the table was created, in <a href="http://www.epochconverter.com/">UNIX /// epoch time</a> format. /// </para> /// </summary> public DateTime CreationDateTime { get { return this._creationDateTime.GetValueOrDefault(); } set { this._creationDateTime = value; } } // Check to see if CreationDateTime property is set internal bool IsSetCreationDateTime() { return this._creationDateTime.HasValue; } /// <summary> /// Gets and sets the property GlobalSecondaryIndexes. /// <para> /// The global secondary indexes, if any, on the table. Each index is scoped to a given /// hash key value. Each element is composed of: /// </para> /// <ul> <li> /// <para> /// <i>Backfilling</i> - If true, then the index is currently in the backfilling phase. /// Backfilling occurs only when a new global secondary index is added to the table; it /// is the process by which DynamoDB populates the new index with data from the table. /// (This attribute does not appear for indexes that were created during a <i>CreateTable</i> /// operation.) /// </para> /// </li> <li> /// <para> /// <i>IndexName</i> - The name of the global secondary index. /// </para> /// </li> <li> /// <para> /// <i>IndexSizeBytes</i> - The total size of the global secondary index, in bytes. DynamoDB /// updates this value approximately every six hours. Recent changes might not be reflected /// in this value. /// </para> /// </li> <li> /// <para> /// <i>IndexStatus</i> - The current status of the global secondary index: /// </para> /// <ul> <li> /// <para> /// <i>CREATING</i> - The index is being created. /// </para> /// </li> <li> /// <para> /// <i>UPDATING</i> - The index is being updated. /// </para> /// </li> <li> /// <para> /// <i>DELETING</i> - The index is being deleted. /// </para> /// </li> <li> /// <para> /// <i>ACTIVE</i> - The index is ready for use. /// </para> /// </li> </ul> </li> <li> /// <para> /// <i>ItemCount</i> - The number of items in the global secondary index. DynamoDB updates /// this value approximately every six hours. Recent changes might not be reflected in /// this value. /// </para> /// </li> <li> /// <para> /// <i>KeySchema</i> - Specifies the complete index key schema. The attribute names in /// the key schema must be between 1 and 255 characters (inclusive). The key schema must /// begin with the same hash key attribute as the table. /// </para> /// </li> <li> /// <para> /// <i>Projection</i> - Specifies attributes that are copied (projected) from the table /// into the index. These are in addition to the primary key attributes and index key /// attributes, which are automatically projected. Each attribute specification is composed /// of: /// </para> /// <ul> <li> /// <para> /// <i>ProjectionType</i> - One of the following: /// </para> /// <ul> <li> /// <para> /// <code>KEYS_ONLY</code> - Only the index and primary keys are projected into the index. /// </para> /// </li> <li> /// <para> /// <code>INCLUDE</code> - Only the specified table attributes are projected into the /// index. The list of projected attributes are in <i>NonKeyAttributes</i>. /// </para> /// </li> <li> /// <para> /// <code>ALL</code> - All of the table attributes are projected into the index. /// </para> /// </li> </ul> </li> <li> /// <para> /// <i>NonKeyAttributes</i> - A list of one or more non-key attribute names that are projected /// into the secondary index. The total count of attributes provided in <i>NonKeyAttributes</i>, /// summed across all of the secondary indexes, must not exceed 20. If you project the /// same attribute into two different indexes, this counts as two distinct attributes /// when determining the total. /// </para> /// </li> </ul> </li> <li> /// <para> /// <i>ProvisionedThroughput</i> - The provisioned throughput settings for the global /// secondary index, consisting of read and write capacity units, along with data about /// increases and decreases. /// </para> /// </li> </ul> /// <para> /// If the table is in the <code>DELETING</code> state, no information about indexes will /// be returned. /// </para> /// </summary> public List<GlobalSecondaryIndexDescription> GlobalSecondaryIndexes { get { return this._globalSecondaryIndexes; } set { this._globalSecondaryIndexes = value; } } // Check to see if GlobalSecondaryIndexes property is set internal bool IsSetGlobalSecondaryIndexes() { return this._globalSecondaryIndexes != null && this._globalSecondaryIndexes.Count > 0; } /// <summary> /// Gets and sets the property ItemCount. /// <para> /// The number of items in the specified table. DynamoDB updates this value approximately /// every six hours. Recent changes might not be reflected in this value. /// </para> /// </summary> public long ItemCount { get { return this._itemCount.GetValueOrDefault(); } set { this._itemCount = value; } } // Check to see if ItemCount property is set internal bool IsSetItemCount() { return this._itemCount.HasValue; } /// <summary> /// Gets and sets the property KeySchema. /// <para> /// The primary key structure for the table. Each <i>KeySchemaElement</i> consists of: /// </para> /// <ul> <li> /// <para> /// <i>AttributeName</i> - The name of the attribute. /// </para> /// </li> <li> /// <para> /// <i>KeyType</i> - The key type for the attribute. Can be either <code>HASH</code> or /// <code>RANGE</code>. /// </para> /// </li> </ul> /// <para> /// For more information about primary keys, see <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html#DataModelPrimaryKey">Primary /// Key</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// </summary> public List<KeySchemaElement> KeySchema { get { return this._keySchema; } set { this._keySchema = value; } } // Check to see if KeySchema property is set internal bool IsSetKeySchema() { return this._keySchema != null && this._keySchema.Count > 0; } /// <summary> /// Gets and sets the property LocalSecondaryIndexes. /// <para> /// Represents one or more local secondary indexes on the table. Each index is scoped /// to a given hash key value. Tables with one or more local secondary indexes are subject /// to an item collection size limit, where the amount of data within a given item collection /// cannot exceed 10 GB. Each element is composed of: /// </para> /// <ul> <li> /// <para> /// <i>IndexName</i> - The name of the local secondary index. /// </para> /// </li> <li> /// <para> /// <i>KeySchema</i> - Specifies the complete index key schema. The attribute names in /// the key schema must be between 1 and 255 characters (inclusive). The key schema must /// begin with the same hash key attribute as the table. /// </para> /// </li> <li> /// <para> /// <i>Projection</i> - Specifies attributes that are copied (projected) from the table /// into the index. These are in addition to the primary key attributes and index key /// attributes, which are automatically projected. Each attribute specification is composed /// of: /// </para> /// <ul> <li> /// <para> /// <i>ProjectionType</i> - One of the following: /// </para> /// <ul> <li> /// <para> /// <code>KEYS_ONLY</code> - Only the index and primary keys are projected into the index. /// </para> /// </li> <li> /// <para> /// <code>INCLUDE</code> - Only the specified table attributes are projected into the /// index. The list of projected attributes are in <i>NonKeyAttributes</i>. /// </para> /// </li> <li> /// <para> /// <code>ALL</code> - All of the table attributes are projected into the index. /// </para> /// </li> </ul> </li> <li> /// <para> /// <i>NonKeyAttributes</i> - A list of one or more non-key attribute names that are projected /// into the secondary index. The total count of attributes provided in <i>NonKeyAttributes</i>, /// summed across all of the secondary indexes, must not exceed 20. If you project the /// same attribute into two different indexes, this counts as two distinct attributes /// when determining the total. /// </para> /// </li> </ul> </li> <li> /// <para> /// <i>IndexSizeBytes</i> - Represents the total size of the index, in bytes. DynamoDB /// updates this value approximately every six hours. Recent changes might not be reflected /// in this value. /// </para> /// </li> <li> /// <para> /// <i>ItemCount</i> - Represents the number of items in the index. DynamoDB updates this /// value approximately every six hours. Recent changes might not be reflected in this /// value. /// </para> /// </li> </ul> /// <para> /// If the table is in the <code>DELETING</code> state, no information about indexes will /// be returned. /// </para> /// </summary> public List<LocalSecondaryIndexDescription> LocalSecondaryIndexes { get { return this._localSecondaryIndexes; } set { this._localSecondaryIndexes = value; } } // Check to see if LocalSecondaryIndexes property is set internal bool IsSetLocalSecondaryIndexes() { return this._localSecondaryIndexes != null && this._localSecondaryIndexes.Count > 0; } /// <summary> /// Gets and sets the property ProvisionedThroughput. /// <para> /// The provisioned throughput settings for the table, consisting of read and write capacity /// units, along with data about increases and decreases. /// </para> /// </summary> public ProvisionedThroughputDescription ProvisionedThroughput { get { return this._provisionedThroughput; } set { this._provisionedThroughput = value; } } // Check to see if ProvisionedThroughput property is set internal bool IsSetProvisionedThroughput() { return this._provisionedThroughput != null; } /// <summary> /// Gets and sets the property TableName. /// <para> /// The name of the table. /// </para> /// </summary> public string TableName { get { return this._tableName; } set { this._tableName = value; } } // Check to see if TableName property is set internal bool IsSetTableName() { return this._tableName != null; } /// <summary> /// Gets and sets the property TableSizeBytes. /// <para> /// The total size of the specified table, in bytes. DynamoDB updates this value approximately /// every six hours. Recent changes might not be reflected in this value. /// </para> /// </summary> public long TableSizeBytes { get { return this._tableSizeBytes.GetValueOrDefault(); } set { this._tableSizeBytes = value; } } // Check to see if TableSizeBytes property is set internal bool IsSetTableSizeBytes() { return this._tableSizeBytes.HasValue; } /// <summary> /// Gets and sets the property TableStatus. /// <para> /// The current state of the table: /// </para> /// <ul> <li> /// <para> /// <i>CREATING</i> - The table is being created. /// </para> /// </li> <li> /// <para> /// <i>UPDATING</i> - The table is being updated. /// </para> /// </li> <li> /// <para> /// <i>DELETING</i> - The table is being deleted. /// </para> /// </li> <li> /// <para> /// <i>ACTIVE</i> - The table is ready for use. /// </para> /// </li> </ul> /// </summary> public TableStatus TableStatus { get { return this._tableStatus; } set { this._tableStatus = value; } } // Check to see if TableStatus property is set internal bool IsSetTableStatus() { return this._tableStatus != null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Authentication; using System.Threading.Tasks; using System.Web; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace RedditSharp.Things { public class Post : VotableThing { private const string CommentUrl = "/api/comment"; private const string RemoveUrl = "/api/remove"; private const string DelUrl = "/api/del"; private const string GetCommentsUrl = "/comments/{0}.json"; private const string ApproveUrl = "/api/approve"; private const string EditUserTextUrl = "/api/editusertext"; private const string HideUrl = "/api/hide"; private const string UnhideUrl = "/api/unhide"; private const string SetFlairUrl = "/r/{0}/api/flair"; private const string MarkNSFWUrl = "/api/marknsfw"; private const string UnmarkNSFWUrl = "/api/unmarknsfw"; private const string ContestModeUrl = "/api/set_contest_mode"; [JsonIgnore] private Reddit Reddit { get; set; } [JsonIgnore] private IWebAgent WebAgent { get; set; } public Post Init(Reddit reddit, JToken post, IWebAgent webAgent) { CommonInit(reddit, post, webAgent); JsonConvert.PopulateObject(post["data"].ToString(), this, reddit.JsonSerializerSettings); return this; } public async Task<Post> InitAsync(Reddit reddit, JToken post, IWebAgent webAgent) { CommonInit(reddit, post, webAgent); await Task.Factory.StartNew(() => JsonConvert.PopulateObject(post["data"].ToString(), this, reddit.JsonSerializerSettings)); return this; } private void CommonInit(Reddit reddit, JToken post, IWebAgent webAgent) { base.Init(reddit, webAgent, post); Reddit = reddit; WebAgent = webAgent; } [JsonProperty("author")] public string AuthorName { get; set; } [JsonIgnore] public RedditUser Author { get { return Reddit.GetUser(AuthorName); } } public Comment[] Comments { get { return ListComments().ToArray(); } } [JsonProperty("approved_by")] public string ApprovedBy { get; set; } [JsonProperty("author_flair_css_class")] public string AuthorFlairCssClass { get; set; } [JsonProperty("author_flair_text")] public string AuthorFlairText { get; set; } [JsonProperty("banned_by")] public string BannedBy { get; set; } [JsonProperty("domain")] public string Domain { get; set; } [JsonProperty("edited")] public bool Edited { get; set; } [JsonProperty("is_self")] public bool IsSelfPost { get; set; } [JsonProperty("link_flair_css_class")] public string LinkFlairCssClass { get; set; } [JsonProperty("link_flair_text")] public string LinkFlairText { get; set; } [JsonProperty("num_comments")] public int CommentCount { get; set; } [JsonProperty("over_18")] public bool NSFW { get; set; } [JsonProperty("permalink")] [JsonConverter(typeof(UrlParser))] public Uri Permalink { get; set; } [JsonProperty("score")] public int Score { get; set; } [JsonProperty("selftext")] public string SelfText { get; set; } [JsonProperty("selftext_html")] public string SelfTextHtml { get; set; } [JsonProperty("thumbnail")] [JsonConverter(typeof(UrlParser))] public Uri Thumbnail { get; set; } [JsonProperty("title")] public string Title { get; set; } [JsonProperty("subreddit")] public string SubredditName { get; set; } [JsonIgnore] public Subreddit Subreddit { get { return Reddit.GetSubreddit("/r/" + SubredditName); } } [JsonProperty("url")] [JsonConverter(typeof(UrlParser))] public Uri Url { get; set; } [JsonProperty("num_reports")] public int? Reports { get; set; } public Comment Comment(string message) { if (Reddit.User == null) throw new AuthenticationException("No user logged in."); var request = WebAgent.CreatePost(CommentUrl); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { text = message, thing_id = FullName, uh = Reddit.User.Modhash, api_type = "json" }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); var json = JObject.Parse(data); if (json["json"]["ratelimit"] != null) throw new RateLimitException(TimeSpan.FromSeconds(json["json"]["ratelimit"].ValueOrDefault<double>())); return new Comment().Init(Reddit, json["json"]["data"]["things"][0], WebAgent, this); } private string SimpleAction(string endpoint) { if (Reddit.User == null) throw new AuthenticationException("No user logged in."); var request = WebAgent.CreatePost(endpoint); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { id = FullName, uh = Reddit.User.Modhash }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); return data; } private string SimpleActionToggle(string endpoint, bool value) { if (Reddit.User == null) throw new AuthenticationException("No user logged in."); var request = WebAgent.CreatePost(endpoint); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { id = FullName, state = value, uh = Reddit.User.Modhash }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); return data; } public void Approve() { var data = SimpleAction(ApproveUrl); } public void Remove() { RemoveImpl(false); } public void RemoveSpam() { RemoveImpl(true); } private void RemoveImpl(bool spam) { var request = WebAgent.CreatePost(RemoveUrl); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { id = FullName, spam = spam, uh = Reddit.User.Modhash }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); } public void Del() { var data = SimpleAction(DelUrl); } public void Hide() { var data = SimpleAction(HideUrl); } public void Unhide() { var data = SimpleAction(UnhideUrl); } public void MarkNSFW() { var data = SimpleAction(MarkNSFWUrl); } public void UnmarkNSFW() { var data = SimpleAction(UnmarkNSFWUrl); } public void ContestMode(bool state) { var data = SimpleActionToggle(ContestModeUrl, state); } #region Obsolete Getter Methods [Obsolete("Use Comments property instead")] public Comment[] GetComments() { return Comments; } #endregion Obsolete Getter Methods /// <summary> /// Replaces the text in this post with the input text. /// </summary> /// <param name="newText">The text to replace the post's contents</param> public void EditText(string newText) { if (Reddit.User == null) throw new Exception("No user logged in."); if (!IsSelfPost) throw new Exception("Submission to edit is not a self-post."); var request = WebAgent.CreatePost(EditUserTextUrl); WebAgent.WritePostBody(request.GetRequestStream(), new { api_type = "json", text = newText, thing_id = FullName, uh = Reddit.User.Modhash }); var response = request.GetResponse(); var result = WebAgent.GetResponseString(response.GetResponseStream()); JToken json = JToken.Parse(result); if (json["json"].ToString().Contains("\"errors\": []")) SelfText = newText; else throw new Exception("Error editing text."); } public void Update() { JToken post = Reddit.GetToken(this.Url); JsonConvert.PopulateObject(post["data"].ToString(), this, Reddit.JsonSerializerSettings); } public void SetFlair(string flairText, string flairClass) { if (Reddit.User == null) throw new Exception("No user logged in."); var request = WebAgent.CreatePost(string.Format(SetFlairUrl,SubredditName)); WebAgent.WritePostBody(request.GetRequestStream(), new { api_type = "json", css_class = flairClass, link = FullName, name = Reddit.User.Name, text = flairText, uh = Reddit.User.Modhash }); var response = request.GetResponse(); var result = WebAgent.GetResponseString(response.GetResponseStream()); var json = JToken.Parse(result); LinkFlairText = flairText; } public List<Comment> ListComments(int? limit = null) { var url = string.Format(GetCommentsUrl, Id); if (limit.HasValue) { var query = HttpUtility.ParseQueryString(string.Empty); query.Add("limit", limit.Value.ToString()); url = string.Format("{0}?{1}", url, query); } var request = WebAgent.CreateGet(url); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); var json = JArray.Parse(data); var postJson = json.Last()["data"]["children"]; var comments = new List<Comment>(); foreach (var comment in postJson) { comments.Add(new Comment().Init(Reddit, comment, WebAgent, this)); } return comments; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="TrackballDecorator.cs" company=""> // // </copyright> // <summary> // The trackball decorator. // </summary> // -------------------------------------------------------------------------------------------------------------------- // IAddChild, ContentPropertyAttribute namespace Microsoft._3DTools { using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Media3D; /// <summary> /// The trackball decorator. /// </summary> public class TrackballDecorator : Viewport3DDecorator { /// <summary> /// The _event source. /// </summary> private readonly Border _eventSource; /// <summary> /// The _rotation. /// </summary> private readonly AxisAngleRotation3D _rotation = new AxisAngleRotation3D(); /// <summary> /// The _scale. /// </summary> private readonly ScaleTransform3D _scale = new ScaleTransform3D(); /// <summary> /// The _transform. /// </summary> private readonly Transform3DGroup _transform; // -------------------------------------------------------------------- // Private data // -------------------------------------------------------------------- /// <summary> /// The _previous position 2 d. /// </summary> private Point _previousPosition2D; /// <summary> /// The _previous position 3 d. /// </summary> private Vector3D _previousPosition3D = new Vector3D(0, 0, 1); /// <summary> /// Initializes a new instance of the <see cref="TrackballDecorator"/> class. /// </summary> public TrackballDecorator() { // the transform that will be applied to the viewport 3d's camera this._transform = new Transform3DGroup(); this._transform.Children.Add(this._scale); this._transform.Children.Add(new RotateTransform3D(this._rotation)); // used so that we always get events while activity occurs within // the viewport3D this._eventSource = new Border { Background = Brushes.Transparent }; this.PreViewportChildren.Add(this._eventSource); } /// <summary> /// A transform to move the camera or scene to the trackball's /// current orientation and scale. /// </summary> public Transform3D Transform { get { return this._transform; } } /// <summary> /// The track. /// </summary> /// <param name="currentPosition"> /// The current position. /// </param> private void Track(Point currentPosition) { var currentPosition3D = this.ProjectToTrackball(this.ActualWidth, this.ActualHeight, currentPosition); var axis = Vector3D.CrossProduct(this._previousPosition3D, currentPosition3D); var angle = Vector3D.AngleBetween(this._previousPosition3D, currentPosition3D); // quaterion will throw if this happens - sometimes we can get 3D positions that // are very similar, so we avoid the throw by doing this check and just ignoring // the event if (axis.Length == 0) { return; } var delta = new Quaternion(axis, -angle); // Get the current orientantion from the RotateTransform3D var r = this._rotation; var q = new Quaternion(this._rotation.Axis, this._rotation.Angle); // Compose the delta with the previous orientation q *= delta; // Write the new orientation back to the Rotation3D this._rotation.Axis = q.Axis; this._rotation.Angle = q.Angle; this._previousPosition3D = currentPosition3D; } /// <summary> /// The project to trackball. /// </summary> /// <param name="width"> /// The width. /// </param> /// <param name="height"> /// The height. /// </param> /// <param name="point"> /// The point. /// </param> /// <returns> /// The <see cref="Vector3D"/>. /// </returns> private Vector3D ProjectToTrackball(double width, double height, Point point) { var x = point.X / (width / 2); // Scale so bounds map to [0,0] - [2,2] var y = point.Y / (height / 2); x = x - 1; // Translate 0,0 to the center y = 1 - y; // Flip so +Y is up instead of down var z2 = 1 - x * x - y * y; // z^2 = 1 - x^2 - y^2 var z = z2 > 0 ? Math.Sqrt(z2) : 0; return new Vector3D(x, y, z); } /// <summary> /// The zoom. /// </summary> /// <param name="currentPosition"> /// The current position. /// </param> private void Zoom(Point currentPosition) { var yDelta = currentPosition.Y - this._previousPosition2D.Y; var scale = Math.Exp(yDelta / 100); // e^(yDelta/100) is fairly arbitrary. this._scale.ScaleX *= scale; this._scale.ScaleY *= scale; this._scale.ScaleZ *= scale; } #region Event Handling /// <summary> /// The on mouse down. /// </summary> /// <param name="e"> /// The e. /// </param> protected override void OnMouseDown(MouseButtonEventArgs e) { base.OnMouseDown(e); this._previousPosition2D = e.GetPosition(this); this._previousPosition3D = this.ProjectToTrackball( this.ActualWidth, this.ActualHeight, this._previousPosition2D); if (Mouse.Captured == null) { Mouse.Capture(this, CaptureMode.Element); } } /// <summary> /// The on mouse up. /// </summary> /// <param name="e"> /// The e. /// </param> protected override void OnMouseUp(MouseButtonEventArgs e) { base.OnMouseUp(e); if (this.IsMouseCaptured) { Mouse.Capture(this, CaptureMode.None); } } /// <summary> /// The on mouse move. /// </summary> /// <param name="e"> /// The e. /// </param> protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (this.IsMouseCaptured) { var currentPosition = e.GetPosition(this); // avoid any zero axis conditions if (currentPosition == this._previousPosition2D) { return; } // Prefer tracking to zooming if both buttons are pressed. if (e.LeftButton == MouseButtonState.Pressed) { this.Track(currentPosition); } else if (e.RightButton == MouseButtonState.Pressed) { this.Zoom(currentPosition); } this._previousPosition2D = currentPosition; var viewport3D = this.Viewport3D; if (viewport3D != null) { if (viewport3D.Camera != null) { if (viewport3D.Camera.IsFrozen) { viewport3D.Camera = viewport3D.Camera.Clone(); } if (viewport3D.Camera.Transform != this._transform) { viewport3D.Camera.Transform = this._transform; } } } } } #endregion Event Handling } }
#if OS_WINDOWS using Microsoft.VisualStudio.Services.Agent.Util; using Microsoft.Win32; using System; using System.Collections; using System.ComponentModel; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; using System.Security.Principal; using System.ServiceProcess; using System.Threading; namespace Microsoft.VisualStudio.Services.Agent.Listener.Configuration { [ServiceLocator(Default = typeof(NativeWindowsServiceHelper))] public interface INativeWindowsServiceHelper : IAgentService { string GetUniqueBuildGroupName(); bool LocalGroupExists(string groupName); void CreateLocalGroup(string groupName); void DeleteLocalGroup(string groupName); void AddMemberToLocalGroup(string accountName, string groupName); void GrantFullControlToGroup(string path, string groupName); void RemoveGroupFromFolderSecuritySetting(string folderPath, string groupName); bool IsUserHasLogonAsServicePrivilege(string domain, string userName); bool GrantUserLogonAsServicePrivilage(string domain, string userName); bool IsValidCredential(string domain, string userName, string logonPassword); NTAccount GetDefaultServiceAccount(); NTAccount GetDefaultAdminServiceAccount(); bool IsServiceExists(string serviceName); void InstallService(string serviceName, string serviceDisplayName, string logonAccount, string logonPassword); void UninstallService(string serviceName); void StartService(string serviceName); void StopService(string serviceName); void CreateVstsAgentRegistryKey(); void DeleteVstsAgentRegistryKey(); string GetSecurityId(string domainName, string userName); void SetAutoLogonPassword(string password); void ResetAutoLogonPassword(); bool IsRunningInElevatedMode(); void LoadUserProfile(string domain, string userName, string logonPassword, out IntPtr tokenHandle, out PROFILEINFO userProfile); void UnloadUserProfile(IntPtr tokenHandle, PROFILEINFO userProfile); bool IsValidAutoLogonCredential(string domain, string userName, string logonPassword); } public class NativeWindowsServiceHelper : AgentService, INativeWindowsServiceHelper { private const string AgentServiceLocalGroupPrefix = "VSTS_AgentService_G"; private ITerminal _term; public override void Initialize(IHostContext hostContext) { base.Initialize(hostContext); _term = hostContext.GetService<ITerminal>(); } public string GetUniqueBuildGroupName() { return AgentServiceLocalGroupPrefix + IOUtil.GetBinPathHash().Substring(0, 5); } // TODO: Make sure to remove Old agent's group and registry changes made during auto upgrade to vsts-agent. public bool LocalGroupExists(string groupName) { Trace.Entering(); bool exists = false; IntPtr bufptr; int returnCode = NetLocalGroupGetInfo(null, // computer name groupName, 1, // group info with comment out bufptr); // Win32GroupAPI.LocalGroupInfo try { switch (returnCode) { case ReturnCode.S_OK: Trace.Info($"Local group '{groupName}' exist."); exists = true; break; case ReturnCode.NERR_GroupNotFound: case ReturnCode.ERROR_NO_SUCH_ALIAS: exists = false; break; case ReturnCode.ERROR_ACCESS_DENIED: // NOTE: None of the exception thrown here are userName facing. The caller logs this exception and prints a more understandable error throw new UnauthorizedAccessException(StringUtil.Loc("AccessDenied")); default: throw new Exception(StringUtil.Loc("OperationFailed", nameof(NetLocalGroupGetInfo), returnCode)); } } finally { // we don't need to actually read the info to determine whether it exists int bufferFreeError = NetApiBufferFree(bufptr); if (bufferFreeError != 0) { Trace.Error(StringUtil.Format("Buffer free error, could not free buffer allocated, error code: {0}", bufferFreeError)); } } return exists; } public void CreateLocalGroup(string groupName) { Trace.Entering(); LocalGroupInfo groupInfo = new LocalGroupInfo(); groupInfo.Name = groupName; groupInfo.Comment = StringUtil.Format("Built-in group used by Team Foundation Server."); int returnCode = NetLocalGroupAdd(null, // computer name 1, // 1 means include comment ref groupInfo, 0); // param error number // return on success if (returnCode == ReturnCode.S_OK) { Trace.Info($"Local Group '{groupName}' created"); return; } // Error Cases switch (returnCode) { case ReturnCode.NERR_GroupExists: case ReturnCode.ERROR_ALIAS_EXISTS: Trace.Info(StringUtil.Format("Group {0} already exists", groupName)); break; case ReturnCode.ERROR_ACCESS_DENIED: throw new UnauthorizedAccessException(StringUtil.Loc("AccessDenied")); case ReturnCode.ERROR_INVALID_PARAMETER: throw new ArgumentException(StringUtil.Loc("InvalidGroupName", groupName)); default: throw new Exception(StringUtil.Loc("OperationFailed", nameof(NetLocalGroupAdd), returnCode)); } } public void DeleteLocalGroup(string groupName) { Trace.Entering(); int returnCode = NetLocalGroupDel(null, // computer name groupName); // return on success if (returnCode == ReturnCode.S_OK) { Trace.Info($"Local Group '{groupName}' deleted"); return; } // Error Cases switch (returnCode) { case ReturnCode.NERR_GroupNotFound: case ReturnCode.ERROR_NO_SUCH_ALIAS: Trace.Info(StringUtil.Format("Group {0} not exists.", groupName)); break; case ReturnCode.ERROR_ACCESS_DENIED: throw new UnauthorizedAccessException(StringUtil.Loc("AccessDenied")); default: throw new Exception(StringUtil.Loc("OperationFailed", nameof(NetLocalGroupDel), returnCode)); } } public void AddMemberToLocalGroup(string accountName, string groupName) { Trace.Entering(); LocalGroupMemberInfo memberInfo = new LocalGroupMemberInfo(); memberInfo.FullName = accountName; int returnCode = NetLocalGroupAddMembers(null, // computer name groupName, 3, // group info with fullname (vs sid) ref memberInfo, 1); //total entries // return on success if (returnCode == ReturnCode.S_OK) { Trace.Info($"Account '{accountName}' is added to local group '{groupName}'."); return; } // Error Cases switch (returnCode) { case ReturnCode.ERROR_MEMBER_IN_ALIAS: Trace.Info(StringUtil.Format("Account {0} is already member of group {1}", accountName, groupName)); break; case ReturnCode.NERR_GroupNotFound: case ReturnCode.ERROR_NO_SUCH_ALIAS: throw new ArgumentException(StringUtil.Loc("GroupDoesNotExists", groupName)); case ReturnCode.ERROR_NO_SUCH_MEMBER: throw new ArgumentException(StringUtil.Loc("MemberDoesNotExists", accountName)); case ReturnCode.ERROR_INVALID_MEMBER: throw new ArgumentException(StringUtil.Loc("InvalidMember")); case ReturnCode.ERROR_ACCESS_DENIED: throw new UnauthorizedAccessException(StringUtil.Loc("AccessDenied")); default: throw new Exception(StringUtil.Loc("OperationFailed", nameof(NetLocalGroupAddMembers), returnCode)); } } public void GrantFullControlToGroup(string path, string groupName) { Trace.Entering(); if (IsGroupHasFullControl(path, groupName)) { Trace.Info($"Local group '{groupName}' already has full control to path '{path}'."); return; } DirectoryInfo dInfo = new DirectoryInfo(path); DirectorySecurity dSecurity = dInfo.GetAccessControl(); if (!dSecurity.AreAccessRulesCanonical) { Trace.Warning("Acls are not canonical, this may cause failure"); } dSecurity.AddAccessRule( new FileSystemAccessRule( groupName, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow)); dInfo.SetAccessControl(dSecurity); } private bool IsGroupHasFullControl(string path, string groupName) { DirectoryInfo dInfo = new DirectoryInfo(path); DirectorySecurity dSecurity = dInfo.GetAccessControl(); var allAccessRuls = dSecurity.GetAccessRules(true, true, typeof(SecurityIdentifier)).Cast<FileSystemAccessRule>(); SecurityIdentifier sid = (SecurityIdentifier)new NTAccount(groupName).Translate(typeof(SecurityIdentifier)); if (allAccessRuls.Any(x => x.IdentityReference.Value == sid.ToString() && x.AccessControlType == AccessControlType.Allow && x.FileSystemRights.HasFlag(FileSystemRights.FullControl) && x.InheritanceFlags == (InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit) && x.PropagationFlags == PropagationFlags.None)) { return true; } else { return false; } } public bool IsUserHasLogonAsServicePrivilege(string domain, string userName) { Trace.Entering(); ArgUtil.NotNullOrEmpty(userName, nameof(userName)); bool userHasPermission = false; using (LsaPolicy lsaPolicy = new LsaPolicy()) { IntPtr rightsPtr; uint count; uint result = LsaEnumerateAccountRights(lsaPolicy.Handle, GetSidBinaryFromWindows(domain, userName), out rightsPtr, out count); try { if (result == 0) { IntPtr incrementPtr = rightsPtr; for (int i = 0; i < count; i++) { LSA_UNICODE_STRING nativeRightString = Marshal.PtrToStructure<LSA_UNICODE_STRING>(incrementPtr); string rightString = Marshal.PtrToStringUni(nativeRightString.Buffer); Trace.Verbose($"Account {userName} has '{rightString}' right."); if (string.Equals(rightString, s_logonAsServiceName, StringComparison.OrdinalIgnoreCase)) { userHasPermission = true; } incrementPtr += Marshal.SizeOf(nativeRightString); } } else { Trace.Error($"Can't enumerate account rights, return code {result}."); } } finally { result = LsaFreeMemory(rightsPtr); if (result != 0) { Trace.Error(StringUtil.Format("Failed to free memory from LsaEnumerateAccountRights. Return code : {0} ", result)); } } } return userHasPermission; } public bool GrantUserLogonAsServicePrivilage(string domain, string userName) { Trace.Entering(); ArgUtil.NotNullOrEmpty(userName, nameof(userName)); using (LsaPolicy lsaPolicy = new LsaPolicy()) { // STATUS_SUCCESS == 0 uint result = LsaAddAccountRights(lsaPolicy.Handle, GetSidBinaryFromWindows(domain, userName), LogonAsServiceRights, 1); if (result == 0) { Trace.Info($"Successfully grant logon as service privilage to account '{userName}'"); return true; } else { Trace.Info($"Fail to grant logon as service privilage to account '{userName}', error code {result}."); return false; } } } public static bool IsWellKnownIdentity(String accountName) { NTAccount ntaccount = new NTAccount(accountName); SecurityIdentifier sid = (SecurityIdentifier)ntaccount.Translate(typeof(SecurityIdentifier)); SecurityIdentifier networkServiceSid = new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null); SecurityIdentifier localServiceSid = new SecurityIdentifier(WellKnownSidType.LocalServiceSid, null); SecurityIdentifier localSystemSid = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null); return sid.Equals(networkServiceSid) || sid.Equals(localServiceSid) || sid.Equals(localSystemSid); } public bool IsValidCredential(string domain, string userName, string logonPassword) { return IsValidCredentialInternal(domain, userName, logonPassword, LOGON32_LOGON_NETWORK); } public bool IsValidAutoLogonCredential(string domain, string userName, string logonPassword) { return IsValidCredentialInternal(domain, userName, logonPassword, LOGON32_LOGON_INTERACTIVE); } public NTAccount GetDefaultServiceAccount() { SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, domainSid: null); NTAccount account = sid.Translate(typeof(NTAccount)) as NTAccount; if (account == null) { throw new InvalidOperationException(StringUtil.Loc("NetworkServiceNotFound")); } return account; } public NTAccount GetDefaultAdminServiceAccount() { SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, domainSid: null); NTAccount account = sid.Translate(typeof(NTAccount)) as NTAccount; if (account == null) { throw new InvalidOperationException(StringUtil.Loc("LocalSystemAccountNotFound")); } return account; } public void RemoveGroupFromFolderSecuritySetting(string folderPath, string groupName) { DirectoryInfo dInfo = new DirectoryInfo(folderPath); if (dInfo.Exists) { DirectorySecurity dSecurity = dInfo.GetAccessControl(); var allAccessRuls = dSecurity.GetAccessRules(true, true, typeof(SecurityIdentifier)).Cast<FileSystemAccessRule>(); SecurityIdentifier sid = (SecurityIdentifier)new NTAccount(groupName).Translate(typeof(SecurityIdentifier)); foreach (FileSystemAccessRule ace in allAccessRuls) { if (String.Equals(sid.ToString(), ace.IdentityReference.Value, StringComparison.OrdinalIgnoreCase)) { dSecurity.RemoveAccessRuleSpecific(ace); } } dInfo.SetAccessControl(dSecurity); } } public bool IsServiceExists(string serviceName) { Trace.Entering(); ServiceController service = ServiceController.GetServices().FirstOrDefault(x => x.ServiceName.Equals(serviceName, StringComparison.OrdinalIgnoreCase)); return service != null; } public void InstallService(string serviceName, string serviceDisplayName, string logonAccount, string logonPassword) { Trace.Entering(); string agentServiceExecutable = Path.Combine(IOUtil.GetBinPath(), WindowsServiceControlManager.WindowsServiceControllerName); IntPtr scmHndl = IntPtr.Zero; IntPtr svcHndl = IntPtr.Zero; IntPtr tmpBuf = IntPtr.Zero; IntPtr svcLock = IntPtr.Zero; try { //invoke the service with special argument, that tells it to register an event log trace source (need to run as an admin) using (var processInvoker = HostContext.CreateService<IProcessInvoker>()) { processInvoker.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message) { _term.WriteLine(message.Data); }; processInvoker.ErrorDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message) { _term.WriteLine(message.Data); }; processInvoker.ExecuteAsync(workingDirectory: string.Empty, fileName: agentServiceExecutable, arguments: "init", environment: null, requireExitCodeZero: true, cancellationToken: CancellationToken.None).GetAwaiter().GetResult(); } Trace.Verbose(StringUtil.Format("Trying to open SCManager.")); scmHndl = OpenSCManager(null, null, ServiceManagerRights.AllAccess); if (scmHndl.ToInt64() <= 0) { throw new Exception(StringUtil.Loc("FailedToOpenSCM")); } Trace.Verbose(StringUtil.Format("Opened SCManager. Trying to create service {0}", serviceName)); svcHndl = CreateService(scmHndl, serviceName, serviceDisplayName, ServiceRights.AllAccess, SERVICE_WIN32_OWN_PROCESS, ServiceBootFlag.AutoStart, ServiceError.Normal, agentServiceExecutable, null, IntPtr.Zero, null, logonAccount, logonPassword); if (svcHndl.ToInt64() <= 0) { throw new InvalidOperationException(StringUtil.Loc("OperationFailed", nameof(CreateService), GetLastError())); } _term.WriteLine(StringUtil.Loc("ServiceInstalled", serviceName)); //set recovery option to restart on failure. ArrayList failureActions = new ArrayList(); //first failure, we will restart the service right away. failureActions.Add(new FailureAction(RecoverAction.Restart, 0)); //second failure, we will restart the service after 1 min. failureActions.Add(new FailureAction(RecoverAction.Restart, 60000)); //subsequent failures, we will restart the service after 1 min failureActions.Add(new FailureAction(RecoverAction.Restart, 60000)); // Lock the Service Database svcLock = LockServiceDatabase(scmHndl); if (svcLock.ToInt64() <= 0) { throw new Exception(StringUtil.Loc("FailedToLockServiceDB")); } int[] actions = new int[failureActions.Count * 2]; int currInd = 0; foreach (FailureAction fa in failureActions) { actions[currInd] = (int)fa.Type; actions[++currInd] = fa.Delay; currInd++; } // Need to pack 8 bytes per struct tmpBuf = Marshal.AllocHGlobal(failureActions.Count * 8); // Move array into marshallable pointer Marshal.Copy(actions, 0, tmpBuf, failureActions.Count * 2); // Set the SERVICE_FAILURE_ACTIONS struct SERVICE_FAILURE_ACTIONS sfa = new SERVICE_FAILURE_ACTIONS(); sfa.cActions = failureActions.Count; sfa.dwResetPeriod = SERVICE_NO_CHANGE; sfa.lpCommand = String.Empty; sfa.lpRebootMsg = String.Empty; sfa.lpsaActions = tmpBuf.ToInt64(); // Call the ChangeServiceFailureActions() abstraction of ChangeServiceConfig2() bool result = ChangeServiceFailureActions(svcHndl, SERVICE_CONFIG_FAILURE_ACTIONS, ref sfa); //Check the return if (!result) { int lastErrorCode = (int)GetLastError(); Exception win32exception = new Win32Exception(lastErrorCode); if (lastErrorCode == ReturnCode.ERROR_ACCESS_DENIED) { throw new SecurityException(StringUtil.Loc("AccessDeniedSettingRecoveryOption"), win32exception); } else { throw win32exception; } } else { _term.WriteLine(StringUtil.Loc("ServiceRecoveryOptionSet", serviceName)); } _term.WriteLine(StringUtil.Loc("ServiceConfigured", serviceName)); } finally { if (scmHndl != IntPtr.Zero) { // Unlock the service database if (svcLock != IntPtr.Zero) { UnlockServiceDatabase(svcLock); svcLock = IntPtr.Zero; } // Close the service control manager handle CloseServiceHandle(scmHndl); scmHndl = IntPtr.Zero; } // Close the service handle if (svcHndl != IntPtr.Zero) { CloseServiceHandle(svcHndl); svcHndl = IntPtr.Zero; } // Free the memory if (tmpBuf != IntPtr.Zero) { Marshal.FreeHGlobal(tmpBuf); tmpBuf = IntPtr.Zero; } } } public void UninstallService(string serviceName) { Trace.Entering(); Trace.Verbose(StringUtil.Format("Trying to open SCManager.")); IntPtr scmHndl = OpenSCManager(null, null, ServiceManagerRights.Connect); if (scmHndl.ToInt64() <= 0) { throw new Exception(StringUtil.Loc("FailedToOpenSCManager")); } try { Trace.Verbose(StringUtil.Format("Opened SCManager. query installed service {0}", serviceName)); IntPtr serviceHndl = OpenService(scmHndl, serviceName, ServiceRights.StandardRightsRequired | ServiceRights.Stop | ServiceRights.QueryStatus); if (serviceHndl == IntPtr.Zero) { int lastError = Marshal.GetLastWin32Error(); throw new Win32Exception(lastError); } try { Trace.Info(StringUtil.Format("Trying to delete service {0}", serviceName)); int result = DeleteService(serviceHndl); if (result == 0) { result = Marshal.GetLastWin32Error(); throw new Win32Exception(result, StringUtil.Loc("CouldNotRemoveService", serviceName)); } Trace.Info("successfully removed the service"); } finally { CloseServiceHandle(serviceHndl); } } finally { CloseServiceHandle(scmHndl); } } public void StartService(string serviceName) { Trace.Entering(); try { ServiceController service = ServiceController.GetServices().FirstOrDefault(x => x.ServiceName.Equals(serviceName, StringComparison.OrdinalIgnoreCase)); if (service != null) { service.Start(); _term.WriteLine(StringUtil.Loc("ServiceStartedSuccessfully", serviceName)); } else { throw new InvalidOperationException(StringUtil.Loc("CanNotFindService", serviceName)); } } catch (Exception exception) { Trace.Error(exception); _term.WriteError(StringUtil.Loc("CanNotStartService")); // This is the last step in the configuration. Even if the start failed the status of the configuration should be error // If its configured through scripts its mandatory we indicate the failure where configuration failed to start the service throw; } } public void StopService(string serviceName) { Trace.Entering(); try { ServiceController service = ServiceController.GetServices().FirstOrDefault(x => x.ServiceName.Equals(serviceName, StringComparison.OrdinalIgnoreCase)); if (service != null) { if (service.Status == ServiceControllerStatus.Running) { Trace.Info("Trying to stop the service"); service.Stop(); try { _term.WriteLine(StringUtil.Loc("WaitForServiceToStop")); service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(35)); } catch (System.ServiceProcess.TimeoutException) { throw new InvalidOperationException(StringUtil.Loc("CanNotStopService", serviceName)); } } Trace.Info("Successfully stopped the service"); } else { Trace.Info(StringUtil.Loc("CanNotFindService", serviceName)); } } catch (Exception exception) { Trace.Error(exception); _term.WriteError(StringUtil.Loc("CanNotStopService", serviceName)); // Log the exception but do not report it as error. We can try uninstalling the service and then report it as error if something goes wrong. } } public void CreateVstsAgentRegistryKey() { RegistryKey tfsKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\TeamFoundationServer\15.0", true); if (tfsKey == null) { //We could be on a machine that doesn't have TFS installed on it, create the key tfsKey = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\TeamFoundationServer\15.0"); } if (tfsKey == null) { throw new ArgumentNullException("Unable to create regiestry key: 'HKLM\\SOFTWARE\\Microsoft\\TeamFoundationServer\\15.0'"); } try { using (RegistryKey vstsAgentsKey = tfsKey.CreateSubKey("VstsAgents")) { String hash = IOUtil.GetBinPathHash(); using (RegistryKey agentKey = vstsAgentsKey.CreateSubKey(hash)) { agentKey.SetValue("InstallPath", Path.Combine(IOUtil.GetBinPath(), "Agent.Listener.exe")); } } } finally { tfsKey.Dispose(); } } public void DeleteVstsAgentRegistryKey() { RegistryKey tfsKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\TeamFoundationServer\15.0", true); if (tfsKey != null) { try { RegistryKey vstsAgentsKey = tfsKey.OpenSubKey("VstsAgents", true); if (vstsAgentsKey != null) { try { String hash = IOUtil.GetBinPathHash(); vstsAgentsKey.DeleteSubKeyTree(hash); } finally { vstsAgentsKey.Dispose(); } } } finally { tfsKey.Dispose(); } } } public string GetSecurityId(string domainName, string userName) { var account = new NTAccount(domainName, userName); var sid = account.Translate(typeof(SecurityIdentifier)); return sid != null ? sid.ToString() : null; } public void SetAutoLogonPassword(string password) { using (LsaPolicy lsaPolicy = new LsaPolicy(LSA_AccessPolicy.POLICY_CREATE_SECRET)) { lsaPolicy.SetSecretData(LsaPolicy.DefaultPassword, password); } } public void ResetAutoLogonPassword() { using (LsaPolicy lsaPolicy = new LsaPolicy(LSA_AccessPolicy.POLICY_CREATE_SECRET)) { lsaPolicy.SetSecretData(LsaPolicy.DefaultPassword, null); } } public bool IsRunningInElevatedMode() { return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator); } public void LoadUserProfile(string domain, string userName, string logonPassword, out IntPtr tokenHandle, out PROFILEINFO userProfile) { Trace.Entering(); tokenHandle = IntPtr.Zero; ArgUtil.NotNullOrEmpty(userName, nameof(userName)); if(LogonUser(userName, domain, logonPassword, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out tokenHandle) == 0) { throw new Win32Exception(Marshal.GetLastWin32Error()); } userProfile = new PROFILEINFO(); userProfile.dwSize = Marshal.SizeOf(typeof(PROFILEINFO)); userProfile.lpUserName = userName; if (!LoadUserProfile(tokenHandle, ref userProfile)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } Trace.Info($"Successfully loaded the profile for {domain}\\{userName}."); } public void UnloadUserProfile(IntPtr tokenHandle, PROFILEINFO userProfile) { Trace.Entering(); if(tokenHandle == IntPtr.Zero) { Trace.Verbose("The handle to unload user profile is not set. Returning."); } if (!UnloadUserProfile(tokenHandle, userProfile.hProfile)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } Trace.Info($"Successfully unloaded the profile for {userProfile.lpUserName}."); } private bool IsValidCredentialInternal(string domain, string userName, string logonPassword, UInt32 logonType) { Trace.Entering(); IntPtr tokenHandle = IntPtr.Zero; ArgUtil.NotNullOrEmpty(userName, nameof(userName)); Trace.Info($"Verify credential for account {userName}."); int result = LogonUser(userName, domain, logonPassword, logonType, LOGON32_PROVIDER_DEFAULT, out tokenHandle); if (tokenHandle.ToInt32() != 0) { if (!CloseHandle(tokenHandle)) { Trace.Error("Failed during CloseHandle on token from LogonUser"); } } if (result != 0) { Trace.Info($"Credential for account '{userName}' is valid."); return true; } else { Trace.Info($"Credential for account '{userName}' is invalid."); return false; } } private byte[] GetSidBinaryFromWindows(string domain, string user) { try { SecurityIdentifier sid = (SecurityIdentifier)new NTAccount(StringUtil.Format("{0}\\{1}", domain, user).TrimStart('\\')).Translate(typeof(SecurityIdentifier)); byte[] binaryForm = new byte[sid.BinaryLength]; sid.GetBinaryForm(binaryForm, 0); return binaryForm; } catch (Exception exception) { Trace.Error(exception); return null; } } // Helper class not to repeat whenever we deal with LSA* api internal class LsaPolicy : IDisposable { public IntPtr Handle { get; set; } public LsaPolicy() : this(LSA_AccessPolicy.POLICY_ALL_ACCESS) { } public LsaPolicy(LSA_AccessPolicy access) { LSA_UNICODE_STRING system = new LSA_UNICODE_STRING(); LSA_OBJECT_ATTRIBUTES attrib = new LSA_OBJECT_ATTRIBUTES() { Length = 0, RootDirectory = IntPtr.Zero, Attributes = 0, SecurityDescriptor = IntPtr.Zero, SecurityQualityOfService = IntPtr.Zero, }; IntPtr handle = IntPtr.Zero; uint hr = LsaOpenPolicy(ref system, ref attrib, (uint)access, out handle); if (hr != 0 || handle == IntPtr.Zero) { throw new Exception(StringUtil.Loc("OperationFailed", nameof(LsaOpenPolicy), hr)); } Handle = handle; } public void SetSecretData(string key, string value) { LSA_UNICODE_STRING secretData = new LSA_UNICODE_STRING(); LSA_UNICODE_STRING secretName = new LSA_UNICODE_STRING(); secretName.Buffer = Marshal.StringToHGlobalUni(key); var charSize = sizeof(char); secretName.Length = (UInt16)(key.Length * charSize); secretName.MaximumLength = (UInt16)((key.Length + 1) * charSize); if (value != null && value.Length > 0) { // Create data and key secretData.Buffer = Marshal.StringToHGlobalUni(value); secretData.Length = (UInt16)(value.Length * charSize); secretData.MaximumLength = (UInt16)((value.Length + 1) * charSize); } else { // Delete data and key secretData.Buffer = IntPtr.Zero; secretData.Length = 0; secretData.MaximumLength = 0; } uint result = LsaStorePrivateData(Handle, ref secretName, ref secretData); uint winErrorCode = LsaNtStatusToWinError(result); if (winErrorCode != 0) { throw new Exception(StringUtil.Loc("OperationFailed", nameof(LsaNtStatusToWinError), winErrorCode)); } } void IDisposable.Dispose() { // We will ignore LsaClose error LsaClose(Handle); GC.SuppressFinalize(this); } internal static string DefaultPassword = "DefaultPassword"; } internal enum LSA_AccessPolicy : long { POLICY_VIEW_LOCAL_INFORMATION = 0x00000001L, POLICY_VIEW_AUDIT_INFORMATION = 0x00000002L, POLICY_GET_PRIVATE_INFORMATION = 0x00000004L, POLICY_TRUST_ADMIN = 0x00000008L, POLICY_CREATE_ACCOUNT = 0x00000010L, POLICY_CREATE_SECRET = 0x00000020L, POLICY_CREATE_PRIVILEGE = 0x00000040L, POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080L, POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100L, POLICY_AUDIT_LOG_ADMIN = 0x00000200L, POLICY_SERVER_ADMIN = 0x00000400L, POLICY_LOOKUP_NAMES = 0x00000800L, POLICY_NOTIFICATION = 0x00001000L, POLICY_ALL_ACCESS = 0x00001FFFL } [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] public static extern uint LsaStorePrivateData( IntPtr policyHandle, ref LSA_UNICODE_STRING KeyName, ref LSA_UNICODE_STRING PrivateData ); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] public static extern uint LsaNtStatusToWinError( uint status ); private static UInt32 LOGON32_LOGON_INTERACTIVE = 2; private const UInt32 LOGON32_LOGON_NETWORK = 3; // Declaration of external pinvoke functions private static readonly string s_logonAsServiceName = "SeServiceLogonRight"; private const UInt32 LOGON32_PROVIDER_DEFAULT = 0; private const int SERVICE_WIN32_OWN_PROCESS = 0x00000010; private const int SERVICE_NO_CHANGE = -1; private const int SERVICE_CONFIG_FAILURE_ACTIONS = 0x2; // TODO Fix this. This is not yet available in coreclr (newer version?) private const int UnicodeCharSize = 2; private static LSA_UNICODE_STRING[] LogonAsServiceRights { get { return new[] { new LSA_UNICODE_STRING() { Buffer = Marshal.StringToHGlobalUni(s_logonAsServiceName), Length = (UInt16)(s_logonAsServiceName.Length * UnicodeCharSize), MaximumLength = (UInt16) ((s_logonAsServiceName.Length + 1) * UnicodeCharSize) } }; } } public struct ReturnCode { public const int S_OK = 0; public const int ERROR_ACCESS_DENIED = 5; public const int ERROR_INVALID_PARAMETER = 87; public const int ERROR_MEMBER_NOT_IN_ALIAS = 1377; // member not in a group public const int ERROR_MEMBER_IN_ALIAS = 1378; // member already exists public const int ERROR_ALIAS_EXISTS = 1379; // group already exists public const int ERROR_NO_SUCH_ALIAS = 1376; public const int ERROR_NO_SUCH_MEMBER = 1387; public const int ERROR_INVALID_MEMBER = 1388; public const int NERR_GroupNotFound = 2220; public const int NERR_GroupExists = 2223; public const int NERR_UserInGroup = 2236; public const uint STATUS_ACCESS_DENIED = 0XC0000022; //NTSTATUS error code: Access Denied } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct LocalGroupInfo { [MarshalAs(UnmanagedType.LPWStr)] public string Name; [MarshalAs(UnmanagedType.LPWStr)] public string Comment; } [StructLayout(LayoutKind.Sequential)] public struct LSA_UNICODE_STRING { public UInt16 Length; public UInt16 MaximumLength; // We need to use an IntPtr because if we wrap the Buffer with a SafeHandle-derived class, we get a failure during LsaAddAccountRights public IntPtr Buffer; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct LocalGroupMemberInfo { [MarshalAs(UnmanagedType.LPWStr)] public string FullName; } [StructLayout(LayoutKind.Sequential)] public struct LSA_OBJECT_ATTRIBUTES { public UInt32 Length; public IntPtr RootDirectory; public LSA_UNICODE_STRING ObjectName; public UInt32 Attributes; public IntPtr SecurityDescriptor; public IntPtr SecurityQualityOfService; } [StructLayout(LayoutKind.Sequential)] public struct SERVICE_FAILURE_ACTIONS { public int dwResetPeriod; public string lpRebootMsg; public string lpCommand; public int cActions; public long lpsaActions; } // Class to represent a failure action which consists of a recovery // action type and an action delay private class FailureAction { // Property to set recover action type public RecoverAction Type { get; set; } // Property to set recover action delay public int Delay { get; set; } // Constructor public FailureAction(RecoverAction actionType, int actionDelay) { Type = actionType; Delay = actionDelay; } } [Flags] public enum ServiceManagerRights { Connect = 0x0001, CreateService = 0x0002, EnumerateService = 0x0004, Lock = 0x0008, QueryLockStatus = 0x0010, ModifyBootConfig = 0x0020, StandardRightsRequired = 0xF0000, AllAccess = (StandardRightsRequired | Connect | CreateService | EnumerateService | Lock | QueryLockStatus | ModifyBootConfig) } [Flags] public enum ServiceRights { QueryConfig = 0x1, ChangeConfig = 0x2, QueryStatus = 0x4, EnumerateDependants = 0x8, Start = 0x10, Stop = 0x20, PauseContinue = 0x40, Interrogate = 0x80, UserDefinedControl = 0x100, Delete = 0x00010000, StandardRightsRequired = 0xF0000, AllAccess = (StandardRightsRequired | QueryConfig | ChangeConfig | QueryStatus | EnumerateDependants | Start | Stop | PauseContinue | Interrogate | UserDefinedControl) } public enum ServiceError { Ignore = 0x00000000, Normal = 0x00000001, Severe = 0x00000002, Critical = 0x00000003 } public enum ServiceBootFlag { Start = 0x00000000, SystemStart = 0x00000001, AutoStart = 0x00000002, DemandStart = 0x00000003, Disabled = 0x00000004 } // Enum for recovery actions (correspond to the Win32 equivalents ) private enum RecoverAction { None = 0, Restart = 1, Reboot = 2, RunCommand = 3 } [DllImport("Netapi32.dll")] private extern static int NetLocalGroupGetInfo(string servername, string groupname, int level, out IntPtr bufptr); [DllImport("Netapi32.dll")] private extern static int NetApiBufferFree(IntPtr Buffer); [DllImport("Netapi32.dll")] private extern static int NetLocalGroupAdd([MarshalAs(UnmanagedType.LPWStr)] string servername, int level, ref LocalGroupInfo buf, int parm_err); [DllImport("Netapi32.dll")] private extern static int NetLocalGroupAddMembers([MarshalAs(UnmanagedType.LPWStr)] string serverName, [MarshalAs(UnmanagedType.LPWStr)] string groupName, int level, ref LocalGroupMemberInfo buf, int totalEntries); [DllImport("Netapi32.dll")] public extern static int NetLocalGroupDel([MarshalAs(UnmanagedType.LPWStr)] string servername, [MarshalAs(UnmanagedType.LPWStr)] string groupname); [DllImport("advapi32.dll")] private static extern Int32 LsaClose(IntPtr ObjectHandle); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] private static extern uint LsaOpenPolicy( ref LSA_UNICODE_STRING SystemName, ref LSA_OBJECT_ATTRIBUTES ObjectAttributes, uint DesiredAccess, out IntPtr PolicyHandle); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] private static extern uint LsaAddAccountRights( IntPtr PolicyHandle, byte[] AccountSid, LSA_UNICODE_STRING[] UserRights, uint CountOfRights); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] public static extern uint LsaEnumerateAccountRights( IntPtr PolicyHandle, byte[] AccountSid, out IntPtr UserRights, out uint CountOfRights); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] public static extern uint LsaFreeMemory(IntPtr pBuffer); [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern int LogonUser(string userName, string domain, string password, uint logonType, uint logonProvider, out IntPtr tokenHandle); [DllImport("userenv.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern Boolean LoadUserProfile(IntPtr hToken, ref PROFILEINFO lpProfileInfo); [DllImport("userenv.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern Boolean UnloadUserProfile(IntPtr hToken, IntPtr hProfile); [DllImport("kernel32", SetLastError = true)] public static extern bool CloseHandle(IntPtr handle); [DllImport("advapi32.dll", EntryPoint = "CreateServiceA")] private static extern IntPtr CreateService( IntPtr hSCManager, string lpServiceName, string lpDisplayName, ServiceRights dwDesiredAccess, int dwServiceType, ServiceBootFlag dwStartType, ServiceError dwErrorControl, string lpBinaryPathName, string lpLoadOrderGroup, IntPtr lpdwTagId, string lpDependencies, string lp, string lpPassword); [DllImport("advapi32.dll")] public static extern IntPtr OpenSCManager(string lpMachineName, string lpDatabaseName, ServiceManagerRights dwDesiredAccess); [DllImport("advapi32.dll", SetLastError = true)] public static extern IntPtr OpenService(IntPtr hSCManager, string lpServiceName, ServiceRights dwDesiredAccess); [DllImport("advapi32.dll", SetLastError = true)] public static extern int DeleteService(IntPtr hService); [DllImport("advapi32.dll")] public static extern int CloseServiceHandle(IntPtr hSCObject); [DllImport("advapi32.dll")] public static extern IntPtr LockServiceDatabase(IntPtr hSCManager); [DllImport("advapi32.dll")] public static extern bool UnlockServiceDatabase(IntPtr hSCManager); [DllImport("advapi32.dll", EntryPoint = "ChangeServiceConfig2")] public static extern bool ChangeServiceFailureActions(IntPtr hService, int dwInfoLevel, ref SERVICE_FAILURE_ACTIONS lpInfo); [DllImport("kernel32.dll")] static extern uint GetLastError(); } [StructLayout(LayoutKind.Sequential)] public struct PROFILEINFO { public int dwSize; public int dwFlags; [MarshalAs(UnmanagedType.LPTStr)] public String lpUserName; [MarshalAs(UnmanagedType.LPTStr)] public String lpProfilePath; [MarshalAs(UnmanagedType.LPTStr)] public String lpDefaultPath; [MarshalAs(UnmanagedType.LPTStr)] public String lpServerName; [MarshalAs(UnmanagedType.LPTStr)] public String lpPolicyPath; public IntPtr hProfile; } } #endif
using System.Threading.Tasks; using Abp.Authorization; using Abp.Collections.Extensions; using Abp.Dependency; using Abp.Localization; using Abp.Runtime.Session; using Abp.Threading; namespace Abp.Application.Features { /// <summary> /// Some extension methods for <see cref="IFeatureChecker"/>. /// </summary> public static class FeatureCheckerExtensions { /// <summary> /// Gets the value of a feature by its name. This is the sync version of <see cref="IFeatureChecker.GetValueAsync(string)"/> /// /// This is a shortcut for <see cref="GetValue(IFeatureChecker, int, string)"/> that uses <see cref="IAbpSession.TenantId"/>. /// Note: This method should be used only if the TenantId can be obtained from the session. /// </summary> /// <param name="featureChecker"><see cref="IFeatureChecker"/> instance</param> /// <param name="featureName">Unique feature name</param> /// <returns>Feature's current value</returns> public static string GetValue(this IFeatureChecker featureChecker, string featureName) { return AsyncHelper.RunSync(() => featureChecker.GetValueAsync(featureName)); } /// <summary> /// Gets the value of a feature by its name. This is the sync version of <see cref="IFeatureChecker.GetValueAsync(int, string)"/> /// </summary> /// <param name="featureChecker"><see cref="IFeatureChecker"/> instance</param> /// <param name="tenantId">Tenant's Id</param> /// <param name="featureName">Unique feature name</param> /// <returns>Feature's current value</returns> public static string GetValue(this IFeatureChecker featureChecker, int tenantId, string featureName) { return AsyncHelper.RunSync(() => featureChecker.GetValueAsync(tenantId, featureName)); } /// <summary> /// Checks if a given feature is enabled. /// This should be used for boolean-value features. /// /// This is a shortcut for <see cref="IsEnabled(IFeatureChecker, int, string)"/> that uses <see cref="IAbpSession.TenantId"/>. /// Note: This method should be used only if the TenantId can be obtained from the session. /// </summary> /// <param name="featureChecker"><see cref="IFeatureChecker"/> instance</param> /// <param name="name">Unique feature name</param> /// <returns>True, if the current feature's value is "true".</returns> public static bool IsEnabled(this IFeatureChecker featureChecker, string name) { return AsyncHelper.RunSync(() => featureChecker.IsEnabledAsync(name)); } /// <summary> /// Checks if a given feature is enabled. /// This should be used for boolean-value features. /// </summary> /// <param name="featureChecker"><see cref="IFeatureChecker"/> instance</param> /// <param name="tenantId">Tenant's Id</param> /// <param name="featureName">Unique feature name</param> /// <returns>True, if the current feature's value is "true".</returns> public static bool IsEnabled(this IFeatureChecker featureChecker, int tenantId, string featureName) { return AsyncHelper.RunSync(() => featureChecker.IsEnabledAsync(tenantId, featureName)); } /// <summary> /// Used to check if one or all of the given features are enabled. /// </summary> /// <param name="featureChecker"><see cref="IFeatureChecker"/> instance</param> /// <param name="requiresAll">True, to require that all the given features are enabled. False, to require one or more.</param> /// <param name="featureNames">Names of the features</param> public static async Task<bool> IsEnabledAsync(this IFeatureChecker featureChecker, bool requiresAll, params string[] featureNames) { if (featureNames.IsNullOrEmpty()) { return true; } if (requiresAll) { foreach (var featureName in featureNames) { if (!(await featureChecker.IsEnabledAsync(featureName))) { return false; } } return true; } foreach (var featureName in featureNames) { if (await featureChecker.IsEnabledAsync(featureName)) { return true; } } return false; } /// <summary> /// Used to check if one or all of the given features are enabled. /// </summary> /// <param name="featureChecker"><see cref="IFeatureChecker"/> instance</param> /// <param name="tenantId">Tenant id</param> /// <param name="requiresAll">True, to require that all the given features are enabled. False, to require one or more.</param> /// <param name="featureNames">Names of the features</param> public static async Task<bool> IsEnabledAsync(this IFeatureChecker featureChecker, int tenantId, bool requiresAll, params string[] featureNames) { if (featureNames.IsNullOrEmpty()) { return true; } if (requiresAll) { foreach (var featureName in featureNames) { if (!(await featureChecker.IsEnabledAsync(tenantId, featureName))) { return false; } } return true; } foreach (var featureName in featureNames) { if (await featureChecker.IsEnabledAsync(tenantId, featureName)) { return true; } } return false; } /// <summary> /// Used to check if one or all of the given features are enabled. /// </summary> /// <param name="featureChecker"><see cref="IFeatureChecker"/> instance</param> /// <param name="requiresAll">True, to require that all the given features are enabled. False, to require one or more.</param> /// <param name="featureNames">Names of the features</param> public static bool IsEnabled(this IFeatureChecker featureChecker, bool requiresAll, params string[] featureNames) { return AsyncHelper.RunSync(() => featureChecker.IsEnabledAsync(requiresAll, featureNames)); } /// <summary> /// Used to check if one or all of the given features are enabled. /// </summary> /// <param name="featureChecker"><see cref="IFeatureChecker"/> instance</param> /// <param name="tenantId">Tenant id</param> /// <param name="requiresAll">True, to require that all the given features are enabled. False, to require one or more.</param> /// <param name="featureNames">Names of the features</param> public static bool IsEnabled(this IFeatureChecker featureChecker, int tenantId, bool requiresAll, params string[] featureNames) { return AsyncHelper.RunSync(() => featureChecker.IsEnabledAsync(tenantId, requiresAll, featureNames)); } /// <summary> /// Checks if a given feature is enabled. Throws <see cref="AbpAuthorizationException"/> if not. /// </summary> /// <param name="featureChecker"><see cref="IFeatureChecker"/> instance</param> /// <param name="featureName">Unique feature name</param> public static async Task CheckEnabledAsync(this IFeatureChecker featureChecker, string featureName) { if (!(await featureChecker.IsEnabledAsync(featureName))) { throw new AbpAuthorizationException(string.Format( L( featureChecker, "FeatureIsNotEnabled", "Feature is not enabled: {0}" ), featureName )); } } /// <summary> /// Checks if a given feature is enabled. Throws <see cref="AbpAuthorizationException"/> if not. /// </summary> /// <param name="featureChecker"><see cref="IFeatureChecker"/> instance</param> /// <param name="featureName">Unique feature name</param> public static void CheckEnabled(this IFeatureChecker featureChecker, string featureName) { if (!featureChecker.IsEnabled(featureName)) { throw new AbpAuthorizationException(string.Format( L( featureChecker, "FeatureIsNotEnabled", "Feature is not enabled: {0}" ), featureName )); } } /// <summary> /// Checks if one or all of the given features are enabled. Throws <see cref="AbpAuthorizationException"/> if not. /// </summary> /// <param name="featureChecker"><see cref="IFeatureChecker"/> instance</param> /// <param name="requiresAll">True, to require that all the given features are enabled. False, to require one or more.</param> /// <param name="featureNames">Names of the features</param> public static async Task CheckEnabledAsync(this IFeatureChecker featureChecker, bool requiresAll, params string[] featureNames) { if (featureNames.IsNullOrEmpty()) { return; } if (requiresAll) { foreach (var featureName in featureNames) { if (!(await featureChecker.IsEnabledAsync(featureName))) { throw new AbpAuthorizationException( string.Format( L( featureChecker, "AllOfTheseFeaturesMustBeEnabled", "Required features are not enabled. All of these features must be enabled: {0}" ), string.Join(", ", featureNames) ) ); } } } else { foreach (var featureName in featureNames) { if (await featureChecker.IsEnabledAsync(featureName)) { return; } } throw new AbpAuthorizationException( string.Format( L( featureChecker, "AtLeastOneOfTheseFeaturesMustBeEnabled", "Required features are not enabled. At least one of these features must be enabled: {0}" ), string.Join(", ", featureNames) ) ); } } /// <summary> /// Checks if one or all of the given features are enabled. Throws <see cref="AbpAuthorizationException"/> if not. /// </summary> /// <param name="featureChecker"><see cref="IFeatureChecker"/> instance</param> /// <param name="tenantId">Tenant id</param> /// <param name="requiresAll">True, to require that all the given features are enabled. False, to require one or more.</param> /// <param name="featureNames">Names of the features</param> public static async Task CheckEnabledAsync(this IFeatureChecker featureChecker, int tenantId, bool requiresAll, params string[] featureNames) { if (featureNames.IsNullOrEmpty()) { return; } if (requiresAll) { foreach (var featureName in featureNames) { if (!(await featureChecker.IsEnabledAsync(tenantId, featureName))) { throw new AbpAuthorizationException( string.Format( L( featureChecker, "AllOfTheseFeaturesMustBeEnabled", "Required features are not enabled. All of these features must be enabled: {0}" ), string.Join(", ", featureNames) ) ); } } } else { foreach (var featureName in featureNames) { if (await featureChecker.IsEnabledAsync(tenantId, featureName)) { return; } } throw new AbpAuthorizationException( string.Format( L( featureChecker, "AtLeastOneOfTheseFeaturesMustBeEnabled", "Required features are not enabled. At least one of these features must be enabled: {0}" ), string.Join(", ", featureNames) ) ); } } /// <summary> /// Checks if one or all of the given features are enabled. Throws <see cref="AbpAuthorizationException"/> if not. /// </summary> /// <param name="featureChecker"><see cref="IFeatureChecker"/> instance</param> /// <param name="requiresAll">True, to require that all the given features are enabled. False, to require one or more.</param> /// <param name="featureNames">Names of the features</param> public static void CheckEnabled(this IFeatureChecker featureChecker, bool requiresAll, params string[] featureNames) { AsyncHelper.RunSync(() => featureChecker.CheckEnabledAsync(requiresAll, featureNames)); } /// <summary> /// Checks if one or all of the given features are enabled. Throws <see cref="AbpAuthorizationException"/> if not. /// </summary> /// <param name="featureChecker"><see cref="IFeatureChecker"/> instance</param> /// <param name="tenantId">Tenant id</param> /// <param name="requiresAll">True, to require that all the given features are enabled. False, to require one or more.</param> /// <param name="featureNames">Names of the features</param> public static void CheckEnabled(this IFeatureChecker featureChecker, int tenantId, bool requiresAll, params string[] featureNames) { AsyncHelper.RunSync(() => featureChecker.CheckEnabledAsync(tenantId, requiresAll, featureNames)); } public static string L(IFeatureChecker featureChecker, string name, string defaultValue) { if (!(featureChecker is IIocManagerAccessor)) { return defaultValue; } var iocManager = (featureChecker as IIocManagerAccessor).IocManager; using (var localizationManager = iocManager.ResolveAsDisposable<ILocalizationManager>()) { return localizationManager.Object.GetString(AbpConsts.LocalizationSourceName, name); } } } }
using System; using System.ComponentModel; using System.Reflection; using System.Runtime.InteropServices; using System.Windows.Forms; using System.Threading; namespace Gma.UserActivityMonitor { public static partial class HookManager { /// <summary> /// The CallWndProc hook procedure is an application-defined or library-defined callback /// function used with the SetWindowsHookEx function. The HOOKPROC type defines a pointer /// to this callback function. CallWndProc is a placeholder for the application-defined /// or library-defined function name. /// </summary> /// <param name="nCode"> /// [in] Specifies whether the hook procedure must process the message. /// If nCode is HC_ACTION, the hook procedure must process the message. /// If nCode is less than zero, the hook procedure must pass the message to the /// CallNextHookEx function without further processing and must return the /// value returned by CallNextHookEx. /// </param> /// <param name="wParam"> /// [in] Specifies whether the message was sent by the current thread. /// If the message was sent by the current thread, it is nonzero; otherwise, it is zero. /// </param> /// <param name="lParam"> /// [in] Pointer to a CWPSTRUCT structure that contains details about the message. /// </param> /// <returns> /// If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx. /// If nCode is greater than or equal to zero, it is highly recommended that you call CallNextHookEx /// and return the value it returns; otherwise, other applications that have installed WH_CALLWNDPROC /// hooks will not receive hook notifications and may behave incorrectly as a result. If the hook /// procedure does not call CallNextHookEx, the return value should be zero. /// </returns> /// <remarks> /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/callwndproc.asp /// </remarks> private delegate int HookProc(int nCode, int wParam, IntPtr lParam); //############################################################################## #region Mouse hook processing /// <summary> /// This field is not objectively needed but we need to keep a reference on a delegate which will be /// passed to unmanaged code. To avoid GC to clean it up. /// When passing delegates to unmanaged code, they must be kept alive by the managed application /// until it is guaranteed that they will never be called. /// </summary> private static HookProc s_MouseDelegate; /// <summary> /// Stores the handle to the mouse hook procedure. /// </summary> private static int s_MouseHookHandle; private static int m_OldX; private static int m_OldY; /// <summary> /// A callback function which will be called every Time a mouse activity detected. /// </summary> /// <param name="nCode"> /// [in] Specifies whether the hook procedure must process the message. /// If nCode is HC_ACTION, the hook procedure must process the message. /// If nCode is less than zero, the hook procedure must pass the message to the /// CallNextHookEx function without further processing and must return the /// value returned by CallNextHookEx. /// </param> /// <param name="wParam"> /// [in] Specifies whether the message was sent by the current thread. /// If the message was sent by the current thread, it is nonzero; otherwise, it is zero. /// </param> /// <param name="lParam"> /// [in] Pointer to a CWPSTRUCT structure that contains details about the message. /// </param> /// <returns> /// If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx. /// If nCode is greater than or equal to zero, it is highly recommended that you call CallNextHookEx /// and return the value it returns; otherwise, other applications that have installed WH_CALLWNDPROC /// hooks will not receive hook notifications and may behave incorrectly as a result. If the hook /// procedure does not call CallNextHookEx, the return value should be zero. /// </returns> private static int MouseHookProc(int nCode, int wParam, IntPtr lParam) { if (nCode >= 0) { //Marshall the data from callback. MouseLLHookStruct mouseHookStruct = (MouseLLHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseLLHookStruct)); //detect button clicked MouseButtons button = MouseButtons.None; short mouseDelta = 0; int clickCount = 0; bool mouseDown = false; bool mouseUp = false; switch (wParam) { case WM_LBUTTONDOWN: mouseDown = true; button = MouseButtons.Left; clickCount = 1; break; case WM_LBUTTONUP: mouseUp = true; button = MouseButtons.Left; clickCount = 1; break; case WM_LBUTTONDBLCLK: button = MouseButtons.Left; clickCount = 2; break; case WM_RBUTTONDOWN: mouseDown = true; button = MouseButtons.Right; clickCount = 1; break; case WM_RBUTTONUP: mouseUp = true; button = MouseButtons.Right; clickCount = 1; break; case WM_RBUTTONDBLCLK: button = MouseButtons.Right; clickCount = 2; break; case WM_MOUSEWHEEL: //If the message is WM_MOUSEWHEEL, the high-order word of MouseData member is the wheel delta. //One wheel click is defined as WHEEL_DELTA, which is 120. //(value >> 16) & 0xffff; retrieves the high-order word from the given 32-bit value mouseDelta = (short)((mouseHookStruct.MouseData >> 16) & 0xffff); //TODO: X BUTTONS (I havent them so was unable to test) //If the message is WM_XBUTTONDOWN, WM_XBUTTONUP, WM_XBUTTONDBLCLK, WM_NCXBUTTONDOWN, WM_NCXBUTTONUP, //or WM_NCXBUTTONDBLCLK, the high-order word specifies which X button was pressed or released, //and the low-order word is reserved. This value can be one or more of the following values. //Otherwise, MouseData is not used. break; } //generate event MouseEventExtArgs e = new MouseEventExtArgs( button, clickCount, mouseHookStruct.Point.X, mouseHookStruct.Point.Y, mouseDelta); //Mouse up if (s_MouseUp!=null && mouseUp) { s_MouseUp.Invoke(null, e); } //Mouse down if (s_MouseDown != null && mouseDown) { s_MouseDown.Invoke(null, e); } //If someone listens to click and a click is heppened if (s_MouseClick != null && clickCount>0) { s_MouseClick.Invoke(null, e); } //If someone listens to click and a click is heppened if (s_MouseClickExt != null && clickCount > 0) { s_MouseClickExt.Invoke(null, e); } //If someone listens to double click and a click is heppened if (s_MouseDoubleClick != null && clickCount == 2) { s_MouseDoubleClick.Invoke(null, e); } //Wheel was moved if (s_MouseWheel!=null && mouseDelta!=0) { s_MouseWheel.Invoke(null, e); } //If someone listens to move and there was a change in coordinates raise move event if ((s_MouseMove!=null || s_MouseMoveExt!=null) && (m_OldX != mouseHookStruct.Point.X || m_OldY != mouseHookStruct.Point.Y)) { m_OldX = mouseHookStruct.Point.X; m_OldY = mouseHookStruct.Point.Y; if (s_MouseMove != null) { s_MouseMove.Invoke(null, e); } if (s_MouseMoveExt != null) { s_MouseMoveExt.Invoke(null, e); } } if (e.Handled) { return -1; } } //call next hook return CallNextHookEx(s_MouseHookHandle, nCode, wParam, lParam); } private static void EnsureSubscribedToGlobalMouseEvents() { // install Mouse hook only if it is not installed and must be installed if (s_MouseHookHandle == 0) { //See comment of this field. To avoid GC to clean it up. s_MouseDelegate = MouseHookProc; //install hook s_MouseHookHandle = SetWindowsHookEx( WH_MOUSE_LL, s_MouseDelegate, IntPtr.Zero/*Marshal.GetHINSTANCE( Assembly.GetExecutingAssembly().GetModules()[0])*/, 0); //If SetWindowsHookEx fails. if (s_MouseHookHandle == 0) { //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set. int errorCode = Marshal.GetLastWin32Error(); //do cleanup //Initializes and throws a new instance of the Win32Exception class with the specified error. throw new Win32Exception(errorCode); } } } private static void TryUnsubscribeFromGlobalMouseEvents() { //if no subsribers are registered unsubsribe from hook if (s_MouseClick == null && s_MouseDown == null && s_MouseMove == null && s_MouseUp == null && s_MouseClickExt == null && s_MouseMoveExt == null && s_MouseWheel == null) { ForceUnsunscribeFromGlobalMouseEvents(); } } private static void ForceUnsunscribeFromGlobalMouseEvents() { if (s_MouseHookHandle != 0) { //uninstall hook int result = UnhookWindowsHookEx(s_MouseHookHandle); //reset invalid handle s_MouseHookHandle = 0; //Free up for GC s_MouseDelegate = null; //if failed and exception must be thrown if (result == 0) { //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set. int errorCode = Marshal.GetLastWin32Error(); //Initializes and throws a new instance of the Win32Exception class with the specified error. throw new Win32Exception(errorCode); } } } #endregion //############################################################################## #region Keyboard hook processing /// <summary> /// This field is not objectively needed but we need to keep a reference on a delegate which will be /// passed to unmanaged code. To avoid GC to clean it up. /// When passing delegates to unmanaged code, they must be kept alive by the managed application /// until it is guaranteed that they will never be called. /// </summary> private static HookProc s_KeyboardDelegate; /// <summary> /// Stores the handle to the Keyboard hook procedure. /// </summary> private static int s_KeyboardHookHandle; /// <summary> /// A callback function which will be called every Time a keyboard activity detected. /// </summary> /// <param name="nCode"> /// [in] Specifies whether the hook procedure must process the message. /// If nCode is HC_ACTION, the hook procedure must process the message. /// If nCode is less than zero, the hook procedure must pass the message to the /// CallNextHookEx function without further processing and must return the /// value returned by CallNextHookEx. /// </param> /// <param name="wParam"> /// [in] Specifies whether the message was sent by the current thread. /// If the message was sent by the current thread, it is nonzero; otherwise, it is zero. /// </param> /// <param name="lParam"> /// [in] Pointer to a CWPSTRUCT structure that contains details about the message. /// </param> /// <returns> /// If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx. /// If nCode is greater than or equal to zero, it is highly recommended that you call CallNextHookEx /// and return the value it returns; otherwise, other applications that have installed WH_CALLWNDPROC /// hooks will not receive hook notifications and may behave incorrectly as a result. If the hook /// procedure does not call CallNextHookEx, the return value should be zero. /// </returns> private static int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam) { //indicates if any of underlaing events set e.Handled flag bool handled = false; if (nCode >= 0) { //read structure KeyboardHookStruct at lParam KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct)); //raise KeyDown if (s_KeyDown != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN)) { Keys keyData = (Keys)MyKeyboardHookStruct.VirtualKeyCode; KeyEventArgs e = new KeyEventArgs(keyData); s_KeyDown.Invoke(null, e); handled = e.Handled; } // raise KeyPress if (s_KeyPress != null && wParam == WM_KEYDOWN) { bool isDownShift = ((GetKeyState(VK_SHIFT) & 0x80) == 0x80 ? true : false); bool isDownCapslock = (GetKeyState(VK_CAPITAL) != 0 ? true : false); byte[] keyState = new byte[256]; GetKeyboardState(keyState); byte[] inBuffer = new byte[2]; if (ToAscii(MyKeyboardHookStruct.VirtualKeyCode, MyKeyboardHookStruct.ScanCode, keyState, inBuffer, MyKeyboardHookStruct.Flags) == 1) { char key = (char)inBuffer[0]; if ((isDownCapslock ^ isDownShift) && Char.IsLetter(key)) key = Char.ToUpper(key); KeyPressEventArgs e = new KeyPressEventArgs(key); s_KeyPress.Invoke(null, e); handled = handled || e.Handled; } } // raise KeyUp if (s_KeyUp != null && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP)) { Keys keyData = (Keys)MyKeyboardHookStruct.VirtualKeyCode; KeyEventArgs e = new KeyEventArgs(keyData); s_KeyUp.Invoke(null, e); handled = handled || e.Handled; } } //if event handled in application do not handoff to other listeners if (handled) return -1; //forward to other application return CallNextHookEx(s_KeyboardHookHandle, nCode, wParam, lParam); } private static void EnsureSubscribedToGlobalKeyboardEvents() { // install Keyboard hook only if it is not installed and must be installed if (s_KeyboardHookHandle == 0) { //See comment of this field. To avoid GC to clean it up. s_KeyboardDelegate = KeyboardHookProc; //install hook s_KeyboardHookHandle = SetWindowsHookEx( WH_KEYBOARD_LL, s_KeyboardDelegate, /*Marshal.GetHINSTANCE( Assembly.GetExecutingAssembly().GetModules()[0])*/IntPtr.Zero, 0); //If SetWindowsHookEx fails. if (s_KeyboardHookHandle == 0) { //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set. int errorCode = Marshal.GetLastWin32Error(); //do cleanup //Initializes and throws a new instance of the Win32Exception class with the specified error. throw new Win32Exception(errorCode); } } } private static void TryUnsubscribeFromGlobalKeyboardEvents() { //if no subsribers are registered unsubsribe from hook if (s_KeyDown == null && s_KeyUp == null && s_KeyPress == null) { ForceUnsunscribeFromGlobalKeyboardEvents(); } } private static void ForceUnsunscribeFromGlobalKeyboardEvents() { if (s_KeyboardHookHandle != 0) { //uninstall hook int result = UnhookWindowsHookEx(s_KeyboardHookHandle); //reset invalid handle s_KeyboardHookHandle = 0; //Free up for GC s_KeyboardDelegate = null; //if failed and exception must be thrown if (result == 0) { //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set. int errorCode = Marshal.GetLastWin32Error(); //Initializes and throws a new instance of the Win32Exception class with the specified error. throw new Win32Exception(errorCode); } } } #endregion } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Options; using OrchardCore.Abstractions.Setup; using OrchardCore.DisplayManagement.ModelBinding; using OrchardCore.Email; using OrchardCore.Environment.Shell; using OrchardCore.Environment.Shell.Models; using OrchardCore.Environment.Shell.Scope; using OrchardCore.Modules; using OrchardCore.Setup.Services; using OrchardCore.Workflows.Abstractions.Models; using OrchardCore.Workflows.Activities; using OrchardCore.Workflows.Models; using OrchardCore.Workflows.Services; namespace OrchardCore.Tenants.Workflows.Activities { public class SetupTenantTask : TenantTask { private readonly IClock _clock; private readonly IUpdateModelAccessor _updateModelAccessor; private readonly IEmailAddressValidator _emailAddressValidator; private readonly IdentityOptions _identityOptions; public SetupTenantTask( IClock clock, IUpdateModelAccessor updateModelAccessor, IEmailAddressValidator emailAddressValidator, IOptions<IdentityOptions> identityOptions, IShellSettingsManager shellSettingsManager, IShellHost shellHost, ISetupService setupService, IWorkflowExpressionEvaluator expressionEvaluator, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer<SetupTenantTask> localizer) : base(shellSettingsManager, shellHost, expressionEvaluator, scriptEvaluator, localizer) { SetupService = setupService; _clock = clock; _updateModelAccessor = updateModelAccessor; _emailAddressValidator = emailAddressValidator; _identityOptions = identityOptions.Value; } protected ISetupService SetupService { get; } public override string Name => nameof(SetupTenantTask); public override LocalizedString Category => S["Tenant"]; public override LocalizedString DisplayText => S["Setup Tenant Task"]; public WorkflowExpression<string> SiteName { get => GetProperty(() => new WorkflowExpression<string>()); set => SetProperty(value); } public WorkflowExpression<string> AdminUsername { get => GetProperty(() => new WorkflowExpression<string>()); set => SetProperty(value); } public WorkflowExpression<string> AdminEmail { get => GetProperty(() => new WorkflowExpression<string>()); set => SetProperty(value); } public WorkflowExpression<string> AdminPassword { get => GetProperty(() => new WorkflowExpression<string>()); set => SetProperty(value); } public WorkflowExpression<string> DatabaseProvider { get => GetProperty(() => new WorkflowExpression<string>()); set => SetProperty(value); } public WorkflowExpression<string> DatabaseConnectionString { get => GetProperty(() => new WorkflowExpression<string>()); set => SetProperty(value); } public WorkflowExpression<string> DatabaseTablePrefix { get => GetProperty(() => new WorkflowExpression<string>()); set => SetProperty(value); } public WorkflowExpression<string> RecipeName { get => GetProperty(() => new WorkflowExpression<string>()); set => SetProperty(value); } public override IEnumerable<Outcome> GetPossibleOutcomes(WorkflowExecutionContext workflowContext, ActivityContext activityContext) { return Outcomes(S["Done"], S["Failed"]); } public override async Task<ActivityExecutionResult> ExecuteAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext) { if (ShellScope.Context.Settings.Name != ShellHelper.DefaultShellName) { return Outcomes("Failed"); } var tenantName = (await ExpressionEvaluator.EvaluateAsync(TenantName, workflowContext, null))?.Trim(); if (string.IsNullOrWhiteSpace(tenantName)) { return Outcomes("Failed"); } if (!ShellHost.TryGetSettings(tenantName, out var shellSettings)) { return Outcomes("Failed"); } if (shellSettings.State == TenantState.Running) { return Outcomes("Failed"); } if (shellSettings.State != TenantState.Uninitialized) { return Outcomes("Failed"); } var siteName = (await ExpressionEvaluator.EvaluateAsync(SiteName, workflowContext, null))?.Trim(); var adminUsername = (await ExpressionEvaluator.EvaluateAsync(AdminUsername, workflowContext, null))?.Trim(); var adminEmail = (await ExpressionEvaluator.EvaluateAsync(AdminEmail, workflowContext, null))?.Trim(); if (string.IsNullOrEmpty(adminUsername) || adminUsername.Any(c => !_identityOptions.User.AllowedUserNameCharacters.Contains(c))) { return Outcomes("Failed"); } if (string.IsNullOrEmpty(adminEmail) || !_emailAddressValidator.Validate(adminEmail)) { return Outcomes("Failed"); } var adminPassword = (await ExpressionEvaluator.EvaluateAsync(AdminPassword, workflowContext, null))?.Trim(); var databaseProvider = (await ExpressionEvaluator.EvaluateAsync(DatabaseProvider, workflowContext, null))?.Trim(); var databaseConnectionString = (await ExpressionEvaluator.EvaluateAsync(DatabaseConnectionString, workflowContext, null))?.Trim(); var databaseTablePrefix = (await ExpressionEvaluator.EvaluateAsync(DatabaseTablePrefix, workflowContext, null))?.Trim(); var recipeName = (await ExpressionEvaluator.EvaluateAsync(RecipeName, workflowContext, null))?.Trim(); if (string.IsNullOrEmpty(databaseProvider)) { databaseProvider = shellSettings["DatabaseProvider"]; } if (string.IsNullOrEmpty(databaseConnectionString)) { databaseConnectionString = shellSettings["ConnectionString"]; } if (string.IsNullOrEmpty(databaseTablePrefix)) { databaseTablePrefix = shellSettings["TablePrefix"]; } if (string.IsNullOrEmpty(recipeName)) { recipeName = shellSettings["RecipeName"]; } var recipes = await SetupService.GetSetupRecipesAsync(); var recipe = recipes.FirstOrDefault(r => r.Name == recipeName); var setupContext = new SetupContext { ShellSettings = shellSettings, EnabledFeatures = null, Errors = new Dictionary<string, string>(), Recipe = recipe, Properties = new Dictionary<string, object> { { SetupConstants.SiteName, siteName }, { SetupConstants.AdminUsername, adminUsername }, { SetupConstants.AdminEmail, AdminEmail }, { SetupConstants.AdminPassword, adminPassword }, { SetupConstants.SiteTimeZone, _clock.GetSystemTimeZone().TimeZoneId }, { SetupConstants.DatabaseProvider, databaseProvider }, { SetupConstants.DatabaseConnectionString, databaseConnectionString }, { SetupConstants.DatabaseTablePrefix, databaseTablePrefix }, } }; var executionId = await SetupService.SetupAsync(setupContext); // Check if a component in the Setup failed if (setupContext.Errors.Any()) { var updater = _updateModelAccessor.ModelUpdater; foreach (var error in setupContext.Errors) { updater.ModelState.AddModelError(error.Key, error.Value); } return Outcomes("Failed"); } return Outcomes("Done"); } } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion [assembly: Elmah.Scc("$Id: JsonTextWriter.cs addb64b2f0fa 2012-03-07 18:50:16Z azizatif $")] namespace Elmah { #region Imports using System; using System.Globalization; using System.IO; using System.Xml; #endregion /// <summary> /// Represents a writer that provides a fast, non-cached, forward-only /// way of generating streams or files containing JSON Text according /// to the grammar rules laid out in /// <a href="http://www.ietf.org/rfc/rfc4627.txt">RFC 4627</a>. /// </summary> /// <remarks> /// This class supports ELMAH and is not intended to be used directly /// from your code. It may be modified or removed in the future without /// notice. It has public accessibility for testing purposes. If you /// need a general-purpose JSON Text encoder, consult /// <a href="http://www.json.org/">JSON.org</a> for implementations /// or use classes available from the Microsoft .NET Framework. /// </remarks> public sealed class JsonTextWriter { private readonly TextWriter _writer; private readonly int[] _counters; private readonly char[] _terminators; private int _depth; private string _memberName; public JsonTextWriter(TextWriter writer) { Debug.Assert(writer != null); _writer = writer; const int levels = 10 + /* root */ 1; _counters = new int[levels]; _terminators = new char[levels]; } public int Depth { get { return _depth; } } private int ItemCount { get { return _counters[Depth]; } set { _counters[Depth] = value; } } private char Terminator { get { return _terminators[Depth]; } set { _terminators[Depth] = value; } } public JsonTextWriter Object() { return StartStructured("{", "}"); } public JsonTextWriter EndObject() { return Pop(); } public JsonTextWriter Array() { return StartStructured("[", "]"); } public JsonTextWriter EndArray() { return Pop(); } public JsonTextWriter Pop() { return EndStructured(); } public JsonTextWriter Member(string name) { if (name == null) throw new ArgumentNullException("name"); if (name.Length == 0) throw new ArgumentException(null, "name"); if (_memberName != null) throw new InvalidOperationException("Missing member value."); _memberName = name; return this; } private JsonTextWriter Write(string text) { return WriteImpl(text, /* raw */ false); } private JsonTextWriter WriteEnquoted(string text) { return WriteImpl(text, /* raw */ true); } private JsonTextWriter WriteImpl(string text, bool raw) { Debug.Assert(raw || (text != null && text.Length > 0)); if (Depth == 0 && (text.Length > 1 || (text[0] != '{' && text[0] != '['))) throw new InvalidOperationException(); TextWriter writer = _writer; if (ItemCount > 0) writer.Write(','); string name = _memberName; _memberName = null; if (name != null) { writer.Write(' '); Enquote(name, writer); writer.Write(':'); } if (Depth > 0) writer.Write(' '); if (raw) Enquote(text, writer); else writer.Write(text); ItemCount = ItemCount + 1; return this; } public JsonTextWriter Number(int value) { return Write(value.ToString(CultureInfo.InvariantCulture)); } public JsonTextWriter String(string str) { return str == null ? Null() : WriteEnquoted(str); } public JsonTextWriter Null() { return Write("null"); } public JsonTextWriter Boolean(bool value) { return Write(value ? "true" : "false"); } private static readonly DateTime _epoch = /* ... */ #if NET_1_0 || NET_1_1 /* ... */ new DateTime(1970, 1, 1, 0, 0, 0); #else /* ... */ new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); #endif public JsonTextWriter Number(DateTime time) { double seconds = time.ToUniversalTime().Subtract(_epoch).TotalSeconds; return Write(seconds.ToString(CultureInfo.InvariantCulture)); } public JsonTextWriter String(DateTime time) { string xmlTime; #if NET_1_0 || NET_1_1 xmlTime = XmlConvert.ToString(time); #else xmlTime = XmlConvert.ToString(time, XmlDateTimeSerializationMode.Utc); #endif return String(xmlTime); } private JsonTextWriter StartStructured(string start, string end) { if (Depth + 1 == _counters.Length) throw new Exception(); Write(start); _depth++; Terminator = end[0]; return this; } private JsonTextWriter EndStructured() { if (Depth - 1 < 0) throw new Exception(); _writer.Write(' '); _writer.Write(Terminator); ItemCount = 0; _depth--; return this; } private static void Enquote(string s, TextWriter writer) { Debug.Assert(writer != null); int length = Mask.NullString(s).Length; writer.Write('"'); char last; char ch = '\0'; for (int index = 0; index < length; index++) { last = ch; ch = s[index]; switch (ch) { case '\\': case '"': { writer.Write('\\'); writer.Write(ch); break; } case '/': { if (last == '<') writer.Write('\\'); writer.Write(ch); break; } case '\b': writer.Write("\\b"); break; case '\t': writer.Write("\\t"); break; case '\n': writer.Write("\\n"); break; case '\f': writer.Write("\\f"); break; case '\r': writer.Write("\\r"); break; default: { if (ch < ' ') { writer.Write("\\u"); writer.Write(((int)ch).ToString("x4", CultureInfo.InvariantCulture)); } else { writer.Write(ch); } break; } } } writer.Write('"'); } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Reflection; using System.Text; namespace FileHelpers { /// <summary> /// Define a field that is delimited, eg CSV and may be quoted /// </summary> public sealed class DelimitedField : FieldBase { #region " Constructor " private static readonly CompareInfo mCompare = StringHelper.CreateComparer(); /// <summary> /// Create an empty delimited field structure /// </summary> private DelimitedField() {} /// <summary> /// Create a delimited field with defined separator /// </summary> /// <param name="fi">field info structure</param> /// <param name="sep">field separator</param> internal DelimitedField(FieldInfo fi, string sep) : base(fi) { QuoteChar = '\0'; QuoteMultiline = MultilineMode.AllowForBoth; Separator = sep; // string.Intern(sep); } #endregion #region " Properties " private string mSeparator; /// <summary> /// Set the separator string /// </summary> /// <remarks>Also sets the discard count</remarks> internal string Separator { get { return mSeparator; } set { mSeparator = value; if (IsLast && IsArray == false) CharsToDiscard = 0; else CharsToDiscard = mSeparator.Length; } } /// <summary> /// allow a quoted multiline format /// </summary> internal MultilineMode QuoteMultiline { get; set; } /// <summary> /// whether quotes are optional for read and / or write /// </summary> internal QuoteMode QuoteMode { get; set; } /// <summary> /// quote character around field (and repeated within it) /// </summary> internal char QuoteChar { get; set; } #endregion #region " Overrides String Handling " /// <summary> /// Extract the field from the delimited file, removing separators and quotes /// and any duplicate quotes within the record /// </summary> /// <param name="line">line containing record input</param> /// <returns>Extract information</returns> internal override ExtractedInfo ExtractFieldString(LineInfo line) { if (IsOptional && line.IsEOL()) return ExtractedInfo.Empty; if (QuoteChar == '\0') return BasicExtractString(line); else { if (TrimMode == TrimMode.Both || TrimMode == TrimMode.Left) line.TrimStart(TrimChars); string quotedStr = QuoteChar.ToString(); if (line.StartsWith(quotedStr)) { var res = StringHelper.ExtractQuotedString(line, QuoteChar, QuoteMultiline == MultilineMode.AllowForBoth || QuoteMultiline == MultilineMode.AllowForRead); if (TrimMode == TrimMode.Both || TrimMode == TrimMode.Right) line.TrimStart(TrimChars); if (!IsLast && !line.StartsWith(Separator) && !line.IsEOL()) { throw new BadUsageException(line, "The field " + this.FieldInfo.Name + " is quoted but the quoted char: " + quotedStr + " not is just before the separator (You can use [FieldTrim] to avoid this error)"); } return res; } else { if (QuoteMode == QuoteMode.OptionalForBoth || QuoteMode == QuoteMode.OptionalForRead) return BasicExtractString(line); else if (line.StartsWithTrim(quotedStr)) { throw new BadUsageException( string.Format( "The field '{0}' has spaces before the QuotedChar at line {1}. Use the TrimAttribute to by pass this error. Field String: {2}", FieldInfo.Name, line.mReader.LineNumber, line.CurrentString)); } else { throw new BadUsageException( string.Format( "The field '{0}' does not begin with the QuotedChar at line {1}. You can use FieldQuoted(QuoteMode.OptionalForRead) to allow optional quoted field. Field String: {2}", FieldInfo.Name, line.mReader.LineNumber, line.CurrentString)); } } } } private ExtractedInfo BasicExtractString(LineInfo line) { if (IsLast && !IsArray) { var sepPos = line.IndexOf(mSeparator); if (sepPos == -1) return new ExtractedInfo(line); // Now check for one extra separator var msg = string.Format( "Delimiter '{0}' found after the last field '{1}' (the file is wrong or you need to add a field to the record class)", mSeparator, this.FieldInfo.Name, line.mReader.LineNumber); throw new BadUsageException(line.mReader.LineNumber, line.mCurrentPos, msg); } else { int sepPos = line.IndexOf(mSeparator); if (sepPos == -1) { if (IsLast && IsArray) return new ExtractedInfo(line); if ( NextIsOptional == false) { string msg; if (IsFirst && line.EmptyFromPos()) { msg = string.Format( "The line {0} is empty. Maybe you need to use the attribute [IgnoreEmptyLines] in your record class.", line.mReader.LineNumber); } else { msg = string.Format( "Delimiter '{0}' not found after field '{1}' (the record has less fields, the delimiter is wrong or the next field must be marked as optional).", mSeparator, this.FieldInfo.Name, line.mReader.LineNumber); } throw new FileHelpersException(line.mReader.LineNumber, line.mCurrentPos, msg); } else sepPos = line.mLineStr.Length; } return new ExtractedInfo(line, sepPos); } } /// <summary> /// Output the field string adding delimiters and any required quotes /// </summary> /// <param name="sb">buffer to add field to</param> /// <param name="fieldValue">value object to add</param> /// <param name="isLast">Indicates if we are processing last field</param> internal override void CreateFieldString(StringBuilder sb, object fieldValue, bool isLast) { string field = base.CreateFieldString(fieldValue); bool hasNewLine = mCompare.IndexOf(field, StringHelper.NewLine, CompareOptions.Ordinal) >= 0; // If have a new line and this is not allowed. We throw an exception if (hasNewLine && (QuoteMultiline == MultilineMode.AllowForRead || QuoteMultiline == MultilineMode.NotAllow)) { throw new BadUsageException("One value for the field " + this.FieldInfo.Name + " has a new line inside. To allow write this value you must add a FieldQuoted attribute with the multiline option in true."); } // Add Quotes If: // - optional == false // - is optional and contains the separator // - is optional and contains a new line if ((QuoteChar != '\0') && (QuoteMode == QuoteMode.AlwaysQuoted || QuoteMode == QuoteMode.OptionalForRead || ((QuoteMode == QuoteMode.OptionalForWrite || QuoteMode == QuoteMode.OptionalForBoth) && mCompare.IndexOf(field, mSeparator, CompareOptions.Ordinal) >= 0) || hasNewLine)) StringHelper.CreateQuotedString(sb, field, QuoteChar); else sb.Append(field); if (isLast == false) sb.Append(mSeparator); } /// <summary> /// create a field base class and populate the delimited values /// base class will add its own values /// </summary> /// <returns>fieldbase ready to be populated with extra info</returns> protected override FieldBase CreateClone() { var res = new DelimitedField { mSeparator = mSeparator, QuoteChar = QuoteChar, QuoteMode = QuoteMode, QuoteMultiline = QuoteMultiline }; return res; } #endregion } }
using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Util; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.Text; using Microsoft.TeamFoundation.DistributedTask.Pipelines; namespace Microsoft.VisualStudio.Services.Agent.Worker.Build { #if OS_WINDOWS [ServiceLocator(Default = typeof(TFCommandManager))] #else [ServiceLocator(Default = typeof(TeeCommandManager))] #endif public interface ITfsVCCommandManager : IAgentService { CancellationToken CancellationToken { set; } ServiceEndpoint Endpoint { set; } RepositoryResource Repository { set; } IExecutionContext ExecutionContext { set; } TfsVCFeatures Features { get; } string FilePath { get; } // TODO: Remove AddAsync after last-saved-checkin-metadata problem is fixed properly. Task AddAsync(string localPath); Task EulaAsync(); Task GetAsync(string localPath); string ResolvePath(string serverPath); Task ScorchAsync(); void SetupProxy(string proxyUrl, string proxyUsername, string proxyPassword); void CleanupProxySetting(); void SetupClientCertificate(string clientCert, string clientCertKey, string clientCertArchive, string clientCertPassword); // TODO: Remove parameter move after last-saved-checkin-metadata problem is fixed properly. Task ShelveAsync(string shelveset, string commentFile, bool move); Task<ITfsVCShelveset> ShelvesetsAsync(string shelveset); Task<ITfsVCStatus> StatusAsync(string localPath); bool TestEulaAccepted(); Task<bool> TryWorkspaceDeleteAsync(ITfsVCWorkspace workspace); Task UndoAsync(string localPath); Task UnshelveAsync(string shelveset); Task WorkfoldCloakAsync(string serverPath); Task WorkfoldMapAsync(string serverPath, string localPath); Task WorkfoldUnmapAsync(string serverPath); Task WorkspaceDeleteAsync(ITfsVCWorkspace workspace); Task WorkspaceNewAsync(); Task<ITfsVCWorkspace[]> WorkspacesAsync(bool matchWorkspaceNameOnAnyComputer = false); Task WorkspacesRemoveAsync(ITfsVCWorkspace workspace); } public abstract class TfsVCCommandManager : AgentService { public readonly Dictionary<string, string> AdditionalEnvironmentVariables = new Dictionary<string, string>(); public CancellationToken CancellationToken { protected get; set; } public ServiceEndpoint Endpoint { protected get; set; } public RepositoryResource Repository { protected get; set; } public IExecutionContext ExecutionContext { protected get; set; } public abstract TfsVCFeatures Features { get; } public abstract string FilePath { get; } protected virtual Encoding OutputEncoding => null; protected string SourceVersion { get { string version = Repository?.Version ?? GetEndpointData(Endpoint, Constants.EndpointData.SourceVersion); ArgUtil.NotNullOrEmpty(version, nameof(version)); return version; } } protected string SourcesDirectory { get { string sourcesDirectory = Repository?.Properties?.Get<string>(RepositoryPropertyNames.Path) ?? GetEndpointData(Endpoint, Constants.EndpointData.SourcesDirectory); ArgUtil.NotNullOrEmpty(sourcesDirectory, nameof(sourcesDirectory)); return sourcesDirectory; } } protected abstract string Switch { get; } protected string WorkspaceName { get { string workspace = ExecutionContext.Variables.Build_RepoTfvcWorkspace; ArgUtil.NotNullOrEmpty(workspace, nameof(workspace)); return workspace; } } protected Task RunCommandAsync(params string[] args) { return RunCommandAsync(FormatFlags.None, args); } protected async Task RunCommandAsync(FormatFlags formatFlags, params string[] args) { // Validation. ArgUtil.NotNull(args, nameof(args)); ArgUtil.NotNull(ExecutionContext, nameof(ExecutionContext)); // Invoke tf. using (var processInvoker = HostContext.CreateService<IProcessInvoker>()) { var outputLock = new object(); processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs e) => { lock (outputLock) { ExecutionContext.Output(e.Data); } }; processInvoker.ErrorDataReceived += (object sender, ProcessDataReceivedEventArgs e) => { lock (outputLock) { ExecutionContext.Output(e.Data); } }; string arguments = FormatArguments(formatFlags, args); ExecutionContext.Command($@"tf {arguments}"); await processInvoker.ExecuteAsync( workingDirectory: SourcesDirectory, fileName: FilePath, arguments: arguments, environment: AdditionalEnvironmentVariables, requireExitCodeZero: true, outputEncoding: OutputEncoding, cancellationToken: CancellationToken); } } protected Task<string> RunPorcelainCommandAsync(params string[] args) { return RunPorcelainCommandAsync(FormatFlags.None, args); } protected Task<string> RunPorcelainCommandAsync(bool ignoreStderr, params string[] args) { return RunPorcelainCommandAsync(FormatFlags.None, ignoreStderr, args); } protected Task<string> RunPorcelainCommandAsync(FormatFlags formatFlags, params string[] args) { return RunPorcelainCommandAsync(formatFlags, false, args); } protected async Task<string> RunPorcelainCommandAsync(FormatFlags formatFlags, bool ignoreStderr, params string[] args) { // Run the command. TfsVCPorcelainCommandResult result = await TryRunPorcelainCommandAsync(formatFlags, ignoreStderr, args); ArgUtil.NotNull(result, nameof(result)); if (result.Exception != null) { // The command failed. Dump the output and throw. result.Output?.ForEach(x => ExecutionContext.Output(x ?? string.Empty)); throw result.Exception; } // Return the output. // Note, string.join gracefully handles a null element within the IEnumerable<string>. return string.Join(Environment.NewLine, result.Output ?? new List<string>()); } protected async Task<TfsVCPorcelainCommandResult> TryRunPorcelainCommandAsync(FormatFlags formatFlags, bool ignoreStderr, params string[] args) { // Validation. ArgUtil.NotNull(args, nameof(args)); ArgUtil.NotNull(ExecutionContext, nameof(ExecutionContext)); // Invoke tf. using (var processInvoker = HostContext.CreateService<IProcessInvoker>()) { var result = new TfsVCPorcelainCommandResult(); var outputLock = new object(); processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs e) => { lock (outputLock) { ExecutionContext.Debug(e.Data); result.Output.Add(e.Data); } }; processInvoker.ErrorDataReceived += (object sender, ProcessDataReceivedEventArgs e) => { lock (outputLock) { if (ignoreStderr) { ExecutionContext.Output(e.Data); } else { ExecutionContext.Debug(e.Data); result.Output.Add(e.Data); } } }; string arguments = FormatArguments(formatFlags, args); ExecutionContext.Debug($@"tf {arguments}"); // TODO: Test whether the output encoding needs to be specified on a non-Latin OS. try { await processInvoker.ExecuteAsync( workingDirectory: SourcesDirectory, fileName: FilePath, arguments: arguments, environment: AdditionalEnvironmentVariables, requireExitCodeZero: true, outputEncoding: OutputEncoding, cancellationToken: CancellationToken); } catch (ProcessExitCodeException ex) { result.Exception = ex; } return result; } } private string FormatArguments(FormatFlags formatFlags, params string[] args) { // Validation. ArgUtil.NotNull(args, nameof(args)); ArgUtil.NotNull(Endpoint, nameof(Endpoint)); ArgUtil.NotNull(Endpoint.Authorization, nameof(Endpoint.Authorization)); ArgUtil.NotNull(Endpoint.Authorization.Parameters, nameof(Endpoint.Authorization.Parameters)); ArgUtil.Equal(EndpointAuthorizationSchemes.OAuth, Endpoint.Authorization.Scheme, nameof(Endpoint.Authorization.Scheme)); string accessToken = Endpoint.Authorization.Parameters.TryGetValue(EndpointAuthorizationParameters.AccessToken, out accessToken) ? accessToken : null; ArgUtil.NotNullOrEmpty(accessToken, EndpointAuthorizationParameters.AccessToken); ArgUtil.NotNull(Repository?.Url ?? Endpoint.Url, nameof(Endpoint.Url)); // Format each arg. var formattedArgs = new List<string>(); foreach (string arg in args ?? new string[0]) { // Validate the arg. if (!string.IsNullOrEmpty(arg) && arg.IndexOfAny(new char[] { '"', '\r', '\n' }) >= 0) { throw new Exception(StringUtil.Loc("InvalidCommandArg", arg)); } // Add the arg. formattedArgs.Add(arg != null && arg.Contains(" ") ? $@"""{arg}""" : $"{arg}"); } // Add the common parameters. if (!formatFlags.HasFlag(FormatFlags.OmitCollectionUrl)) { if (Features.HasFlag(TfsVCFeatures.EscapedUrl)) { formattedArgs.Add($"{Switch}collection:{Repository?.Url?.AbsoluteUri ?? Endpoint.Url.AbsoluteUri}"); } else { // TEE CLC expects the URL in unescaped form. string url; try { url = Uri.UnescapeDataString(Repository?.Url?.AbsoluteUri ?? Endpoint.Url.AbsoluteUri); } catch (Exception ex) { // Unlikely (impossible?), but don't fail if encountered. If we don't hear complaints // about this warning then it is likely OK to remove the try/catch altogether and have // faith that UnescapeDataString won't throw for this scenario. url = Repository?.Url?.AbsoluteUri ?? Endpoint.Url.AbsoluteUri; ExecutionContext.Warning($"{ex.Message} ({url})"); } formattedArgs.Add($"\"{Switch}collection:{url}\""); } } if (!formatFlags.HasFlag(FormatFlags.OmitLogin)) { if (Features.HasFlag(TfsVCFeatures.LoginType)) { formattedArgs.Add($"{Switch}loginType:OAuth"); formattedArgs.Add($"{Switch}login:.,{accessToken}"); } else { formattedArgs.Add($"{Switch}jwt:{accessToken}"); } } if (!formatFlags.HasFlag(FormatFlags.OmitNoPrompt)) { formattedArgs.Add($"{Switch}noprompt"); } return string.Join(" ", formattedArgs); } private string GetEndpointData(ServiceEndpoint endpoint, string name) { string value; if (endpoint.Data.TryGetValue(name, out value)) { Trace.Info($"Get '{name}': '{value}'"); return value; } Trace.Info($"Get '{name}' (not found)"); return null; } [Flags] protected enum FormatFlags { None = 0, OmitCollectionUrl = 1, OmitLogin = 2, OmitNoPrompt = 4, All = OmitCollectionUrl | OmitLogin | OmitNoPrompt, } } [Flags] public enum TfsVCFeatures { None = 0, // Indicates whether "workspace /new" adds a default mapping. DefaultWorkfoldMap = 1, // Indicates whether the CLI accepts the collection URL in escaped form. EscapedUrl = 2, // Indicates whether the "eula" subcommand is supported. Eula = 4, // Indicates whether the "get" and "undo" subcommands will correctly resolve // the workspace from an unmapped root folder. For example, if a workspace // contains only two mappings, $/foo -> $(build.sourcesDirectory)\foo and // $/bar -> $(build.sourcesDirectory)\bar, then "tf get $(build.sourcesDirectory)" // will not be able to resolve the workspace unless this feature is supported. GetFromUnmappedRoot = 8, // Indicates whether the "loginType" parameter is supported. LoginType = 16, // Indicates whether the "scorch" subcommand is supported. Scorch = 32, } public sealed class TfsVCPorcelainCommandResult { public TfsVCPorcelainCommandResult() { Output = new List<string>(); } public ProcessExitCodeException Exception { get; set; } public List<string> Output { get; } } //////////////////////////////////////////////////////////////////////////////// // tf shelvesets interfaces. //////////////////////////////////////////////////////////////////////////////// public interface ITfsVCShelveset { string Comment { get; } } //////////////////////////////////////////////////////////////////////////////// // tf status interfaces. //////////////////////////////////////////////////////////////////////////////// public interface ITfsVCStatus { IEnumerable<ITfsVCPendingChange> AllAdds { get; } bool HasPendingChanges { get; } } public interface ITfsVCPendingChange { string LocalItem { get; } } //////////////////////////////////////////////////////////////////////////////// // tf workspaces interfaces. //////////////////////////////////////////////////////////////////////////////// public interface ITfsVCWorkspace { string Computer { get; set; } string Name { get; } string Owner { get; } ITfsVCMapping[] Mappings { get; } } public interface ITfsVCMapping { bool Cloak { get; } string LocalPath { get; } bool Recursive { get; } string ServerPath { get; } } }
/* * Copyright (c) 2007-2008, openmetaverse.org * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.ComponentModel; using OpenMetaverse.StructuredData; namespace OpenMetaverse { /// <summary> /// Particle system specific enumerators, flags and methods. /// </summary> public partial class Primitive { #region Subclasses /// <summary> /// Complete structure for the particle system /// </summary> public struct ParticleSystem { /// <summary> /// Particle source pattern /// </summary> public enum SourcePattern : byte { /// <summary>None</summary> None = 0, /// <summary>Drop particles from source position with no force</summary> Drop = 0x01, /// <summary>"Explode" particles in all directions</summary> Explode = 0x02, /// <summary>Particles shoot across a 2D area</summary> Angle = 0x04, /// <summary>Particles shoot across a 3D Cone</summary> AngleCone = 0x08, /// <summary>Inverse of AngleCone (shoot particles everywhere except the 3D cone defined</summary> AngleConeEmpty = 0x10 } /// <summary> /// Particle Data Flags /// </summary> [Flags] public enum ParticleDataFlags : uint { /// <summary>None</summary> None = 0, /// <summary>Interpolate color and alpha from start to end</summary> InterpColor = 0x001, /// <summary>Interpolate scale from start to end</summary> InterpScale = 0x002, /// <summary>Bounce particles off particle sources Z height</summary> Bounce = 0x004, /// <summary>velocity of particles is dampened toward the simulators wind</summary> Wind = 0x008, /// <summary>Particles follow the source</summary> FollowSrc = 0x010, /// <summary>Particles point towards the direction of source's velocity</summary> FollowVelocity = 0x020, /// <summary>Target of the particles</summary> TargetPos = 0x040, /// <summary>Particles are sent in a straight line</summary> TargetLinear = 0x080, /// <summary>Particles emit a glow</summary> Emissive = 0x100, /// <summary>used for point/grab/touch</summary> Beam = 0x200, /// <summary>continuous ribbon particle</summary> Ribbon = 0x400, /// <summary>particle data contains glow</summary> DataGlow = 0x10000, /// <summary>particle data contains blend functions</summary> DataBlend = 0x20000, } /// <summary> /// Particle Flags Enum /// </summary> [Flags] public enum ParticleFlags : uint { /// <summary>None</summary> None = 0, /// <summary>Acceleration and velocity for particles are /// relative to the object rotation</summary> ObjectRelative = 0x01, /// <summary>Particles use new 'correct' angle parameters</summary> UseNewAngle = 0x02 } public enum BlendFunc : byte { One = 0, Zero = 1, DestColor = 2, SourceColor = 3, OneMinusDestColor = 4, OneMinusSourceColor = 5, DestAlpha = 6, SourceAlpha = 7, OneMinusDestAlpha = 8, OneMinusSourceAlpha = 9, } public uint CRC; /// <summary>Particle Flags</summary> /// <remarks>There appears to be more data packed in to this area /// for many particle systems. It doesn't appear to be flag values /// and serialization breaks unless there is a flag for every /// possible bit so it is left as an unsigned integer</remarks> public uint PartFlags; /// <summary><seealso cref="T:SourcePattern"/> pattern of particles</summary> public SourcePattern Pattern; /// <summary>A <see langword="float"/> representing the maximimum age (in seconds) particle will be displayed</summary> /// <remarks>Maximum value is 30 seconds</remarks> public float MaxAge; /// <summary>A <see langword="float"/> representing the number of seconds, /// from when the particle source comes into view, /// or the particle system's creation, that the object will emits particles; /// after this time period no more particles are emitted</summary> public float StartAge; /// <summary>A <see langword="float"/> in radians that specifies where particles will not be created</summary> public float InnerAngle; /// <summary>A <see langword="float"/> in radians that specifies where particles will be created</summary> public float OuterAngle; /// <summary>A <see langword="float"/> representing the number of seconds between burts.</summary> public float BurstRate; /// <summary>A <see langword="float"/> representing the number of meters /// around the center of the source where particles will be created.</summary> public float BurstRadius; /// <summary>A <see langword="float"/> representing in seconds, the minimum speed between bursts of new particles /// being emitted</summary> public float BurstSpeedMin; /// <summary>A <see langword="float"/> representing in seconds the maximum speed of new particles being emitted.</summary> public float BurstSpeedMax; /// <summary>A <see langword="byte"/> representing the maximum number of particles emitted per burst</summary> public byte BurstPartCount; /// <summary>A <see cref="T:Vector3"/> which represents the velocity (speed) from the source which particles are emitted</summary> public Vector3 AngularVelocity; /// <summary>A <see cref="T:Vector3"/> which represents the Acceleration from the source which particles are emitted</summary> public Vector3 PartAcceleration; /// <summary>The <see cref="T:UUID"/> Key of the texture displayed on the particle</summary> public UUID Texture; /// <summary>The <see cref="T:UUID"/> Key of the specified target object or avatar particles will follow</summary> public UUID Target; /// <summary>Flags of particle from <seealso cref="T:ParticleDataFlags"/></summary> public ParticleDataFlags PartDataFlags; /// <summary>Max Age particle system will emit particles for</summary> public float PartMaxAge; /// <summary>The <see cref="T:Color4"/> the particle has at the beginning of its lifecycle</summary> public Color4 PartStartColor; /// <summary>The <see cref="T:Color4"/> the particle has at the ending of its lifecycle</summary> public Color4 PartEndColor; /// <summary>A <see langword="float"/> that represents the starting X size of the particle</summary> /// <remarks>Minimum value is 0, maximum value is 4</remarks> public float PartStartScaleX; /// <summary>A <see langword="float"/> that represents the starting Y size of the particle</summary> /// <remarks>Minimum value is 0, maximum value is 4</remarks> public float PartStartScaleY; /// <summary>A <see langword="float"/> that represents the ending X size of the particle</summary> /// <remarks>Minimum value is 0, maximum value is 4</remarks> public float PartEndScaleX; /// <summary>A <see langword="float"/> that represents the ending Y size of the particle</summary> /// <remarks>Minimum value is 0, maximum value is 4</remarks> public float PartEndScaleY; /// <summary>A <see langword="float"/> that represents the start glow value</summary> /// <remarks>Minimum value is 0, maximum value is 1</remarks> public float PartStartGlow; /// <summary>A <see langword="float"/> that represents the end glow value</summary> /// <remarks>Minimum value is 0, maximum value is 1</remarks> public float PartEndGlow; /// <summary>OpenGL blend function to use at particle source</summary> public byte BlendFuncSource; /// <summary>OpenGL blend function to use at particle destination</summary> public byte BlendFuncDest; public const byte MaxDataBlockSize = 98; public const byte LegacyDataBlockSize = 86; public const byte SysDataSize = 68; public const byte PartDataSize = 18; /// <summary> /// Can this particle system be packed in a legacy compatible way /// </summary> /// <returns>True if the particle system doesn't use new particle system features</returns> public bool IsLegacyCompatible() { return !HasGlow() && !HasBlendFunc(); } public bool HasGlow() { return PartStartGlow > 0f || PartEndGlow > 0f; } public bool HasBlendFunc() { return BlendFuncSource != (byte)BlendFunc.SourceAlpha || BlendFuncDest != (byte)BlendFunc.OneMinusSourceAlpha; } /// <summary> /// Decodes a byte[] array into a ParticleSystem Object /// </summary> /// <param name="data">ParticleSystem object</param> /// <param name="pos">Start position for BitPacker</param> public ParticleSystem(byte[] data, int pos) { PartStartGlow = 0f; PartEndGlow = 0f; BlendFuncSource = (byte)BlendFunc.SourceAlpha; BlendFuncDest = (byte)BlendFunc.OneMinusSourceAlpha; CRC = PartFlags = 0; Pattern = SourcePattern.None; MaxAge = StartAge = InnerAngle = OuterAngle = BurstRate = BurstRadius = BurstSpeedMin = BurstSpeedMax = 0.0f; BurstPartCount = 0; AngularVelocity = PartAcceleration = Vector3.Zero; Texture = Target = UUID.Zero; PartDataFlags = ParticleDataFlags.None; PartMaxAge = 0.0f; PartStartColor = PartEndColor = Color4.Black; PartStartScaleX = PartStartScaleY = PartEndScaleX = PartEndScaleY = 0.0f; int size = data.Length - pos; BitPack pack = new BitPack(data, pos); if (size == LegacyDataBlockSize) { UnpackSystem(ref pack); UnpackLegacyData(ref pack); } else if (size > LegacyDataBlockSize && size <= MaxDataBlockSize) { int sysSize = pack.UnpackBits(32); if (sysSize != SysDataSize) return; // unkown particle system data size UnpackSystem(ref pack); int dataSize = pack.UnpackBits(32); UnpackLegacyData(ref pack); if ((PartDataFlags & ParticleDataFlags.DataGlow) == ParticleDataFlags.DataGlow) { if (pack.Data.Length - pack.BytePos < 2) return; uint glow = pack.UnpackUBits(8); PartStartGlow = glow / 255f; glow = pack.UnpackUBits(8); PartEndGlow = glow / 255f; } if ((PartDataFlags & ParticleDataFlags.DataBlend) == ParticleDataFlags.DataBlend) { if (pack.Data.Length - pack.BytePos < 2) return; BlendFuncSource = (byte)pack.UnpackUBits(8); BlendFuncDest = (byte)pack.UnpackUBits(8); } } } void UnpackSystem(ref BitPack pack) { CRC = pack.UnpackUBits(32); PartFlags = pack.UnpackUBits(32); Pattern = (SourcePattern)pack.UnpackByte(); MaxAge = pack.UnpackFixed(false, 8, 8); StartAge = pack.UnpackFixed(false, 8, 8); InnerAngle = pack.UnpackFixed(false, 3, 5); OuterAngle = pack.UnpackFixed(false, 3, 5); BurstRate = pack.UnpackFixed(false, 8, 8); BurstRadius = pack.UnpackFixed(false, 8, 8); BurstSpeedMin = pack.UnpackFixed(false, 8, 8); BurstSpeedMax = pack.UnpackFixed(false, 8, 8); BurstPartCount = pack.UnpackByte(); float x = pack.UnpackFixed(true, 8, 7); float y = pack.UnpackFixed(true, 8, 7); float z = pack.UnpackFixed(true, 8, 7); AngularVelocity = new Vector3(x, y, z); x = pack.UnpackFixed(true, 8, 7); y = pack.UnpackFixed(true, 8, 7); z = pack.UnpackFixed(true, 8, 7); PartAcceleration = new Vector3(x, y, z); Texture = pack.UnpackUUID(); Target = pack.UnpackUUID(); } void UnpackLegacyData(ref BitPack pack) { PartDataFlags = (ParticleDataFlags)pack.UnpackUBits(32); PartMaxAge = pack.UnpackFixed(false, 8, 8); byte r = pack.UnpackByte(); byte g = pack.UnpackByte(); byte b = pack.UnpackByte(); byte a = pack.UnpackByte(); PartStartColor = new Color4(r, g, b, a); r = pack.UnpackByte(); g = pack.UnpackByte(); b = pack.UnpackByte(); a = pack.UnpackByte(); PartEndColor = new Color4(r, g, b, a); PartStartScaleX = pack.UnpackFixed(false, 3, 5); PartStartScaleY = pack.UnpackFixed(false, 3, 5); PartEndScaleX = pack.UnpackFixed(false, 3, 5); PartEndScaleY = pack.UnpackFixed(false, 3, 5); } /// <summary> /// Generate byte[] array from particle data /// </summary> /// <returns>Byte array</returns> public byte[] GetBytes() { int size = LegacyDataBlockSize; if (!IsLegacyCompatible()) size += 8; // two new ints for size if (HasGlow()) size += 2; // two bytes for start and end glow if (HasBlendFunc()) size += 2; // two bytes for start end end blend function byte[] bytes = new byte[size]; BitPack pack = new BitPack(bytes, 0); if (IsLegacyCompatible()) { PackSystemBytes(ref pack); PackLegacyData(ref pack); } else { if (HasGlow()) PartDataFlags |= ParticleDataFlags.DataGlow; if (HasBlendFunc()) PartDataFlags |= ParticleDataFlags.DataBlend; pack.PackBits(SysDataSize, 32); PackSystemBytes(ref pack); int partSize = PartDataSize; if (HasGlow()) partSize += 2; // two bytes for start and end glow if (HasBlendFunc()) partSize += 2; // two bytes for start end end blend function pack.PackBits(partSize, 32); PackLegacyData(ref pack); if (HasGlow()) { pack.PackBits((byte)(PartStartGlow * 255f), 8); pack.PackBits((byte)(PartEndGlow * 255f), 8); } if (HasBlendFunc()) { pack.PackBits(BlendFuncSource, 8); pack.PackBits(BlendFuncDest, 8); } } return bytes; } void PackSystemBytes(ref BitPack pack) { pack.PackBits(CRC, 32); pack.PackBits((uint)PartFlags, 32); pack.PackBits((uint)Pattern, 8); pack.PackFixed(MaxAge, false, 8, 8); pack.PackFixed(StartAge, false, 8, 8); pack.PackFixed(InnerAngle, false, 3, 5); pack.PackFixed(OuterAngle, false, 3, 5); pack.PackFixed(BurstRate, false, 8, 8); pack.PackFixed(BurstRadius, false, 8, 8); pack.PackFixed(BurstSpeedMin, false, 8, 8); pack.PackFixed(BurstSpeedMax, false, 8, 8); pack.PackBits(BurstPartCount, 8); pack.PackFixed(AngularVelocity.X, true, 8, 7); pack.PackFixed(AngularVelocity.Y, true, 8, 7); pack.PackFixed(AngularVelocity.Z, true, 8, 7); pack.PackFixed(PartAcceleration.X, true, 8, 7); pack.PackFixed(PartAcceleration.Y, true, 8, 7); pack.PackFixed(PartAcceleration.Z, true, 8, 7); pack.PackUUID(Texture); pack.PackUUID(Target); } void PackLegacyData(ref BitPack pack) { pack.PackBits((uint)PartDataFlags, 32); pack.PackFixed(PartMaxAge, false, 8, 8); pack.PackColor(PartStartColor); pack.PackColor(PartEndColor); pack.PackFixed(PartStartScaleX, false, 3, 5); pack.PackFixed(PartStartScaleY, false, 3, 5); pack.PackFixed(PartEndScaleX, false, 3, 5); pack.PackFixed(PartEndScaleY, false, 3, 5); } public OSD GetOSD() { OSDMap map = new OSDMap(); map["crc"] = OSD.FromInteger(CRC); map["part_flags"] = OSD.FromInteger(PartFlags); map["pattern"] = OSD.FromInteger((int)Pattern); map["max_age"] = OSD.FromReal(MaxAge); map["start_age"] = OSD.FromReal(StartAge); map["inner_angle"] = OSD.FromReal(InnerAngle); map["outer_angle"] = OSD.FromReal(OuterAngle); map["burst_rate"] = OSD.FromReal(BurstRate); map["burst_radius"] = OSD.FromReal(BurstRadius); map["burst_speed_min"] = OSD.FromReal(BurstSpeedMin); map["burst_speed_max"] = OSD.FromReal(BurstSpeedMax); map["burst_part_count"] = OSD.FromInteger(BurstPartCount); map["ang_velocity"] = OSD.FromVector3(AngularVelocity); map["part_acceleration"] = OSD.FromVector3(PartAcceleration); map["texture"] = OSD.FromUUID(Texture); map["target"] = OSD.FromUUID(Target); map["part_data_flags"] = (uint)PartDataFlags; map["part_max_age"] = PartMaxAge; map["part_start_color"] = PartStartColor; map["part_end_color"] = PartEndColor; map["part_start_scale"] = new Vector3(PartStartScaleX, PartStartScaleY, 0f); map["part_end_scale"] = new Vector3(PartEndScaleX, PartEndScaleY, 0f); if (HasGlow()) { map["part_start_glow"] = PartStartGlow; map["part_end_glow"] = PartEndGlow; } if (HasBlendFunc()) { map["blendfunc_source"] = BlendFuncSource; map["blendfunc_dest"] = BlendFuncDest; } return map; } public static ParticleSystem FromOSD(OSD osd) { ParticleSystem partSys = new ParticleSystem(); OSDMap map = osd as OSDMap; if (map != null) { partSys.CRC = map["crc"].AsUInteger(); partSys.PartFlags = map["part_flags"].AsUInteger(); partSys.Pattern = (SourcePattern)map["pattern"].AsInteger(); partSys.MaxAge = (float)map["max_age"].AsReal(); partSys.StartAge = (float)map["start_age"].AsReal(); partSys.InnerAngle = (float)map["inner_angle"].AsReal(); partSys.OuterAngle = (float)map["outer_angle"].AsReal(); partSys.BurstRate = (float)map["burst_rate"].AsReal(); partSys.BurstRadius = (float)map["burst_radius"].AsReal(); partSys.BurstSpeedMin = (float)map["burst_speed_min"].AsReal(); partSys.BurstSpeedMax = (float)map["burst_speed_max"].AsReal(); partSys.BurstPartCount = (byte)map["burst_part_count"].AsInteger(); partSys.AngularVelocity = map["ang_velocity"].AsVector3(); partSys.PartAcceleration = map["part_acceleration"].AsVector3(); partSys.Texture = map["texture"].AsUUID(); partSys.Target = map["target"].AsUUID(); partSys.PartDataFlags = (ParticleDataFlags)map["part_data_flags"].AsUInteger(); partSys.PartMaxAge = map["part_max_age"]; partSys.PartStartColor = map["part_start_color"]; partSys.PartEndColor = map["part_end_color"]; Vector3 ss = map["part_start_scale"]; partSys.PartStartScaleX = ss.X; partSys.PartStartScaleY = ss.Y; Vector3 es = map["part_end_scale"]; partSys.PartEndScaleX = es.X; partSys.PartEndScaleY = es.Y; if (map.ContainsKey("part_start_glow")) { partSys.PartStartGlow = map["part_start_glow"]; partSys.PartEndGlow = map["part_end_glow"]; } if (map.ContainsKey("blendfunc_source")) { partSys.BlendFuncSource = (byte)map["blendfunc_source"].AsUInteger(); partSys.BlendFuncDest = (byte)map["blendfunc_dest"].AsUInteger(); } } return partSys; } } #endregion Subclasses #region Public Members /// <summary></summary> public ParticleSystem ParticleSys; #endregion Public Members } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Compute.Fluent.GalleryImage.Update { using Microsoft.Azure.Management.Compute.Fluent.Models; using System; using System.Collections.Generic; /// <summary> /// The stage of the gallery image update allowing to specify OsState. /// </summary> public interface IWithOsState : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Specifies osState. /// </summary> /// <param name="osState">The OS State.</param> /// <return>The next update stage.</return> Microsoft.Azure.Management.Compute.Fluent.GalleryImage.Update.IUpdate WithOsState(OperatingSystemStateTypes osState); } /// <summary> /// The stage of the gallery image update allowing to specify description. /// </summary> public interface IWithDescription : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Specifies description of the gallery image resource. /// </summary> /// <param name="description">The description.</param> /// <return>The next update stage.</return> Microsoft.Azure.Management.Compute.Fluent.GalleryImage.Update.IUpdate WithDescription(string description); } /// <summary> /// The stage of the gallery image update allowing to specify Eula. /// </summary> public interface IWithEula : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Specifies eula. /// </summary> /// <param name="eula">The Eula agreement for the gallery image.</param> /// <return>The next update stage.</return> Microsoft.Azure.Management.Compute.Fluent.GalleryImage.Update.IUpdate WithEula(string eula); } /// <summary> /// The stage of the gallery image update allowing to specify EndOfLifeDate. /// </summary> public interface IWithEndOfLifeDate : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Specifies end of life date of the image. /// </summary> /// <param name="endOfLifeDate">The end of life of the gallery image.</param> /// <return>The next update stage.</return> Microsoft.Azure.Management.Compute.Fluent.GalleryImage.Update.IUpdate WithEndOfLifeDate(DateTime endOfLifeDate); } /// <summary> /// The template for a gallery image update operation, containing all the settings that can be modified. /// </summary> public interface IUpdate : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta, Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.IAppliable<Microsoft.Azure.Management.Compute.Fluent.IGalleryImage>, Microsoft.Azure.Management.Compute.Fluent.GalleryImage.Update.IWithDescription, Microsoft.Azure.Management.Compute.Fluent.GalleryImage.Update.IWithDisallowed, Microsoft.Azure.Management.Compute.Fluent.GalleryImage.Update.IWithEndOfLifeDate, Microsoft.Azure.Management.Compute.Fluent.GalleryImage.Update.IWithEula, Microsoft.Azure.Management.Compute.Fluent.GalleryImage.Update.IWithOsState, Microsoft.Azure.Management.Compute.Fluent.GalleryImage.Update.IWithPrivacyStatementUri, Microsoft.Azure.Management.Compute.Fluent.GalleryImage.Update.IWithRecommendedVMConfiguration, Microsoft.Azure.Management.Compute.Fluent.GalleryImage.Update.IWithReleaseNoteUri, Microsoft.Azure.Management.Compute.Fluent.GalleryImage.Update.IWithTags { } /// <summary> /// The stage of the gallery image definition allowing to specify recommended /// configuration for the virtual machine. /// </summary> public interface IWithRecommendedVMConfiguration : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Specifies recommended configuration for the virtual machine based on the image. /// </summary> /// <param name="recommendedConfig">The recommended configuration.</param> /// <return>The next update stage.</return> Microsoft.Azure.Management.Compute.Fluent.GalleryImage.Update.IUpdate WithRecommendedConfigurationForVirtualMachine(RecommendedMachineConfiguration recommendedConfig); /// <summary> /// Specifies the recommended virtual CUPs for the virtual machine bases on the image. /// </summary> /// <param name="minCount">The minimum number of virtual CPUs.</param> /// <param name="maxCount">The maximum number of virtual CPUs.</param> /// <return>The next update stage.</return> Microsoft.Azure.Management.Compute.Fluent.GalleryImage.Update.IUpdate WithRecommendedCPUsCountForVirtualMachine(int minCount, int maxCount); /// <summary> /// Specifies the recommended maximum number of virtual CUPs for the virtual machine bases on the image. /// </summary> /// <param name="maxCount">The maximum number of virtual CPUs.</param> /// <return>The next update stage.</return> Microsoft.Azure.Management.Compute.Fluent.GalleryImage.Update.IUpdate WithRecommendedMaximumCPUsCountForVirtualMachine(int maxCount); /// <summary> /// Specifies the recommended maximum memory for the virtual machine bases on the image. /// </summary> /// <param name="maxMB">The maximum memory in MB.</param> /// <return>The next update stage.</return> Microsoft.Azure.Management.Compute.Fluent.GalleryImage.Update.IUpdate WithRecommendedMaximumMemoryForVirtualMachine(int maxMB); /// <summary> /// Specifies the recommended virtual CUPs for the virtual machine bases on the image. /// </summary> /// <param name="minMB">The minimum memory in MB.</param> /// <param name="maxMB">The maximum memory in MB.</param> /// <return>The next update stage.</return> Microsoft.Azure.Management.Compute.Fluent.GalleryImage.Update.IUpdate WithRecommendedMemoryForVirtualMachine(int minMB, int maxMB); /// <summary> /// Specifies the recommended minimum number of virtual CUPs for the virtual machine bases on the image. /// </summary> /// <param name="minCount">The minimum number of virtual CPUs.</param> /// <return>The next update stage.</return> Microsoft.Azure.Management.Compute.Fluent.GalleryImage.Update.IUpdate WithRecommendedMinimumCPUsCountForVirtualMachine(int minCount); /// <summary> /// Specifies the recommended minimum memory for the virtual machine bases on the image. /// </summary> /// <param name="minMB">The minimum memory in MB.</param> /// <return>The next update stage.</return> Microsoft.Azure.Management.Compute.Fluent.GalleryImage.Update.IUpdate WithRecommendedMinimumMemoryForVirtualMachine(int minMB); } /// <summary> /// The stage of the gallery image update allowing to specify settings disallowed /// for a virtual machine based on the image. /// </summary> public interface IWithDisallowed : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Specifies disallowed settings. /// </summary> /// <param name="disallowed">The disallowed settings.</param> /// <return>The next update stage.</return> Microsoft.Azure.Management.Compute.Fluent.GalleryImage.Update.IUpdate WithDisallowed(Disallowed disallowed); /// <summary> /// Specifies the disk type should be removed from the unsupported disk type. /// </summary> /// <param name="diskType">The disk type.</param> /// <return>The next update stage.</return> Microsoft.Azure.Management.Compute.Fluent.GalleryImage.Update.IUpdate WithoutUnsupportedDiskType(DiskSkuTypes diskType); /// <summary> /// Specifies the disk type not supported by the image. /// </summary> /// <param name="diskType">The disk type.</param> /// <return>The next update stage.</return> Microsoft.Azure.Management.Compute.Fluent.GalleryImage.Update.IUpdate WithUnsupportedDiskType(DiskSkuTypes diskType); /// <summary> /// Specifies the disk types not supported by the image. /// </summary> /// <param name="diskTypes">The disk types.</param> /// <return>The next update stage.</return> Microsoft.Azure.Management.Compute.Fluent.GalleryImage.Update.IUpdate WithUnsupportedDiskTypes(IList<Microsoft.Azure.Management.Compute.Fluent.Models.DiskSkuTypes> diskTypes); } /// <summary> /// The stage of the gallery image update allowing to specify uri to release note. /// </summary> public interface IWithReleaseNoteUri : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Specifies release note uri. /// </summary> /// <param name="releaseNoteUri">The release note uri.</param> /// <return>The next update stage.</return> Microsoft.Azure.Management.Compute.Fluent.GalleryImage.Update.IUpdate WithReleaseNoteUri(string releaseNoteUri); } /// <summary> /// The stage of the gallery image update allowing to specify privacy statement uri. /// </summary> public interface IWithPrivacyStatementUri : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Specifies image privacy statement uri. /// </summary> /// <param name="privacyStatementUri">The privacy statement uri.</param> /// <return>The next update stage.</return> Microsoft.Azure.Management.Compute.Fluent.GalleryImage.Update.IUpdate WithPrivacyStatementUri(string privacyStatementUri); } /// <summary> /// The stage of the gallery image update allowing to specify Tags. /// </summary> public interface IWithTags : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Specifies tags. /// </summary> /// <param name="tags">Resource tags.</param> /// <return>The next update stage.</return> Microsoft.Azure.Management.Compute.Fluent.GalleryImage.Update.IUpdate WithTags(IDictionary<string,string> tags); } }
// Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. using System; namespace SixLabors.Fonts.Unicode { /// <summary> /// Builder class to manipulate and generate a trie. /// This is useful for ICU data in primitive types. /// Provides a compact way to store information that is indexed by Unicode /// values, such as character properties, types, keyboard values, etc. /// This is very useful when you have a block of Unicode data that contains significant /// values while the rest of the Unicode data is unused in the application or /// when you have a lot of redundance, such as where all 21,000 Han ideographs /// have the same value. However, lookup is much faster than a hash table. /// A trie of any primitive data type serves two purposes: /// <ul> /// <li>Fast access of the indexed values.</li> /// <li>Smaller memory footprint.</li> /// </ul> /// </summary> internal class UnicodeTrieBuilder { // These have been kept in the original format for now to aid porting // and testing. #pragma warning disable SA1310 // Field names should not contain underscore // Shift size for getting the index-1 table offset. internal const int UTRIE2_SHIFT_1 = 6 + 5; // Shift size for getting the index-2 table offset. internal const int UTRIE2_SHIFT_2 = 5; // Difference between the two shift sizes, // for getting an index-1 offset from an index-2 offset. 6=11-5 private const int UTRIE2_SHIFT_1_2 = UTRIE2_SHIFT_1 - UTRIE2_SHIFT_2; // Number of index-1 entries for the BMP. 32=0x20 // This part of the index-1 table is omitted from the serialized form. internal const int UTRIE2_OMITTED_BMP_INDEX_1_LENGTH = 0x10000 >> UTRIE2_SHIFT_1; // Number of code points per index-1 table entry. 2048=0x800 private const int UTRIE2_CP_PER_INDEX_1_ENTRY = 1 << UTRIE2_SHIFT_1; // Start with allocation of 16k data entries. private const int INITIAL_DATA_LENGTH = 1 << 14; // Grow about 8x each time. private const int UNEWTRIE2_MEDIUM_DATA_LENGTH = 1 << 17; private const int INDEX_1_LENGTH = 0x110000 >> UTRIE2_SHIFT_1; // Number of entries in a data block. 32=0x20 private const int UTRIE2_DATA_BLOCK_LENGTH = 1 << UTRIE2_SHIFT_2; // Mask for getting the lower bits for the in-data-block offset. internal const int UTRIE2_DATA_MASK = UTRIE2_DATA_BLOCK_LENGTH - 1; // Shift size for shifting left the index array values. // Increases possible data size with 16-bit index values at the cost // of compactability. // This requires data blocks to be aligned by UTRIE2_DATA_GRANULARITY. internal const int UTRIE2_INDEX_SHIFT = 2; // The alignment size of a data block. Also the granularity for compaction. internal const int UTRIE2_DATA_GRANULARITY = 1 << UTRIE2_INDEX_SHIFT; // The BMP part of the index-2 table is fixed and linear and starts at offset 0. // Length=2048=0x800=0x10000>>UTRIE2_SHIFT_2. private const int UTRIE2_INDEX_2_OFFSET = 0; // The part of the index-2 table for U+D800..U+DBFF stores values for // lead surrogate code _units_ not code _points_. // Values for lead surrogate code _points_ are indexed with this portion of the table. // Length=32=0x20=0x400>>UTRIE2_SHIFT_2. (There are 1024=0x400 lead surrogates.) internal const int UTRIE2_LSCP_INDEX_2_OFFSET = 0x10000 >> UTRIE2_SHIFT_2; private const int UTRIE2_LSCP_INDEX_2_LENGTH = 0x400 >> UTRIE2_SHIFT_2; // Count the lengths of both BMP pieces. 2080=0x820 private const int UTRIE2_INDEX_2_BMP_LENGTH = UTRIE2_LSCP_INDEX_2_OFFSET + UTRIE2_LSCP_INDEX_2_LENGTH; // The 2-byte UTF-8 version of the index-2 table follows at offset 2080=0x820. // Length 32=0x20 for lead bytes C0..DF, regardless of UTRIE2_SHIFT_2. private const int UTRIE2_UTF8_2B_INDEX_2_OFFSET = UTRIE2_INDEX_2_BMP_LENGTH; private const int UTRIE2_UTF8_2B_INDEX_2_LENGTH = 0x800 >> 6; // U+0800 is the first code point after 2-byte UTF-8 // The index-1 table, only used for supplementary code points, at offset 2112=0x840. // Variable length, for code points up to highStart, where the last single-value range starts. // Maximum length 512=0x200=0x100000>>UTRIE2_SHIFT_1. // (For 0x100000 supplementary code points U+10000..U+10ffff.) // // The part of the index-2 table for supplementary code points starts // after this index-1 table. // // Both the index-1 table and the following part of the index-2 table // are omitted completely if there is only BMP data. internal const int UTRIE2_INDEX_1_OFFSET = UTRIE2_UTF8_2B_INDEX_2_OFFSET + UTRIE2_UTF8_2B_INDEX_2_LENGTH; private const int UTRIE2_MAX_INDEX_1_LENGTH = 0x100000 >> UTRIE2_SHIFT_1; // Maximum length of the build-time index-2 array. // Maximum number of Unicode code points (0x110000) shifted right by UTRIE2_SHIFT_2, // plus the part of the index-2 table for lead surrogate code points, // plus the build-time index gap, // plus the null index-2 block. private const int UNEWTRIE2_MAX_INDEX_2_LENGTH = (0x110000 >> UTRIE2_SHIFT_2) + UTRIE2_LSCP_INDEX_2_LENGTH + UNEWTRIE2_INDEX_GAP_LENGTH + UTRIE2_INDEX_2_BLOCK_LENGTH; private const int UNEWTRIE2_INDEX_1_LENGTH = 0x110000 >> UTRIE2_SHIFT_1; // Number of entries in an index-2 block. 64=0x40 private const int UTRIE2_INDEX_2_BLOCK_LENGTH = 1 << UTRIE2_SHIFT_1_2; // Mask for getting the lower bits for the in-index-2-block offset. internal const int UTRIE2_INDEX_2_MASK = UTRIE2_INDEX_2_BLOCK_LENGTH - 1; // At build time, leave a gap in the index-2 table, // at least as long as the maximum lengths of the 2-byte UTF-8 index-2 table // and the supplementary index-1 table. // Round up to UTRIE2_INDEX_2_BLOCK_LENGTH for proper compacting. private const int UNEWTRIE2_INDEX_GAP_OFFSET = UTRIE2_INDEX_2_BMP_LENGTH; private const int UNEWTRIE2_INDEX_GAP_LENGTH = (UTRIE2_UTF8_2B_INDEX_2_LENGTH + UTRIE2_MAX_INDEX_1_LENGTH + UTRIE2_INDEX_2_MASK) & ~UTRIE2_INDEX_2_MASK; // Maximum length of the build-time data array. // One entry per 0x110000 code points, plus the illegal-UTF-8 block and the null block, // plus values for the 0x400 surrogate code units. private const int UNEWTRIE2_MAX_DATA_LENGTH = 0x110000 + 0x40 + 0x40 + 0x400; // The illegal-UTF-8 data block follows the ASCII block, at offset 128=0x80. // Used with linear access for single bytes 0..0xbf for simple error handling. // Length 64=0x40, not UTRIE2_DATA_BLOCK_LENGTH. private const int UTRIE2_BAD_UTF8_DATA_OFFSET = 0x80; // The start of non-linear-ASCII data blocks, at offset 192=0xc0. private const int UTRIE2_DATA_START_OFFSET = 0xc0; // The null data block. // Length 64=0x40 even if UTRIE2_DATA_BLOCK_LENGTH is smaller, // to work with 6-bit trail bytes from 2-byte UTF-8. private const int UNEWTRIE2_DATA_NULL_OFFSET = UTRIE2_DATA_START_OFFSET; // The null index-2 block, following the gap in the index-2 table. private const int UNEWTRIE2_INDEX_2_NULL_OFFSET = UNEWTRIE2_INDEX_GAP_OFFSET + UNEWTRIE2_INDEX_GAP_LENGTH; // The start of allocated index-2 blocks. private const int UNEWTRIE2_INDEX_2_START_OFFSET = UNEWTRIE2_INDEX_2_NULL_OFFSET + UTRIE2_INDEX_2_BLOCK_LENGTH; // The start of allocated data blocks. private const int UNEWTRIE2_DATA_START_OFFSET = UNEWTRIE2_DATA_NULL_OFFSET + 0x40; // The start of data blocks for U+0800 and above. // Below, compaction uses a block length of 64 for 2-byte UTF-8. // From here on, compaction uses UTRIE2_DATA_BLOCK_LENGTH. // Data values for 0x780 code points beyond ASCII. private const int UNEWTRIE2_DATA_0800_OFFSET = UNEWTRIE2_DATA_START_OFFSET + 0x780; // Maximum length of the runtime index array. // Limited by its own 16-bit index values, and by uint16_t UTrie2Header.indexLength. // (The actual maximum length is lower, // (0x110000>>UTRIE2_SHIFT_2)+UTRIE2_UTF8_2B_INDEX_2_LENGTH+UTRIE2_MAX_INDEX_1_LENGTH.) private const int UTRIE2_MAX_INDEX_LENGTH = 0xffff; // Maximum length of the runtime data array. // Limited by 16-bit index values that are left-shifted by UTRIE2_INDEX_SHIFT, // and by uint16_t UTrie2Header.shiftedDataLength. private const int UTRIE2_MAX_DATA_LENGTH = 0xffff << UTRIE2_INDEX_SHIFT; #pragma warning restore SA1310 // Field names should not contain underscore private readonly uint initialValue; private readonly uint errorValue; private int highStart; private uint[] data; private int dataCapacity; private readonly int[] index1; private readonly int[] index2; private int firstFreeBlock; private bool isCompacted; private readonly int[] map; private int dataNullOffset; private int dataLength; private int index2NullOffset; private int index2Length; /// <summary> /// Initializes a new instance of the <see cref="UnicodeTrieBuilder"/> class. /// </summary> /// <param name="initialValue">The initial value that is set for all code points.</param> /// <param name="errorValue">The value for out-of-range code points and illegal UTF-8.</param> public UnicodeTrieBuilder(uint initialValue = 0, uint errorValue = 0) { this.initialValue = initialValue; this.errorValue = errorValue; this.highStart = 0x110000; this.index1 = new int[INDEX_1_LENGTH]; this.index2 = new int[UNEWTRIE2_MAX_INDEX_2_LENGTH]; this.data = new uint[INITIAL_DATA_LENGTH]; this.dataCapacity = INITIAL_DATA_LENGTH; this.firstFreeBlock = 0; this.isCompacted = false; // Multi-purpose per-data-block table. // // Before compacting: // // Per-data-block reference counters/free-block list. // 0: unused // >0: reference counter (number of index-2 entries pointing here) // <0: next free data block in free-block list // // While compacting: // // Map of adjusted indexes, used in compactData() and compactIndex2(). // Maps from original indexes to new ones. this.map = new int[UNEWTRIE2_MAX_DATA_LENGTH >> UTRIE2_SHIFT_2]; // preallocate and reset // - ASCII // - the bad-UTF-8-data block // - the null data block int i; for (i = 0; i < 0x80; ++i) { this.data[i] = initialValue; } for (; i < 0xc0; ++i) { this.data[i] = errorValue; } for (i = UNEWTRIE2_DATA_NULL_OFFSET; i < UNEWTRIE2_DATA_START_OFFSET; ++i) { this.data[i] = initialValue; } this.dataNullOffset = UNEWTRIE2_DATA_NULL_OFFSET; this.dataLength = UNEWTRIE2_DATA_START_OFFSET; // set the index-2 indexes for the 2=0x80>>UTRIE2_SHIFT_2 ASCII data blocks int j; for (i = 0, j = 0; j < 0x80; ++i, j += UTRIE2_DATA_BLOCK_LENGTH) { this.index2[i] = j; this.map[i] = 1; } // reference counts for the bad-UTF-8-data block */ for (; j < 0xc0; ++i, j += UTRIE2_DATA_BLOCK_LENGTH) { this.map[i] = 0; } // Reference counts for the null data block: all blocks except for the ASCII blocks. // Plus 1 so that we don't drop this block during compaction. // Plus as many as needed for lead surrogate code points. // i==newdataNullOffset this.map[i++] = (0x110000 >> UTRIE2_SHIFT_2) - (0x80 >> UTRIE2_SHIFT_2) + 1 + UTRIE2_LSCP_INDEX_2_LENGTH; j += UTRIE2_DATA_BLOCK_LENGTH; for (; j < UNEWTRIE2_DATA_START_OFFSET; ++i, j += UTRIE2_DATA_BLOCK_LENGTH) { this.map[i] = 0; } // set the remaining indexes in the BMP index-2 block // to the null data block for (i = 0x80 >> UTRIE2_SHIFT_2; i < UTRIE2_INDEX_2_BMP_LENGTH; ++i) { this.index2[i] = UNEWTRIE2_DATA_NULL_OFFSET; } // Fill the index gap with impossible values so that compaction // does not overlap other index-2 blocks with the gap. for (i = 0; i < UNEWTRIE2_INDEX_GAP_LENGTH; ++i) { this.index2[UNEWTRIE2_INDEX_GAP_OFFSET + i] = -1; } // set the indexes in the null index-2 block for (i = 0; i < UTRIE2_INDEX_2_BLOCK_LENGTH; ++i) { this.index2[UNEWTRIE2_INDEX_2_NULL_OFFSET + i] = UNEWTRIE2_DATA_NULL_OFFSET; } this.index2NullOffset = UNEWTRIE2_INDEX_2_NULL_OFFSET; this.index2Length = UNEWTRIE2_INDEX_2_START_OFFSET; // set the index-1 indexes for the linear index-2 block for (i = 0, j = 0; i < UTRIE2_OMITTED_BMP_INDEX_1_LENGTH; ++i, j += UTRIE2_INDEX_2_BLOCK_LENGTH) { this.index1[i] = j; } // set the remaining index-1 indexes to the null index-2 block for (; i < UNEWTRIE2_INDEX_1_LENGTH; ++i) { this.index1[i] = UNEWTRIE2_INDEX_2_NULL_OFFSET; } // Preallocate and reset data for U+0080..U+07ff, // for 2-byte UTF-8 which will be compacted in 64-blocks // even if UTRIE2_DATA_BLOCK_LENGTH is smaller. for (i = 0x80; i < 0x800; i += UTRIE2_DATA_BLOCK_LENGTH) { this.Set(i, initialValue); } } /// <summary> /// Gets the value for a code point as stored in the trie. /// </summary> /// <param name="c">The code point.</param> /// <returns>The value.</returns> public uint Get(int c) => this.Get(c, true); /// <summary> /// Sets a value for a given code point. /// </summary> /// <param name="codePoint">The code point.</param> /// <param name="value">The value.</param> public void Set(int codePoint, uint value) { if ((codePoint < 0) || (codePoint > 0x10ffff)) { throw new ArgumentOutOfRangeException("Invalid code point"); } if (this.isCompacted) { throw new InvalidOperationException("Already compacted"); } int block = this.GetDataBlock(codePoint, true); this.data[block + (codePoint & UTRIE2_DATA_MASK)] = value; } /// <summary> /// Set a value in a range of code points [start..end]. /// All code points c with start &lt;= c &lt;= end will get the value if /// <paramref name="overwrite"/> is <see langword="true"/> or if the old value is the /// initial value. /// </summary> /// <param name="start">The first code point to get the value.</param> /// <param name="end">The last code point to get the value (inclusive).</param> /// <param name="value">The value.</param> /// <param name="overwrite">Whether old non-initial values are to be overwritten.</param> public void SetRange(int start, int end, uint value, bool overwrite) { if ((start > 0x10ffff) || (end > 0x10ffff) || start > end) { throw new ArgumentOutOfRangeException("Invalid code point"); } if (this.isCompacted) { throw new InvalidOperationException("Already compacted"); } if (!overwrite && value == this.initialValue) { return; // Nothing to do. } int block; int rest; int repeatBlock; int limit = end + 1; if ((start & UTRIE2_DATA_MASK) != 0) { int nextStart; // set partial block at [start..following block boundary[ block = this.GetDataBlock(start, true); if (block < 0) { throw new IndexOutOfRangeException(nameof(block)); } nextStart = (start + UTRIE2_DATA_MASK) & ~UTRIE2_DATA_MASK; if (nextStart <= limit) { this.FillBlock(block, start & UTRIE2_DATA_MASK, UTRIE2_DATA_BLOCK_LENGTH, value, this.initialValue, overwrite); start = nextStart; } else { this.FillBlock(block, start & UTRIE2_DATA_MASK, limit & UTRIE2_DATA_MASK, value, this.initialValue, overwrite); return; } } // number of positions in the last, partial block rest = limit & UTRIE2_DATA_MASK; // round down limit to a block boundary limit &= ~UTRIE2_DATA_MASK; // iterate over all-value blocks if (value == this.initialValue) { repeatBlock = this.dataNullOffset; } else { repeatBlock = -1; } while (start < limit) { int i2; bool setRepeatBlock = false; if (value == this.initialValue && this.IsInNullBlock(start, true)) { start += UTRIE2_DATA_BLOCK_LENGTH; // nothing to do continue; } // get index value i2 = this.GetIndex2Block(start, true); if (i2 < 0) { throw new IndexOutOfRangeException(nameof(i2)); } i2 += (start >> UTRIE2_SHIFT_2) & UTRIE2_INDEX_2_MASK; block = this.index2[i2]; if (this.IsWritableBlock(block)) { // already allocated if (overwrite && block >= UNEWTRIE2_DATA_0800_OFFSET) { // We overwrite all values, and it's not a // protected (ASCII-linear or 2-byte UTF-8) block: // replace with the repeatBlock. setRepeatBlock = true; } else { // !overwrite, or protected block: just write the values into this block this.FillBlock(block, 0, UTRIE2_DATA_BLOCK_LENGTH, value, this.initialValue, overwrite); } } else if (this.data[block] != value && (overwrite || block == this.dataNullOffset)) { // Set the repeatBlock instead of the null block or previous repeat block: // // If !isWritableBlock() then all entries in the block have the same value // because it's the null block or a range block (the repeatBlock from a previous // call to utrie2_setRange32()). // No other blocks are used multiple times before compacting. // // The null block is the only non-writable block with the initialValue because // of the repeatBlock initialization above. (If value==initialValue, then // the repeatBlock will be the null data block.) // // We set our repeatBlock if the desired value differs from the block's value, // and if we overwrite any data or if the data is all initial values // (which is the same as the block being the null block, see above). setRepeatBlock = true; } if (setRepeatBlock) { if (repeatBlock >= 0) { this.SetIndex2Entry(i2, repeatBlock); } else { // create and set and fill the repeatBlock repeatBlock = this.GetDataBlock(start, true); if (repeatBlock < 0) { throw new IndexOutOfRangeException(nameof(repeatBlock)); } this.WriteBlock(repeatBlock, value); } } start += UTRIE2_DATA_BLOCK_LENGTH; } if (rest > 0) { // set partial block at [last block boundary..limit[ block = this.GetDataBlock(start, true); if (block < 0) { throw new IndexOutOfRangeException(nameof(block)); } this.FillBlock(block, 0, rest, value, this.initialValue, overwrite); } } /// <summary> /// Compacts the data and populates an optimized readonly Trie. /// </summary> /// <returns>The <see cref="UnicodeTrie"/>.</returns> public UnicodeTrie Freeze() { int allIndexesLength, i; if (!this.isCompacted) { this.CompactTrie(); } if (this.highStart <= 0x10000) { allIndexesLength = UTRIE2_INDEX_1_OFFSET; } else { allIndexesLength = this.index2Length; } int dataMove = allIndexesLength; // are indexLength and dataLength within limits? if ((allIndexesLength > UTRIE2_MAX_INDEX_LENGTH) // for unshifted indexLength || ((dataMove + this.dataNullOffset) > 0xffff) // for unshifted dataNullOffset || ((dataMove + UNEWTRIE2_DATA_0800_OFFSET) > 0xffff) // for unshifted 2-byte UTF-8 index-2 values || ((dataMove + this.dataLength) > UTRIE2_MAX_DATA_LENGTH)) { // for shiftedDataLength throw new InvalidOperationException("Trie data is too large."); } // calculate the sizes of, and allocate, the index and data arrays int indexLength = allIndexesLength + this.dataLength; uint[] data32 = new uint[indexLength]; // write the index-2 array values shifted right by UTRIE2_INDEX_SHIFT, after adding dataMove int destIdx = 0; for (i = 0; i < UTRIE2_INDEX_2_BMP_LENGTH; i++) { data32[destIdx++] = (uint)((this.index2[i] + dataMove) >> UTRIE2_INDEX_SHIFT); } // write UTF-8 2-byte index-2 values, not right-shifted for (i = 0; i < 0xc2 - 0xc0; i++) { // C0..C1 data32[destIdx++] = (uint)(dataMove + UTRIE2_BAD_UTF8_DATA_OFFSET); } for (; i < 0xe0 - 0xc0; i++) { // C2..DF data32[destIdx++] = (uint)(dataMove + this.index2[i << (6 - UTRIE2_SHIFT_2)]); } if (this.highStart > 0x10000) { int index1Length = (this.highStart - 0x10000) >> UTRIE2_SHIFT_1; int index2Offset = UTRIE2_INDEX_2_BMP_LENGTH + UTRIE2_UTF8_2B_INDEX_2_LENGTH + index1Length; // write 16-bit index-1 values for supplementary code points for (i = 0; i < index1Length; i++) { data32[destIdx++] = (uint)(UTRIE2_INDEX_2_OFFSET + this.index1[i + UTRIE2_OMITTED_BMP_INDEX_1_LENGTH]); } // write the index-2 array values for supplementary code points, // shifted right by INDEX_SHIFT, after adding dataMove for (i = 0; i < this.index2Length - index2Offset; i++) { data32[destIdx++] = (uint)((dataMove + this.index2[index2Offset + i]) >> UTRIE2_INDEX_SHIFT); } } // write 16-bit data values for (i = 0; i < this.dataLength; i++) { data32[destIdx++] = this.data[i]; } return new UnicodeTrie(data32, this.highStart, this.errorValue); } private uint Get(int c, bool fromLSCP) { if ((c < 0) || (c > 0x10ffff)) { return this.errorValue; } int i2; int block; if (c >= this.highStart && (!U_IS_LEAD(c) || fromLSCP)) { return this.data[this.dataLength - UTRIE2_DATA_GRANULARITY]; } if (U_IS_LEAD(c) && fromLSCP) { i2 = UTRIE2_LSCP_INDEX_2_OFFSET - (0xd800 >> UTRIE2_SHIFT_2) + (c >> UTRIE2_SHIFT_2); } else { i2 = this.index1[c >> UTRIE2_SHIFT_1] + ((c >> UTRIE2_SHIFT_2) & UTRIE2_INDEX_2_MASK); } block = this.index2[i2]; return this.data[block + (c & UTRIE2_DATA_MASK)]; } private int GetDataBlock(int c, bool forLSCP) { int i2 = this.GetIndex2Block(c, forLSCP); if (i2 < 0) { throw new IndexOutOfRangeException(nameof(i2)); } i2 += (c >> UTRIE2_SHIFT_2) & UTRIE2_INDEX_2_MASK; int oldBlock = this.index2[i2]; if (this.IsWritableBlock(oldBlock)) { return oldBlock; } // allocate a new data block int newBlock = this.AllocDataBlock(oldBlock); if (newBlock < 0) { throw new IndexOutOfRangeException(nameof(newBlock)); } this.SetIndex2Entry(i2, newBlock); return newBlock; } private int GetIndex2Block(int c, bool forLSCP) { if (U_IS_LEAD(c) && forLSCP) { return UTRIE2_LSCP_INDEX_2_OFFSET; } int i1 = c >> UTRIE2_SHIFT_1; int i2 = this.index1[i1]; if (i2 == this.index2NullOffset) { i2 = this.AllocIndex2Block(); if (i2 < 0) { throw new IndexOutOfRangeException(nameof(i2)); } this.index1[i1] = i2; } return i2; } /// <summary> /// Is this code point a lead surrogate (U+d800..U+dbff)? /// </summary> /// <param name="c">The code point.</param> /// <returns>The <see cref="bool"/>.</returns> private static bool U_IS_LEAD(int c) => (c & 0xfffffc00) == 0xd800; private bool IsWritableBlock(int block) => block != this.dataNullOffset && this.map[block >> UTRIE2_SHIFT_2] == 1; private bool IsInNullBlock(int c, bool forLSCP) { int i2, block; if (U_IS_LEAD(c) && forLSCP) { i2 = UTRIE2_LSCP_INDEX_2_OFFSET - (0xd800 >> UTRIE2_SHIFT_2) + (c >> UTRIE2_SHIFT_2); } else { i2 = this.index1[c >> UTRIE2_SHIFT_1] + ((c >> UTRIE2_SHIFT_2) & UTRIE2_INDEX_2_MASK); } block = this.index2[i2]; return block == this.dataNullOffset; } private void SetIndex2Entry(int i2, int block) { int oldBlock; // increment first, in case block==oldBlock! ++this.map[block >> UTRIE2_SHIFT_2]; oldBlock = this.index2[i2]; if (--this.map[oldBlock >> UTRIE2_SHIFT_2] == 0) { this.ReleaseDataBlock(oldBlock); } this.index2[i2] = block; } // call when the block's reference counter reaches 0 private void ReleaseDataBlock(int block) { // put this block at the front of the free-block chain this.map[block >> UTRIE2_SHIFT_2] = -this.firstFreeBlock; this.firstFreeBlock = block; } private int AllocDataBlock(int copyBlock) { int newBlock, newTop; if (this.firstFreeBlock != 0) { // get the first free block newBlock = this.firstFreeBlock; this.firstFreeBlock = -this.map[newBlock >> UTRIE2_SHIFT_2]; } else { // get a new block from the high end newBlock = this.dataLength; newTop = newBlock + UTRIE2_DATA_BLOCK_LENGTH; if (newTop > this.dataCapacity) { // out of memory in the data array. int capacity; uint[] newData; if (this.dataCapacity < UNEWTRIE2_MEDIUM_DATA_LENGTH) { capacity = UNEWTRIE2_MEDIUM_DATA_LENGTH; } else if (this.dataCapacity < UNEWTRIE2_MAX_DATA_LENGTH) { capacity = UNEWTRIE2_MAX_DATA_LENGTH; } else { // Should never occur. // Either UNEWTRIE2_MAX_DATA_LENGTH is incorrect, // or the code writes more values than should be possible. throw new InvalidOperationException(nameof(capacity)); } newData = new uint[capacity]; Array.Copy(this.data, newData, this.dataLength); this.data = newData; this.dataCapacity = capacity; } this.dataLength = newTop; } Array.Copy(this.data, copyBlock, this.data, newBlock, UTRIE2_DATA_BLOCK_LENGTH); this.map[newBlock >> UTRIE2_SHIFT_2] = 0; return newBlock; } private int AllocIndex2Block() { int newBlock, newTop; newBlock = this.index2Length; newTop = newBlock + UTRIE2_INDEX_2_BLOCK_LENGTH; if (newTop > this.index2.Length) { // Should never occur. // Either UTRIE2_MAX_BUILD_TIME_INDEX_LENGTH is incorrect, // or the code writes more values than should be possible. throw new InvalidOperationException(nameof(newTop)); } this.index2Length = newTop; Array.Copy(this.index2, this.index2NullOffset, this.index2, newBlock, UTRIE2_INDEX_2_BLOCK_LENGTH); return newBlock; } private int FindSameIndex2Block(int index2Length, int otherBlock) { // ensure that we do not even partially get past index2Length index2Length -= UTRIE2_INDEX_2_BLOCK_LENGTH; for (int block = 0; block <= index2Length; ++block) { if (Equal(this.index2, block, otherBlock, UTRIE2_INDEX_2_BLOCK_LENGTH)) { return block; } } return -1; } private int FindSameDataBlock(int dataLength, int otherBlock, int blockLength) { // ensure that we do not even partially get past dataLength dataLength -= blockLength; for (int block = 0; block <= dataLength; block += UTRIE2_DATA_GRANULARITY) { if (Equal(this.data, block, otherBlock, blockLength)) { return block; } } return -1; } // Find the start of the last range in the trie by enumerating backward. // Indexes for supplementary code points higher than this will be omitted. private int FindHighStart(uint highValue) { uint[] data32; uint value, initialValue; int c, prev; int i1, i2, j, i2Block, prevI2Block, index2NullOffset, block, prevBlock, nullBlock; data32 = this.data; initialValue = this.initialValue; index2NullOffset = this.index2NullOffset; nullBlock = this.dataNullOffset; /* set variables for previous range */ if (highValue == initialValue) { prevI2Block = index2NullOffset; prevBlock = nullBlock; } else { prevI2Block = -1; prevBlock = -1; } prev = 0x110000; // enumerate index-2 blocks i1 = UNEWTRIE2_INDEX_1_LENGTH; c = prev; while (c > 0) { i2Block = this.index1[--i1]; if (i2Block == prevI2Block) { // the index-2 block is the same as // the previous one, and filled with highValue c -= UTRIE2_CP_PER_INDEX_1_ENTRY; continue; } prevI2Block = i2Block; if (i2Block == index2NullOffset) { // this is the null index-2 block if (highValue != initialValue) { return c; } c -= UTRIE2_CP_PER_INDEX_1_ENTRY; } else { // enumerate data blocks for one index-2 block for (i2 = UTRIE2_INDEX_2_BLOCK_LENGTH; i2 > 0;) { block = this.index2[i2Block + --i2]; if (block == prevBlock) { // the block is the same as the previous one, and filled with highValue c -= UTRIE2_DATA_BLOCK_LENGTH; continue; } prevBlock = block; if (block == nullBlock) { // this is the null data block if (highValue != initialValue) { return c; } c -= UTRIE2_DATA_BLOCK_LENGTH; } else { for (j = UTRIE2_DATA_BLOCK_LENGTH; j > 0;) { value = data32[block + --j]; if (value != highValue) { return c; } --c; } } } } } // deliver last range return 0; } // initialValue is ignored if overwrite=TRUE private void FillBlock(int block, int start, int limit, uint value, uint initialValue, bool overwrite) { int pLimit = block + limit; block += start; if (overwrite) { while (block < pLimit) { this.data[block++] = value; } } else { while (block < pLimit) { if (this.data[block] == initialValue) { this.data[block] = value; } ++block; } } } private void WriteBlock(int block, uint value) { int limit = block + UTRIE2_DATA_BLOCK_LENGTH; while (block < limit) { this.data[block++] = value; } } private void CompactTrie() { // find highStart and round it up uint highValue = this.Get(0x10ffff); int localHighStart = this.FindHighStart(highValue); localHighStart = (localHighStart + (UTRIE2_CP_PER_INDEX_1_ENTRY - 1)) & ~(UTRIE2_CP_PER_INDEX_1_ENTRY - 1); if (localHighStart == 0x110000) { highValue = this.errorValue; } // Set highStart only after Get(trie, highStart). // Otherwise Get(highStart) would try to read the highValue. this.highStart = localHighStart; if (localHighStart < 0x110000) { // Blank out [highStart..10ffff] to release associated data blocks. int suppHighStart = this.highStart <= 0x10000 ? 0x10000 : this.highStart; this.SetRange(suppHighStart, 0x10ffff, this.initialValue, true); } this.CompactData(); if (this.highStart > 0x10000) { this.CompactIndex2(); } // Store the highValue in the data array and round up the dataLength. // Must be done after compactData() because that assumes that dataLength // is a multiple of UTRIE2_DATA_BLOCK_LENGTH. this.data[this.dataLength++] = highValue; while ((this.dataLength & (UTRIE2_DATA_GRANULARITY - 1)) != 0) { this.data[this.dataLength++] = this.initialValue; } this.isCompacted = true; } // Compact a build-time trie. // // The compaction // - removes blocks that are identical with earlier ones // - overlaps adjacent blocks as much as possible (if overlap==TRUE) // - moves blocks in steps of the data granularity // - moves and overlaps blocks that overlap with multiple values in the overlap region // // It does not // - try to move and overlap blocks that are not already adjacent private void CompactData() { int start, newStart, movedStart; int blockLength, overlap; int i, mapIndex, blockCount; // do not compact linear-ASCII data newStart = UTRIE2_DATA_START_OFFSET; for (start = 0, i = 0; start < newStart; start += UTRIE2_DATA_BLOCK_LENGTH, ++i) { this.map[i] = start; } // Start with a block length of 64 for 2-byte UTF-8, // then switch to UTRIE2_DATA_BLOCK_LENGTH. blockLength = 64; blockCount = blockLength >> UTRIE2_SHIFT_2; for (start = newStart; start < this.dataLength;) { // start: index of first entry of current block // newStart: index where the current block is to be moved // (right after current end of already-compacted data) if (start == UNEWTRIE2_DATA_0800_OFFSET) { blockLength = UTRIE2_DATA_BLOCK_LENGTH; blockCount = 1; } // skip blocks that are not used if (this.map[start >> UTRIE2_SHIFT_2] <= 0) { // advance start to the next block start += blockLength; // leave newStart with the previous block! continue; } // search for an identical block if ((movedStart = this.FindSameDataBlock(newStart, start, blockLength)) >= 0) { // found an identical block, set the other block's index value for the current block for (i = blockCount, mapIndex = start >> UTRIE2_SHIFT_2; i > 0; --i) { this.map[mapIndex++] = movedStart; movedStart += UTRIE2_DATA_BLOCK_LENGTH; } // advance start to the next block start += blockLength; // leave newStart with the previous block! continue; } // see if the beginning of this block can be overlapped with the end of the previous block // look for maximum overlap (modulo granularity) with the previous, adjacent block overlap = blockLength - UTRIE2_DATA_GRANULARITY; while (overlap > 0 && !Equal(this.data, newStart - overlap, start, overlap)) { overlap -= UTRIE2_DATA_GRANULARITY; } if (overlap > 0 || newStart < start) { // some overlap, or just move the whole block movedStart = newStart - overlap; for (i = blockCount, mapIndex = start >> UTRIE2_SHIFT_2; i > 0; --i) { this.map[mapIndex++] = movedStart; movedStart += UTRIE2_DATA_BLOCK_LENGTH; } // move the non-overlapping indexes to their new positions start += overlap; for (i = blockLength - overlap; i > 0; --i) { this.data[newStart++] = this.data[start++]; } } else { // no overlap && newStart==start for (i = blockCount, mapIndex = start >> UTRIE2_SHIFT_2; i > 0; --i) { this.map[mapIndex++] = start; start += UTRIE2_DATA_BLOCK_LENGTH; } newStart = start; } } // now adjust the index-2 table for (i = 0; i < this.index2Length; ++i) { if (i == UNEWTRIE2_INDEX_GAP_OFFSET) { // Gap indexes are invalid (-1). Skip over the gap. i += UNEWTRIE2_INDEX_GAP_LENGTH; } this.index2[i] = this.map[this.index2[i] >> UTRIE2_SHIFT_2]; } this.dataNullOffset = this.map[this.dataNullOffset >> UTRIE2_SHIFT_2]; // ensure dataLength alignment while ((newStart & (UTRIE2_DATA_GRANULARITY - 1)) != 0) { this.data[newStart++] = this.initialValue; } this.dataLength = newStart; } private void CompactIndex2() { int i, start, newStart, movedStart, overlap; // do not compact linear-BMP index-2 blocks newStart = UTRIE2_INDEX_2_BMP_LENGTH; for (start = 0, i = 0; start < newStart; start += UTRIE2_INDEX_2_BLOCK_LENGTH, ++i) { this.map[i] = start; } // Reduce the index table gap to what will be needed at runtime. newStart += UTRIE2_UTF8_2B_INDEX_2_LENGTH + ((this.highStart - 0x10000) >> UTRIE2_SHIFT_1); for (start = UNEWTRIE2_INDEX_2_NULL_OFFSET; start < this.index2Length;) { // start: index of first entry of current block // newStart: index where the current block is to be moved // (right after current end of already-compacted data) // // search for an identical block if ((movedStart = this.FindSameIndex2Block(newStart, start)) >= 0) { // found an identical block, set the other block's index value for the current block this.map[start >> UTRIE2_SHIFT_1_2] = movedStart; // advance start to the next block start += UTRIE2_INDEX_2_BLOCK_LENGTH; // leave newStart with the previous block! continue; } // see if the beginning of this block can be overlapped with the end of the previous block // look for maximum overlap with the previous, adjacent block for (overlap = UTRIE2_INDEX_2_BLOCK_LENGTH - 1; overlap > 0 && !Equal(this.index2, newStart - overlap, start, overlap); --overlap) { } if (overlap > 0 || newStart < start) { // some overlap, or just move the whole block this.map[start >> UTRIE2_SHIFT_1_2] = newStart - overlap; // move the non-overlapping indexes to their new positions start += overlap; for (i = UTRIE2_INDEX_2_BLOCK_LENGTH - overlap; i > 0; --i) { this.index2[newStart++] = this.index2[start++]; } } else { // no overlap && newStart==start this.map[start >> UTRIE2_SHIFT_1_2] = start; start += UTRIE2_INDEX_2_BLOCK_LENGTH; newStart = start; } } // now adjust the index-1 table for (i = 0; i < UNEWTRIE2_INDEX_1_LENGTH; ++i) { this.index1[i] = this.map[this.index1[i] >> UTRIE2_SHIFT_1_2]; } this.index2NullOffset = this.map[this.index2NullOffset >> UTRIE2_SHIFT_1_2]; // Ensure data table alignment: // Needs to be granularity-aligned for 16-bit trie // (so that dataMove will be down-shiftable), // and 2-aligned for uint32_t data. while ((newStart & ((UTRIE2_DATA_GRANULARITY - 1) | 1)) != 0) { // Arbitrary value: 0x3fffc not possible for real data. this.index2[newStart++] = 0xffff << UTRIE2_INDEX_SHIFT; } this.index2Length = newStart; } private static bool Equal(uint[] a, int s, int t, int length) { for (int i = 0; i < length; i++) { if (a[s + i] != a[t + i]) { return false; } } return true; } private static bool Equal(int[] a, int s, int t, int length) { for (int i = 0; i < length; i++) { if (a[s + i] != a[t + i]) { return false; } } return true; } } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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. //----------------------------------------------------------------------------- // Common code for object selection dialogs. //============================================================================================= // Initialization. //============================================================================================= //--------------------------------------------------------------------------------------------- function EObjectSelection::init( %this ) { // Initialize the class list. %classList = %this-->classList; if( isObject( %classList ) ) %this.initClassList(); // Initialize the filter list. %filterList = %this-->filterList; if( isObject( %filterList ) ) %this.initFilterList(); // Initialize the group list. %groupList = %this-->groupList; if( isObject( %groupList ) ) %this.initGroupList(); } //--------------------------------------------------------------------------------------------- function EObjectSelection::cleanup( %this ) { // Clear the class list. %classList = %this-->classList; if( isObject( %classList ) ) %classList.clear(); // Clear the filter list. %filterList = %this-->filterList; if( isObject( %filterList ) ) %filterList.clear(); // Clear the group list. %groupList = %this-->groupList; if( isObject( %groupList ) ) %groupList.clear(); // Delete the class array. if( isObject( %this.classArray ) ) %this.classArray.delete(); } //============================================================================================= // Methods to override in a subclass. //============================================================================================= //--------------------------------------------------------------------------------------------- /// Return the group object where onSelectObjects should begin searching for objects. function EObjectSelection::getRootGroup( %this ) { return RootGroup; } //--------------------------------------------------------------------------------------------- /// Return a set that contains all filter objects to include in the filter list. /// Returning 0 will leave the filter list empty. function EObjectSelection::getFilterSet( %this ) { return 0; } //--------------------------------------------------------------------------------------------- /// Return true if the given class should be included in the class list. function EObjectSelection::includeClass( %this, %className ) { return true; } //--------------------------------------------------------------------------------------------- /// The object has met the given criteria. Select or deselect it depending on %val. function EObjectSelection::selectObject( %this, %object, %val ) { } //============================================================================================= // Events. //============================================================================================= //--------------------------------------------------------------------------------------------- function EObjectSelection::onSelectObjects( %this, %val ) { // Get the root group to search in. %groupList = %this-->groupList; if( !isObject( %groupList ) ) %root = %this.getRootGroup(); else %root = %groupList.getSelected(); if( !isObject( %root ) ) return; // Fetch the object name pattern. %namePatternField = %this-->namePattern; if( isObject( %namePatternField ) ) %this.namePattern = %namePatternField.getText(); else %this.namePattern = ""; // Clear current selection first, if need be. if( %val ) { %retainSelectionBox = %this-->retainSelection; if( isObject( %retainSelectionBox ) && !%retainSelectionBox.isStateOn() ) %this.clearSelection(); } // (De)Select all matching objects in it. %this.selectObjectsIn( %root, %val, true ); } //============================================================================================= // Selection. //============================================================================================= //--------------------------------------------------------------------------------------------- function EObjectSelection::selectObjectsIn( %this, %group, %val, %excludeGroup ) { // Match to the group itself. if( !%excludeGroup && %this.objectMatchesCriteria( %group ) ) %this.selectObject( %group, %val ); // Recursively match all children. foreach( %obj in %group ) { if( %obj.isMemberOfClass( "SimSet" ) ) %this.selectObjectsIn( %obj, %val ); else if( %this.objectMatchesCriteria( %obj ) ) %this.selectObject( %obj, %val ); } } //--------------------------------------------------------------------------------------------- function EObjectSelection::objectMatchesCriteria( %this, %object ) { // Check name. if( %this.namePattern !$= "" && !strIsMatchExpr( %this.namePattern, %object.getName() ) ) return false; // Check class. if( !%this.isClassEnabled( %object.getClassName() ) ) return false; return true; } //============================================================================================= // Groups. //============================================================================================= //--------------------------------------------------------------------------------------------- function EObjectSelection::initGroupList( %this ) { %groupList = %this-->groupList; %selected = 0; if( %groupList.size() > 0 ) %selected = %groupList.getSelected(); %groupList.clear(); %root = %this.getRootGroup(); if( !isObject( %root ) ) return; // Add all non-empty groups. %this.scanGroup( %root, %groupList, 0 ); // Select initial group. if( %selected != 0 && isObject( %selected ) ) %groupList.setSelected( %selected ); else %groupList.setSelected( %root.getId() ); } //--------------------------------------------------------------------------------------------- function EObjectSelection::scanGroup( %this, %group, %list, %indentLevel ) { // Create a display name for the group. %text = %group.getName(); if( %text $= "" ) %text = %group.getClassName(); %internalName = %group.getInternalName(); if( %internalName !$= "" ) %text = %text @ " [" @ %internalName @ "]"; // Indent the name according to the depth in the hierarchy. if( %indentLevel > 0 ) %text = strrepeat( " ", %indentLevel ) @ %text; // Add it to the list. %list.add( %text, %group.getId() ); // Recurse into SimSets with at least one child. foreach ( %obj in %group ) { if( !%obj.isMemberOfClass( "SimSet" ) || %obj.getCount() == 0 ) continue; %this.scanGroup( %obj, %list, %indentLevel + 1 ); } } //============================================================================================= // Filters. //============================================================================================= //--------------------------------------------------------------------------------------------- function EObjectSelection::initFilterList( %this ) { %filterList = %this-->filterList; } //============================================================================================= // Classes. //============================================================================================= //--------------------------------------------------------------------------------------------- /// Initialize the list of class toggles. function EObjectSelection::initClassList( %this ) { %classArray = new ArrayObject(); %this.classArray = %classArray; // Add all classes to the array. %classes = enumerateConsoleClasses(); foreach$( %className in %classes ) { if( !%this.includeClass( %className ) ) continue; %classArray.push_back( %className, true ); } // Sort the class list. %classArray.sortk( true ); // Add checkboxes for all classes to the list. %classList = %this-->classList; %count = %classArray.count(); for( %i = 0; %i < %count; %i ++ ) { %className = %classArray.getKey( %i ); %textLength = strlen( %className ); %text = " " @ %className; %checkBox = new GuiCheckBoxCtrl() { canSaveDynamicFields = "0"; isContainer = "0"; Profile = "ToolsGuiCheckBoxListFlipedProfile"; HorizSizing = "right"; VertSizing = "bottom"; Position = "0 0"; Extent = ( %textLength * 4 ) @ " 18"; MinExtent = "8 2"; canSave = "0"; Visible = "1"; tooltipprofile = "ToolsGuiToolTipProfile"; hovertime = "1000"; tooltip = "Include/exclude all " @ %className @ " objects."; text = %text; groupNum = "-1"; buttonType = "ToggleButton"; useMouseEvents = "0"; useInactiveState = "0"; command = %classArray @ ".setValue( $ThisControl.getValue(), " @ %i @ " );"; }; %checkBox.setStateOn( true ); %classList.addGuiControl( %checkBox ); } } //--------------------------------------------------------------------------------------------- function EObjectSelection::selectAllInClassList( %this, %state ) { %classList = %this-->classList; foreach( %ctrl in %classList ) { if( %ctrl.getValue() == %state ) %ctrl.performClick(); } } //--------------------------------------------------------------------------------------------- function EObjectSelection::isClassEnabled( %this, %className ) { // Look up the class entry in the array. %index = %this.classArray.getIndexFromKey( %className ); if( %index == -1 ) return false; // Return the flag. return %this.classArray.getValue( %index ); }
using System; using System.Collections.Generic; using UnityEngine; using Common; using Exploration; using Objects; namespace Extra { public class Analyzer { public enum Heuristic : int { Velocity = 0, Crazyness = 1, Danger = 2, Danger3 = 3, Danger3Norm = 4, Los = 5, Los3 = 6, Los3Norm = 7 } // This is to hold the time for each heuristic used so we can export/save this data later [Heuristic] [Time] public static Dictionary<Path, float[][]> pathMap = new Dictionary<Path, float[][]> (); public static float[][] ComputeSeenValuesGrid (Cell[][][] fullMap, out float max) { float[][] metric = new float[fullMap [0].Length][]; max = 0f; for (int x = 0; x < metric.Length; x++) { metric [x] = new float[fullMap [0] [0].Length]; for (int y = 0; y < metric[0].Length; y++) { for (int t = 0; t < fullMap.Length; t++) { metric [x] [y] += ((Cell)fullMap [t] [x] [y]).seen ? 1f : 0f; } if (metric [x] [y] > max) max = metric [x] [y]; } } return metric; } private static float ComputeLength3D (List<Node> length) { float total = 0f; Node n = length [length.Count - 1]; while (n.parent != null) { total += n.DistanceFrom (n.parent); n = n.parent; } return total; } // This must be called before a single path analysis or a batch path analysis if, and only if you want to export/save the time-per-heuristic public static void PreparePaths (List<Path> paths) { Heuristic[] values = (Heuristic[])Enum.GetValues (typeof(Analyzer.Heuristic)); pathMap.Clear (); foreach (Path path in paths) { if (!(pathMap.ContainsKey (path))) { pathMap.Add (path, new float[Enum.GetValues (typeof(Analyzer.Heuristic)).Length][]); path.ZeroValues(); } foreach (Heuristic metric in values) pathMap [path] [(int)metric] = new float[path.points [path.points.Count - 1].t]; } } #region Comparers public class TimeComparer : IComparer<Path> { public int Compare (Path path1, Path path2) { return Mathf.FloorToInt (path1.time - path2.time); } } public class Length2dComparer : IComparer<Path> { public int Compare (Path path1, Path path2) { return Mathf.FloorToInt (path1.length2d - path2.length2d); } } public class DangerComparer : IComparer<Path> { public int Compare (Path path1, Path path2) { return Mathf.FloorToInt (path2.danger - path1.danger); } } public class Danger3Comparer : IComparer<Path> { public int Compare (Path path1, Path path2) { return Mathf.FloorToInt (path2.danger3 - path1.danger3); } } public class Danger3NormComparer : IComparer<Path> { public int Compare (Path path1, Path path2) { return Mathf.FloorToInt (path2.danger3Norm - path1.danger3Norm); } } public class LoSComparer : IComparer<Path> { public int Compare (Path path1, Path path2) { return Mathf.FloorToInt (path2.los - path1.los); } } public class LoS3Comparer : IComparer<Path> { public int Compare (Path path1, Path path2) { return Mathf.FloorToInt (path2.los3 - path1.los3); } } public class LoS3NormComparer : IComparer<Path> { public int Compare (Path path1, Path path2) { return Mathf.FloorToInt (path2.los3Norm - path1.los3Norm); } } public class CrazyComparer : IComparer<Path> { public int Compare (Path path1, Path path2) { return Mathf.FloorToInt (path2.crazy - path1.crazy); } } public class VelocityComparer : IComparer<Path> { public int Compare (Path path1, Path path2) { return Mathf.FloorToInt (path2.velocity - path1.velocity); } } #endregion #region Paths values public static void ComputePathsTimeValues (List<Path> paths) { foreach (Path path in paths) path.time = path.points [path.points.Count - 1].t; } public static void ComputePathsLengthValues (List<Path> paths) { foreach (Path path in paths) { Node n = path.points [path.points.Count - 1]; while (n.parent != null) { path.length2d += Vector2.Distance (n.GetVector2 (), n.parent.GetVector2 ()); path.length3d += n.DistanceFrom (n.parent); n = n.parent; } } } public static void ComputePathsVelocityValues (List<Path> paths) { foreach (Path path in paths) { Node n = path.points [path.points.Count - 1]; while (n.parent != null && n.parent.parent != null) { Vector3 p1 = n.GetVector3 (); Vector3 p2 = n.parent.GetVector3 (); Vector3 p3 = n.parent.parent.GetVector3 (); Vector3 v1 = p1 - p2; Vector3 v2 = p2 - p3; v1.z = 0f; v2.z = 0f; v1.Normalize (); v2.Normalize (); float angle1 = Vector3.Angle (v1, Vector3.up); float angle2 = Vector3.Angle (v2, Vector3.up); float result = Mathf.Abs (angle2 - angle1); path.velocity += result; if (pathMap.ContainsKey(path)) pathMap [path] [(int)Heuristic.Velocity] [n.parent.t] = Mathf.Abs (angle2 - angle1); n = n.parent; } if (path.length3d == 0) path.length3d = ComputeLength3D (path.points); path.velocity /= path.length3d; } } public static void ComputePathsLoSValues (List<Path> paths, Enemy[] enemies, Vector3 min, float tileSizeX, float tileSizeZ, Cell[][][] fullMap, float[][] dangerCells, float maxDanger) { // Compute the y = ax + b equation for each FoV (i.e. enemy=) float[][] formula = new float[enemies.Length][]; for (int i = 0; i < formula.Length; i++) { formula [i] = new float[2]; formula [i] [0] = (180 - enemies [i].fovAngle) * -2; formula [i] [1] = enemies [i].fovAngle - formula [i] [0]; } DDA dda = new DDA(tileSizeX, tileSizeZ, fullMap [0].Length, fullMap [0] [0].Length); foreach (Path currentPath in paths) { if (currentPath.length3d == 0) currentPath.length3d = ComputeLength3D (currentPath.points); Node cur = currentPath.points [currentPath.points.Count - 1]; Node par = cur.parent; while (cur.parent != null) { Vector3 p1 = cur.GetVector3 (); Vector3 p2 = par.GetVector3 (); Vector3 pd = p1 - p2; float pt = (cur.t - par.t); // Navigate through time to find the right cells to start from for (int t = 0; t < pt; t++) { float delta = ((float)t) / pt; Vector3 pos = p2 + pd * delta; for (int enemyIndex = 0; enemyIndex < enemies.Length; enemyIndex++) { Vector3 enemy = enemies [enemyIndex].positions [par.t + t]; Vector2 pos2d = new Vector2 (pos.x, pos.z); Vector2 enemy2d = new Vector2 ((enemy.x - min.x) / tileSizeX, (enemy.z - min.z) / tileSizeZ); bool seen = dda.HasLOS(fullMap[par.t + t], pos2d, enemy2d); // If the cell is in LoS if (seen && enemies [enemyIndex].cells [par.t + t].Length > 0) { // Grab the cell closest to my position Vector2 shortest = enemies [enemyIndex].cells [par.t + t] [0]; float dist = Vector2.Distance (shortest, pos2d); float ddist; for (int k = 1; k < enemies[enemyIndex].cells[par.t + t].Length; k++) { ddist = Vector2.Distance (enemies [enemyIndex].cells [par.t + t] [k], pos2d); if (ddist < dist) { dist = ddist; shortest = enemies [enemyIndex].cells [par.t + t] [k]; } } // Calculate the angle between them float angle = Vector2.Angle (enemies [enemyIndex].positions [par.t + t].normalized, (pos2d - enemy2d).normalized); if (angle <= enemies [enemyIndex].fovAngle) angle = 1; else { angle = (angle - formula [enemyIndex] [1]) / formula [enemyIndex] [0]; } float f = angle / (pos2d - shortest).sqrMagnitude; float g = angle / Mathf.Pow ((pos2d - shortest).magnitude, 3); if (f == Mathf.Infinity) { f = angle / (pos2d - enemy2d).sqrMagnitude; } if (g == Mathf.Infinity) { g = angle / Mathf.Pow ((pos2d - enemy2d).magnitude, 3); } float g3 = g * (dangerCells [(int)pos2d.x] [(int)pos2d.y] / maxDanger); // Increment the total metric currentPath.los += f; currentPath.los3 += g; currentPath.los3Norm += g3; if (pathMap.ContainsKey(currentPath)) { // Store in 'per-time' metric pathMap [currentPath] [(int)Heuristic.Los] [par.t + t] = f; pathMap [currentPath] [(int)Heuristic.Los3] [par.t + t] = g; pathMap [currentPath] [(int)Heuristic.Los3Norm] [par.t + t] = g3; } } } } cur = par; par = par.parent; } currentPath.los /= currentPath.length3d; currentPath.los3 /= currentPath.length3d; currentPath.los3Norm /= currentPath.length3d; } } public static void ComputePathsDangerValues (List<Path> paths, Enemy[] enemies, Vector3 min, float tileSizeX, float tileSizeZ, Cell[][][] fullMap, float[][] dangerCells, float maxDanger) { AStar astar = new AStar (); foreach (Path currentPath in paths) { if (currentPath.length3d == 0) currentPath.length3d = ComputeLength3D (currentPath.points); Node cur = currentPath.points [currentPath.points.Count - 1]; Node par = cur.parent; while (cur.parent != null) { Vector3 p1 = cur.GetVector3 (); Vector3 p2 = par.GetVector3 (); Vector3 pd = p1 - p2; float pt = (cur.t - par.t); // Navigate through time to find the right cells to start from for (int t = 0; t < pt; t++) { float delta = ((float)t) / pt; Vector3 pos = p2 + pd * delta; foreach (Enemy each in enemies) { Vector3 enemy = each.positions [par.t + t]; int startX = (int)pos.x; int startY = (int)pos.z; int endX = (int)((enemy.x - min.x) / tileSizeX); int endY = (int)((enemy.z - min.z) / tileSizeZ); // Do A* from the player to the enemy to compute the cost List<Node> astarpath = astar.Compute (startX, startY, endX, endY, fullMap [par.t + t], true); if (astarpath.Count > 0) { float l = ComputeLength3D (astarpath); float ld = 1 / (l * l); float ld3 = 1 / (l * l * l); float ld3n = (1 / (l * l * l)) * (dangerCells [startX] [startY] / maxDanger); currentPath.danger += ld; currentPath.danger3 += ld3; currentPath.danger3Norm += ld3n; if (pathMap.ContainsKey(currentPath)) { // Store in 'per-time' metric pathMap [currentPath] [(int)Heuristic.Danger] [par.t + t] = ld; pathMap [currentPath] [(int)Heuristic.Danger3] [par.t + t] = ld3; pathMap [currentPath] [(int)Heuristic.Danger3Norm] [par.t + t] = ld3n; } } } } cur = par; par = par.parent; } currentPath.danger /= currentPath.length3d; currentPath.danger3 /= currentPath.length3d; currentPath.danger3Norm /= currentPath.length3d; } } public static void ComputeCrazyness (List<Path> paths, Cell[][][] fullMap, int stepsBehind) { foreach (Path currentPath in paths) { Node cur = currentPath.points [currentPath.points.Count - 1]; Node par = cur.parent; while (cur.parent != null) { Vector3 p1 = cur.GetVector3 (); Vector3 p2 = par.GetVector3 (); Vector3 pd = p1 - p2; float pt = (cur.t - par.t); // Navigate through time to find the right cells to start from for (int t = 0; t < pt; t++) { float delta = ((float)t) / pt; Vector3 pos = p2 + pd * delta; int x = (int)pos.x; int y = (int)pos.z; float tempCrazy = 0f; for (int back = 1; back <= stepsBehind; back++) { // Look back in time to search for visible cells if ((par.t + t - back) > 0 && fullMap [par.t + t - back] [x] [y].seen) { tempCrazy += Mathf.Pow (stepsBehind - back, 2); } //Do the in front if ((par.t + t + back) < fullMap.Length && fullMap [par.t + t + back] [x] [y].seen) { tempCrazy += Mathf.Pow (stepsBehind - back, 2); } } currentPath.crazy += tempCrazy; if (pathMap.ContainsKey(currentPath)) pathMap [currentPath] [(int)Heuristic.Crazyness] [par.t + t] = tempCrazy; } cur = par; par = par.parent; } } } #endregion public static int[][,] Compute3DHeatMap (List<Path> paths, int sizeX, int sizeY, int sizeT, out int[] maxN) { // Initialization int[][,] heatMap = new int[sizeT][,]; for (int t = 0; t < sizeT; t++) heatMap [t] = new int[sizeX, sizeY]; maxN = new int[sizeT]; foreach (Path path in paths) { foreach (Node node in path.points) { if (node.parent == null) { continue; } Vector3 pos = new Vector3 (node.x, node.y, node.t); Vector3 p = new Vector3 (node.parent.x, node.parent.y, node.parent.t); Vector3 res = (p - pos).normalized; //which box of the map we're in int mapX = node.x; int mapY = node.y; int mapT = node.t; //length of ray from current position to next x or y-side float sideDistX; float sideDistY; float sideDistT; //length of ray from one x or y-side to next x or y-side float deltaDistX = 1 / Mathf.Abs (res.x); float deltaDistY = 1 / Mathf.Abs (res.y); float deltaDistT = 1 / Mathf.Abs (res.z); //what direction to step in x or y-direction (either +1 or -1) int stepX; int stepY; int stepT; //calculate step and initial sideDist if (res.x < 0) { stepX = -1; sideDistX = (pos.x - mapX) * deltaDistX; } else { stepX = 1; sideDistX = (mapX + 1 - pos.x) * deltaDistX; } if (res.y < 0) { stepY = -1; sideDistY = (pos.y - mapY) * deltaDistY; } else { stepY = 1; sideDistY = (mapY + 1 - pos.y) * deltaDistY; } if (res.z < 0) { stepT = -1; sideDistT = (pos.z - mapT) * deltaDistT; } else { stepT = 1; sideDistT = (mapT + 1 - pos.z) * deltaDistT; } bool done = false; //perform DDA while (!done) { heatMap [mapT] [mapX, mapY] += 10; //jump to next map square, OR in x-direction, OR in y-direction if (sideDistX <= sideDistY && sideDistX <= sideDistT) { sideDistX += deltaDistX; mapX += stepX; } else if (sideDistY <= sideDistT) { sideDistY += deltaDistY; mapY += stepY; } else { sideDistT += deltaDistT; mapT += stepT; } // Check map boundaries if (stepX == 1) { if (mapX > node.parent.x) done = true; } else if (mapX < node.parent.x) done = true; if (stepY == 1) { if (mapY > node.parent.y) done = true; } else if (mapY < node.parent.y) done = true; if (stepT == 1) { if (mapT > node.parent.t) done = true; } else if (mapT < node.parent.t) done = true; // Paint adjacent ones if (!done) for (int t = mapT - 1; t <= mapT + 1; t++) for (int x = mapX - 1; x <= mapX + 1; x++) for (int y = mapY - 1; y <= mapY + 1; y++) if (!(x < 0 || y < 0 || x >= sizeX || y >= sizeY || t < 0 || t >= sizeT)) { heatMap [t] [x, y]++; if (heatMap [t] [x, y] > maxN [t]) maxN [t] = heatMap [t] [x, y]; } if (node.parent.x == mapX && node.parent.y == mapY) { // End the algorithm on reach done = true; } } } } return heatMap; } public static int[,] ComputeDeathHeatMap (List<Path> paths, int sizeX, int sizeY, out int maxN) { maxN = -1; int[,] heatMap = new int[sizeX, sizeY]; foreach (Path path in paths) { Node death = path.points[path.points.Count-1]; // Paint adjacent nodes for (int x = death.x -2; x >= 0 && x <= death.x + 2 && x < sizeX; x++) for (int y = death.y -2; y >= 0 && y <= death.y + 2 && y < sizeY; y++) { int dx = Math.Abs(death.x - x); int dy = Math.Abs(death.y - y); heatMap[x,y] += (5 - dx - dy); } // Main node heatMap[death.x, death.y] += 10; } // Get maxN for (int x = 0; x < sizeX; x++) { for (int y = 0; y < sizeY; y++) { if (maxN < heatMap [x, y]) maxN = heatMap [x, y]; } } return heatMap; } public static int[][,] Compute3dDeathHeatMap (List<Path> paths, int sizeX, int sizeY, int sizeT, out int[] maxN) { maxN = new int[sizeT]; int[][,] heatMap = new int[sizeT][,]; for (int t = 0; t < sizeT; t++) heatMap[t] = new int[sizeX,sizeY]; foreach (Path path in paths) { Node death = path.points[path.points.Count-1]; // Paint adjacent nodes for (int t = death.t -2; t >= 0 && t <= death.t + 2 && t < sizeT; t++){ for (int x = death.x -2; x >= 0 && x <= death.x + 2 && x < sizeX; x++){ for (int y = death.y -2; y >= 0 && y <= death.y + 2 && y < sizeY; y++) { int dx = Math.Abs(death.x - x); int dy = Math.Abs(death.y - y); int dt = Math.Abs(death.t - t); heatMap[t][x,y] += (7 - dx - dy - dt); } } } // Main node heatMap[death.t][death.x, death.y] += 15; } // Get maxN for (int t = 0; t < sizeT; t++) { for (int x = 0; x < sizeX; x++) { for (int y = 0; y < sizeY; y++) { if (maxN[t] < heatMap [t][x, y]) maxN[t] = heatMap [t][x, y]; } } } return heatMap; } public static int[,] Compute2DHeatMap (List<Path> paths, int sizeX, int sizeY, out int maxN) { maxN = -1; int[,] heatMap = new int[sizeX, sizeY]; foreach (Path path in paths) { int[,] hm = new int[sizeX, sizeY]; foreach (Node node in path.points) { if (node.parent == null || node.parent == node) { hm [node.x, node.y] += 10; continue; } // Perform the DDA line algorithm // Based on http://lodev.org/cgtutor/raycasting.html Vector2 pos = new Vector2 (node.x, node.y); Vector2 p = new Vector2 (node.parent.x, node.parent.y); Vector2 res = (p - pos).normalized; //which box of the map we're in int mapX = Mathf.FloorToInt (node.x); int mapY = Mathf.FloorToInt (node.y); //length of ray from current position to next x or y-side float sideDistX; float sideDistY; //length of ray from one x or y-side to next x or y-side float deltaDistX = Mathf.Sqrt (1 + (res.y * res.y) / (res.x * res.x)); float deltaDistY = Mathf.Sqrt (1 + (res.x * res.x) / (res.y * res.y)); //what direction to step in x or y-direction (either +1 or -1) int stepX; int stepY; //calculate step and initial sideDist if (res.x < 0) { stepX = -1; sideDistX = (pos.x - mapX) * deltaDistX; } else { stepX = 1; sideDistX = (mapX + 1 - pos.x) * deltaDistX; } if (res.y < 0) { stepY = -1; sideDistY = (pos.y - mapY) * deltaDistY; } else { stepY = 1; sideDistY = (mapY + 1 - pos.y) * deltaDistY; } bool done = false; //perform DDA while (!done) { hm [mapX, mapY] += 10; //jump to next map square, OR in x-direction, OR in y-direction if (sideDistX <= sideDistY) { sideDistX += deltaDistX; mapX += stepX; } else { sideDistY += deltaDistY; mapY += stepY; } for (int x = mapX - 1; x <= mapX + 1; x++) for (int y = mapY - 1; y <= mapY + 1; y++) if (!(x < 0 || y < 0 || x >= sizeX || y >= sizeY)) hm [x, y]++; // Check map boundaries if (stepX == 1) { if (mapX > node.parent.x) done = true; } else if (mapX < node.parent.x) done = true; if (stepY == 1) { if (mapY > node.parent.y) done = true; } else if (mapY < node.parent.y) done = true; if (node.parent.x == mapX && node.parent.y == mapY) { // End the algorithm done = true; } } } // Pass to the global heatmap for (int x = 0; x < sizeX; x++) { for (int y = 0; y < sizeY; y++) { heatMap [x, y] += hm [x, y]; } } } for (int y = 0; y < sizeX; y++) { String s = ""; for (int x = 0; x < sizeY; x++) { s += "" + heatMap [x, y] + " "; if (maxN < heatMap [x, y]) maxN = heatMap [x, y]; } } return heatMap; } public static int[,] Compute2DCombatHeatMap (List<Path> paths, List<Path> deaths, int sizeX, int sizeY, out int maxN) { List<Path> all = new List<Path>(paths); all.AddRange(deaths); int[,] map = new int[sizeX,sizeY]; maxN = 0; foreach (Path path in all) { foreach (Node n in path.points) { if (n.fighting != null && n.fighting.Count > 0) { // Paint adjacent nodes for (int x = n.x -2; x >= 0 && x <= n.x + 2 && x < sizeX; x++){ for (int y = n.y -2; y >= 0 && y <= n.y + 2 && y < sizeY; y++) { int dx = Math.Abs(n.x - x); int dy = Math.Abs(n.y - y); map[x,y] += (5 - dx - dy); } } map[n.x,n.y] += 10; maxN = Mathf.Max(map[n.x, n.y], maxN); } } } return map; } } }
// Copyright 2011 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using NodaTime.Text; using NodaTime.Text.Patterns; using NUnit.Framework; namespace NodaTime.Test.Text { public partial class LocalTimePatternTest : PatternTestBase<LocalTime> { private static readonly DateTime SampleDateTime = new DateTime(2000, 1, 1, 21, 13, 34, 123, DateTimeKind.Unspecified).AddTicks(4567); private static readonly LocalTime SampleLocalTime = LocalTime.FromHourMinuteSecondMillisecondTick(21, 13, 34, 123, 4567); // Characters we expect to work the same in Noda Time as in the BCL. private const string ExpectedCharacters = "hHms.:fFtT "; private static readonly CultureInfo AmOnlyCulture = CreateCustomAmPmCulture("am", ""); private static readonly CultureInfo PmOnlyCulture = CreateCustomAmPmCulture("", "pm"); private static readonly CultureInfo NoAmOrPmCulture = CreateCustomAmPmCulture("", ""); internal static readonly Data[] InvalidPatternData = { new Data { Pattern = "", Message = TextErrorMessages.FormatStringEmpty }, new Data { Pattern = "!", Message = TextErrorMessages.UnknownStandardFormat, Parameters = {'!', typeof(LocalTime).FullName}}, new Data { Pattern = "%", Message = TextErrorMessages.UnknownStandardFormat, Parameters = { '%', typeof(LocalTime).FullName } }, new Data { Pattern = "\\", Message = TextErrorMessages.UnknownStandardFormat, Parameters = { '\\', typeof(LocalTime).FullName } }, new Data { Pattern = "%%", Message = TextErrorMessages.PercentDoubled }, new Data { Pattern = "%\\", Message = TextErrorMessages.EscapeAtEndOfString }, new Data { Pattern = "ffffffffff", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 'f', 9 } }, new Data { Pattern = "FFFFFFFFFF", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 'F', 9 } }, new Data { Pattern = "H%", Message = TextErrorMessages.PercentAtEndOfString }, new Data { Pattern = "HHH", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 'H', 2 } }, new Data { Pattern = "mmm", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 'm', 2 } }, new Data { Pattern = "mmmmmmmmmmmmmmmmmmm", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 'm', 2 } }, new Data { Pattern = "'qwe", Message = TextErrorMessages.MissingEndQuote, Parameters = { '\'' } }, new Data { Pattern = "'qwe\\", Message = TextErrorMessages.EscapeAtEndOfString }, new Data { Pattern = "'qwe\\'", Message = TextErrorMessages.MissingEndQuote, Parameters = { '\'' } }, new Data { Pattern = "sss", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 's', 2 } }, // T isn't valid in a time pattern new Data { Pattern = "1970-01-01THH:mm:ss", Message = TextErrorMessages.UnquotedLiteral, Parameters = { 'T' } } }; internal static Data[] ParseFailureData = { new Data { Text = "17 6", Pattern = "HH h", Message = TextErrorMessages.InconsistentValues2, Parameters = {'H', 'h', typeof(LocalTime).FullName}}, new Data { Text = "17 AM", Pattern = "HH tt", Message = TextErrorMessages.InconsistentValues2, Parameters = {'H', 't', typeof(LocalTime).FullName}}, new Data { Text = "5 foo", Pattern = "h t", Message = TextErrorMessages.MissingAmPmDesignator}, new Data { Text = "04.", Pattern = "ss.FF", Message = TextErrorMessages.MismatchedNumber, Parameters = { "FF" } }, new Data { Text = "04.", Pattern = "ss;FF", Message = TextErrorMessages.MismatchedNumber, Parameters = { "FF" } }, new Data { Text = "04.", Pattern = "ss.ff", Message = TextErrorMessages.MismatchedNumber, Parameters = { "ff" } }, new Data { Text = "04.", Pattern = "ss;ff", Message = TextErrorMessages.MismatchedNumber, Parameters = { "ff" } }, new Data { Text = "04.x", Pattern = "ss.FF", Message = TextErrorMessages.MismatchedNumber, Parameters = { "FF" } }, new Data { Text = "04.x", Pattern = "ss;FF", Message = TextErrorMessages.MismatchedNumber, Parameters = { "FF" } }, new Data { Text = "04.x", Pattern = "ss.ff", Message = TextErrorMessages.MismatchedNumber, Parameters = { "ff" } }, new Data { Text = "04.x", Pattern = "ss;ff", Message = TextErrorMessages.MismatchedNumber, Parameters = { "ff" } }, new Data { Text = "05 Foo", Pattern = "HH tt", Message = TextErrorMessages.MissingAmPmDesignator } }; internal static Data[] ParseOnlyData = { new Data(0, 0, 0, 400) { Text = "4", Pattern = "%f", }, new Data(0, 0, 0, 400) { Text = "4", Pattern = "%F", }, new Data(0, 0, 0, 400) { Text = "4", Pattern = "FF", }, new Data(0, 0, 0, 400) { Text = "40", Pattern = "FF", }, new Data(0, 0, 0, 400) { Text = "4", Pattern = "FFF", }, new Data(0, 0, 0, 400) { Text = "40", Pattern = "FFF" }, new Data(0, 0, 0, 400) { Text = "400", Pattern = "FFF" }, new Data(0, 0, 0, 400) { Text = "40", Pattern = "ff", }, new Data(0, 0, 0, 400) { Text = "400", Pattern = "fff", }, new Data(0, 0, 0, 400) { Text = "4000", Pattern = "ffff", }, new Data(0, 0, 0, 400) { Text = "40000", Pattern = "fffff", }, new Data(0, 0, 0, 400) { Text = "400000", Pattern = "ffffff", }, new Data(0, 0, 0, 400) { Text = "4000000", Pattern = "fffffff", }, new Data(0, 0, 0, 450) { Text = "45", Pattern = "ff" }, new Data(0, 0, 0, 450) { Text = "45", Pattern = "FF" }, new Data(0, 0, 0, 450) { Text = "45", Pattern = "FFF" }, new Data(0, 0, 0, 450) { Text = "450", Pattern = "fff" }, new Data(0, 0, 0, 456) { Text = "456", Pattern = "fff" }, new Data(0, 0, 0, 456) { Text = "456", Pattern = "FFF" }, new Data(0, 0, 0, 0) { Text = "0", Pattern = "%f" }, new Data(0, 0, 0, 0) { Text = "00", Pattern = "ff" }, new Data(0, 0, 0, 8) { Text = "008", Pattern = "fff" }, new Data(0, 0, 0, 8) { Text = "008", Pattern = "FFF" }, new Data(5, 0, 0, 0) { Text = "05", Pattern = "HH" }, new Data(0, 6, 0, 0) { Text = "06", Pattern = "mm" }, new Data(0, 0, 7, 0) { Text = "07", Pattern = "ss" }, new Data(5, 0, 0, 0) { Text = "5", Pattern = "%H" }, new Data(0, 6, 0, 0) { Text = "6", Pattern = "%m" }, new Data(0, 0, 7, 0) { Text = "7", Pattern = "%s" }, // AM/PM designator is case-insensitive for both short and long forms new Data(17, 0, 0, 0) { Text = "5 p", Pattern = "h t" }, new Data(17, 0, 0, 0) { Text = "5 pm", Pattern = "h tt" }, // Parsing using the semi-colon "comma dot" specifier new Data(16, 05, 20, 352) { Pattern = "HH:mm:ss;fff", Text = "16:05:20,352" }, new Data(16, 05, 20, 352) { Pattern = "HH:mm:ss;FFF", Text = "16:05:20,352" }, // Empty fractional section new Data(0,0,4,0) { Text = "04", Pattern = "ssFF" }, new Data(0,0,4,0) { Text = "040", Pattern = "ssFF" }, new Data(0,0,4,0) { Text = "040", Pattern = "ssFFF" }, new Data(0,0,4,0) { Text = "04", Pattern = "ss.FF"}, }; internal static Data[] FormatOnlyData = { new Data(5, 6, 7, 8) { Text = "", Pattern = "%F" }, new Data(5, 6, 7, 8) { Text = "", Pattern = "FF" }, new Data(1, 1, 1, 400) { Text = "4", Pattern = "%f" }, new Data(1, 1, 1, 400) { Text = "4", Pattern = "%F" }, new Data(1, 1, 1, 400) { Text = "4", Pattern = "FF" }, new Data(1, 1, 1, 400) { Text = "4", Pattern = "FFF" }, new Data(1, 1, 1, 400) { Text = "40", Pattern = "ff" }, new Data(1, 1, 1, 400) { Text = "400", Pattern = "fff" }, new Data(1, 1, 1, 400) { Text = "4000", Pattern = "ffff" }, new Data(1, 1, 1, 400) { Text = "40000", Pattern = "fffff" }, new Data(1, 1, 1, 400) { Text = "400000", Pattern = "ffffff" }, new Data(1, 1, 1, 400) { Text = "4000000", Pattern = "fffffff" }, new Data(1, 1, 1, 450) { Text = "4", Pattern = "%f" }, new Data(1, 1, 1, 450) { Text = "4", Pattern = "%F" }, new Data(1, 1, 1, 450) { Text = "45", Pattern = "ff" }, new Data(1, 1, 1, 450) { Text = "45", Pattern = "FF" }, new Data(1, 1, 1, 450) { Text = "45", Pattern = "FFF" }, new Data(1, 1, 1, 450) { Text = "450", Pattern = "fff" }, new Data(1, 1, 1, 456) { Text = "4", Pattern = "%f" }, new Data(1, 1, 1, 456) { Text = "4", Pattern = "%F" }, new Data(1, 1, 1, 456) { Text = "45", Pattern = "ff" }, new Data(1, 1, 1, 456) { Text = "45", Pattern = "FF" }, new Data(1, 1, 1, 456) { Text = "456", Pattern = "fff" }, new Data(1, 1, 1, 456) { Text = "456", Pattern = "FFF" }, new Data(0,0,0,0) {Text = "", Pattern = "FF" }, new Data(5, 6, 7, 8) { Culture = Cultures.EnUs, Text = "0", Pattern = "%f" }, new Data(5, 6, 7, 8) { Culture = Cultures.EnUs, Text = "00", Pattern = "ff" }, new Data(5, 6, 7, 8) { Culture = Cultures.EnUs, Text = "008", Pattern = "fff" }, new Data(5, 6, 7, 8) { Culture = Cultures.EnUs, Text = "008", Pattern = "FFF" }, new Data(5, 6, 7, 8) { Culture = Cultures.EnUs, Text = "05", Pattern = "HH" }, new Data(5, 6, 7, 8) { Culture = Cultures.EnUs, Text = "06", Pattern = "mm" }, new Data(5, 6, 7, 8) { Culture = Cultures.EnUs, Text = "07", Pattern = "ss" }, new Data(5, 6, 7, 8) { Culture = Cultures.EnUs, Text = "5", Pattern = "%H" }, new Data(5, 6, 7, 8) { Culture = Cultures.EnUs, Text = "6", Pattern = "%m" }, new Data(5, 6, 7, 8) { Culture = Cultures.EnUs, Text = "7", Pattern = "%s" }, // The subminute values are truncated for the short pattern new Data(14, 15, 16) { Culture = Cultures.DotTimeSeparator, Text = "14.15", Pattern = "t" }, new Data(14, 15, 16) { Culture = Cultures.Invariant, Text = "14:15", Pattern = "t" }, }; internal static Data[] DefaultPatternData = { // Invariant culture uses HH:mm:ss for the "long" pattern new Data(5, 0, 0, 0) { Text = "05:00:00" }, new Data(5, 12, 0, 0) { Text = "05:12:00" }, new Data(5, 12, 34, 0) { Text = "05:12:34" }, // US uses hh:mm:ss tt for the "long" pattern new Data(17, 0, 0, 0) { Culture = Cultures.EnUs, Text = "5:00:00 PM" }, new Data(5, 0, 0, 0) { Culture = Cultures.EnUs, Text = "5:00:00 AM" }, new Data(5, 12, 0, 0) { Culture = Cultures.EnUs, Text = "5:12:00 AM" }, new Data(5, 12, 34, 0) { Culture = Cultures.EnUs, Text = "5:12:34 AM" }, }; internal static readonly Data[] TemplateValueData = { // Pattern specifies nothing - template value is passed through new Data(LocalTime.FromHourMinuteSecondMillisecondTick(1, 2, 3, 4, 5)) { Culture = Cultures.EnUs, Text = "X", Pattern = "'X'", Template = LocalTime.FromHourMinuteSecondMillisecondTick(1, 2, 3, 4, 5) }, // Tests for each individual field being propagated new Data(LocalTime.FromHourMinuteSecondMillisecondTick(1, 6, 7, 8, 9)) { Culture = Cultures.EnUs, Text = "06:07.0080009", Pattern = "mm:ss.FFFFFFF", Template = LocalTime.FromHourMinuteSecondMillisecondTick(1, 2, 3, 4, 5) }, new Data(LocalTime.FromHourMinuteSecondMillisecondTick(6, 2, 7, 8, 9)) { Culture = Cultures.EnUs, Text = "06:07.0080009", Pattern = "HH:ss.FFFFFFF", Template = LocalTime.FromHourMinuteSecondMillisecondTick(1, 2, 3, 4, 5) }, new Data(LocalTime.FromHourMinuteSecondMillisecondTick(6, 7, 3, 8, 9)) { Culture = Cultures.EnUs, Text = "06:07.0080009", Pattern = "HH:mm.FFFFFFF", Template = LocalTime.FromHourMinuteSecondMillisecondTick(1, 2, 3, 4, 5) }, new Data(LocalTime.FromHourMinuteSecondMillisecondTick(6, 7, 8, 4, 5)) { Culture = Cultures.EnUs, Text = "06:07:08", Pattern = "HH:mm:ss", Template = LocalTime.FromHourMinuteSecondMillisecondTick(1, 2, 3, 4, 5) }, // Hours are tricky because of the ways they can be specified new Data(new LocalTime(6, 2, 3)) { Culture = Cultures.EnUs, Text = "6", Pattern = "%h", Template = new LocalTime(1, 2, 3) }, new Data(new LocalTime(18, 2, 3)) { Culture = Cultures.EnUs, Text = "6", Pattern = "%h", Template = new LocalTime(14, 2, 3) }, new Data(new LocalTime(2, 2, 3)) { Culture = Cultures.EnUs, Text = "AM", Pattern = "tt", Template = new LocalTime(14, 2, 3) }, new Data(new LocalTime(14, 2, 3)) { Culture = Cultures.EnUs, Text = "PM", Pattern = "tt", Template = new LocalTime(14, 2, 3) }, new Data(new LocalTime(2, 2, 3)) { Culture = Cultures.EnUs, Text = "AM", Pattern = "tt", Template = new LocalTime(2, 2, 3) }, new Data(new LocalTime(14, 2, 3)) { Culture = Cultures.EnUs, Text = "PM", Pattern = "tt", Template = new LocalTime(2, 2, 3) }, new Data(new LocalTime(17, 2, 3)) { Culture = Cultures.EnUs, Text = "5 PM", Pattern = "h tt", Template = new LocalTime(1, 2, 3) }, }; /// <summary> /// Common test data for both formatting and parsing. A test should be placed here unless is truly /// cannot be run both ways. This ensures that as many round-trip type tests are performed as possible. /// </summary> internal static readonly Data[] FormatAndParseData = { new Data(LocalTime.Midnight) { Culture = Cultures.EnUs, Text = ".", Pattern = "%." }, new Data(LocalTime.Midnight) { Culture = Cultures.EnUs, Text = ":", Pattern = "%:" }, new Data(LocalTime.Midnight) { Culture = Cultures.DotTimeSeparator, Text = ".", Pattern = "%." }, new Data(LocalTime.Midnight) { Culture = Cultures.DotTimeSeparator, Text = ".", Pattern = "%:" }, new Data(LocalTime.Midnight) { Culture = Cultures.EnUs, Text = "H", Pattern = "\\H" }, new Data(LocalTime.Midnight) { Culture = Cultures.EnUs, Text = "HHss", Pattern = "'HHss'" }, new Data(0, 0, 0, 100) { Culture = Cultures.EnUs, Text = "1", Pattern = "%f" }, new Data(0, 0, 0, 100) { Culture = Cultures.EnUs, Text = "1", Pattern = "%F" }, new Data(0, 0, 0, 100) { Culture = Cultures.EnUs, Text = "1", Pattern = "FF" }, new Data(0, 0, 0, 100) { Culture = Cultures.EnUs, Text = "1", Pattern = "FFF" }, new Data(0, 0, 0, 100) { Culture = Cultures.EnUs, Text = "100000000", Pattern = "fffffffff" }, new Data(0, 0, 0, 100) { Culture = Cultures.EnUs, Text = "1", Pattern = "FFFFFFFFF" }, new Data(0, 0, 0, 120) { Culture = Cultures.EnUs, Text = "12", Pattern = "ff" }, new Data(0, 0, 0, 120) { Culture = Cultures.EnUs, Text = "12", Pattern = "FF" }, new Data(0, 0, 0, 120) { Culture = Cultures.EnUs, Text = "12", Pattern = "FFF" }, new Data(0, 0, 0, 123) { Culture = Cultures.EnUs, Text = "123", Pattern = "fff" }, new Data(0, 0, 0, 123) { Culture = Cultures.EnUs, Text = "123", Pattern = "FFF" }, new Data(0, 0, 0, 123, 4000) { Culture = Cultures.EnUs, Text = "1234", Pattern = "ffff" }, new Data(0, 0, 0, 123, 4000) { Culture = Cultures.EnUs, Text = "1234", Pattern = "FFFF" }, new Data(0, 0, 0, 123, 4500) { Culture = Cultures.EnUs, Text = "12345", Pattern = "fffff" }, new Data(0, 0, 0, 123, 4500) { Culture = Cultures.EnUs, Text = "12345", Pattern = "FFFFF" }, new Data(0, 0, 0, 123, 4560) { Culture = Cultures.EnUs, Text = "123456", Pattern = "ffffff" }, new Data(0, 0, 0, 123, 4560) { Culture = Cultures.EnUs, Text = "123456", Pattern = "FFFFFF" }, new Data(0, 0, 0, 123, 4567) { Culture = Cultures.EnUs, Text = "1234567", Pattern = "fffffff" }, new Data(0, 0, 0, 123, 4567) { Culture = Cultures.EnUs, Text = "1234567", Pattern = "FFFFFFF" }, new Data(0, 0, 0, 123456780L) { Culture = Cultures.EnUs, Text = "12345678", Pattern = "ffffffff" }, new Data(0, 0, 0, 123456780L) { Culture = Cultures.EnUs, Text = "12345678", Pattern = "FFFFFFFF" }, new Data(0, 0, 0, 123456789L) { Culture = Cultures.EnUs, Text = "123456789", Pattern = "fffffffff" }, new Data(0, 0, 0, 123456789L) { Culture = Cultures.EnUs, Text = "123456789", Pattern = "FFFFFFFFF" }, new Data(0, 0, 0, 600) { Culture = Cultures.EnUs, Text = ".6", Pattern = ".f" }, new Data(0, 0, 0, 600) { Culture = Cultures.EnUs, Text = ".6", Pattern = ".F" }, new Data(0, 0, 0, 600) { Culture = Cultures.EnUs, Text = ".6", Pattern = ".FFF" }, // Elided fraction new Data(0, 0, 0, 678) { Culture = Cultures.EnUs, Text = ".678", Pattern = ".fff" }, new Data(0, 0, 0, 678) { Culture = Cultures.EnUs, Text = ".678", Pattern = ".FFF" }, new Data(0, 0, 12, 0) { Culture = Cultures.EnUs, Text = "12", Pattern = "%s" }, new Data(0, 0, 12, 0) { Culture = Cultures.EnUs, Text = "12", Pattern = "ss" }, new Data(0, 0, 2, 0) { Culture = Cultures.EnUs, Text = "2", Pattern = "%s" }, new Data(0, 12, 0, 0) { Culture = Cultures.EnUs, Text = "12", Pattern = "%m" }, new Data(0, 12, 0, 0) { Culture = Cultures.EnUs, Text = "12", Pattern = "mm" }, new Data(0, 2, 0, 0) { Culture = Cultures.EnUs, Text = "2", Pattern = "%m" }, new Data(1, 0, 0, 0) { Culture = Cultures.EnUs, Text = "1", Pattern = "H.FFF" }, // Missing fraction new Data(12, 0, 0, 0) { Culture = Cultures.EnUs, Text = "12", Pattern = "%H" }, new Data(12, 0, 0, 0) { Culture = Cultures.EnUs, Text = "12", Pattern = "HH" }, new Data(2, 0, 0, 0) { Culture = Cultures.EnUs, Text = "2", Pattern = "%H" }, new Data(0, 0, 12, 340) { Culture = Cultures.EnUs, Text = "12.34", Pattern = "ss.FFF" }, // Standard patterns new Data(14, 15, 16) { Culture = Cultures.EnUs, Text = "14:15:16", Pattern = "r" }, new Data(14, 15, 16, 700) { Culture = Cultures.EnUs, Text = "14:15:16.7", Pattern = "r" }, new Data(14, 15, 16, 780) { Culture = Cultures.EnUs, Text = "14:15:16.78", Pattern = "r" }, new Data(14, 15, 16, 789) { Culture = Cultures.EnUs, Text = "14:15:16.789", Pattern = "r" }, new Data(14, 15, 16, 789, 1000) { Culture = Cultures.EnUs, Text = "14:15:16.7891", Pattern = "r" }, new Data(14, 15, 16, 789, 1200) { Culture = Cultures.EnUs, Text = "14:15:16.78912", Pattern = "r" }, new Data(14, 15, 16, 789, 1230) { Culture = Cultures.EnUs, Text = "14:15:16.789123", Pattern = "r" }, new Data(14, 15, 16, 789, 1234) { Culture = Cultures.EnUs, Text = "14:15:16.7891234", Pattern = "r" }, new Data(14, 15, 16, 700) { Culture = Cultures.DotTimeSeparator, Text = "14.15.16.7", Pattern = "r" }, new Data(14, 15, 16, 780) { Culture = Cultures.DotTimeSeparator, Text = "14.15.16.78", Pattern = "r" }, new Data(14, 15, 16, 789) { Culture = Cultures.DotTimeSeparator, Text = "14.15.16.789", Pattern = "r" }, new Data(14, 15, 16, 789, 1000) { Culture = Cultures.DotTimeSeparator, Text = "14.15.16.7891", Pattern = "r" }, new Data(14, 15, 16, 789, 1200) { Culture = Cultures.DotTimeSeparator, Text = "14.15.16.78912", Pattern = "r" }, new Data(14, 15, 16, 789, 1230) { Culture = Cultures.DotTimeSeparator, Text = "14.15.16.789123", Pattern = "r" }, new Data(14, 15, 16, 789, 1234) { Culture = Cultures.DotTimeSeparator, Text = "14.15.16.7891234", Pattern = "r" }, new Data(14, 15, 16, 789123456L) { Culture = Cultures.DotTimeSeparator, Text = "14.15.16.789123456", Pattern = "r" }, new Data(14, 15, 0) { Culture = Cultures.DotTimeSeparator, Text = "14.15", Pattern = "t" }, new Data(14, 15, 0) { Culture = Cultures.Invariant, Text = "14:15", Pattern = "t" }, new Data(14, 15, 16) { Culture = Cultures.DotTimeSeparator, Text = "14.15.16", Pattern = "T" }, new Data(14, 15, 16) { Culture = Cultures.Invariant, Text = "14:15:16", Pattern = "T" }, new Data(14, 15, 16, 789) { StandardPattern = LocalTimePattern.ExtendedIso, Culture = Cultures.DotTimeSeparator, Text = "14:15:16.789", Pattern = "o" }, new Data(14, 15, 16, 789) { StandardPattern = LocalTimePattern.ExtendedIso, Culture = Cultures.EnUs, Text = "14:15:16.789", Pattern = "o" }, new Data(14, 15, 16) { StandardPattern = LocalTimePattern.ExtendedIso, Culture = Cultures.Invariant, Text = "14:15:16", Pattern = "o" }, new Data(14, 15, 16, 789) { StandardPattern = LocalTimePattern.LongExtendedIso, Culture = Cultures.DotTimeSeparator, Text = "14:15:16.789000000", Pattern = "O" }, new Data(14, 15, 16, 789) { StandardPattern = LocalTimePattern.LongExtendedIso, Culture = Cultures.EnUs, Text = "14:15:16.789000000", Pattern = "O" }, new Data(14, 15, 16) { StandardPattern = LocalTimePattern.LongExtendedIso, Culture = Cultures.Invariant, Text = "14:15:16.000000000", Pattern = "O" }, // ------------ Template value tests ---------- // Mixtures of 12 and 24 hour times new Data(18, 0, 0) { Culture = Cultures.EnUs, Text = "18 6 PM", Pattern = "HH h tt" }, new Data(18, 0, 0) { Culture = Cultures.EnUs, Text = "18 6", Pattern = "HH h" }, new Data(18, 0, 0) { Culture = Cultures.EnUs, Text = "18 PM", Pattern = "HH tt" }, new Data(18, 0, 0) { Culture = Cultures.EnUs, Text = "6 PM", Pattern = "h tt" }, new Data(6, 0, 0) { Culture = Cultures.EnUs, Text = "6", Pattern = "%h" }, new Data(0, 0, 0) { Culture = Cultures.EnUs, Text = "AM", Pattern = "tt" }, new Data(12, 0, 0) { Culture = Cultures.EnUs, Text = "PM", Pattern = "tt" }, new Data(0, 0, 0) { Culture = Cultures.EnUs, Text = "A", Pattern = "%t" }, new Data(12, 0, 0) { Culture = Cultures.EnUs, Text = "P", Pattern = "%t" }, // Pattern specifies nothing - template value is passed through new Data(LocalTime.FromHourMinuteSecondMillisecondTick(1, 2, 3, 4, 5)) { Culture = Cultures.EnUs, Text = "*", Pattern = "%*", Template = LocalTime.FromHourMinuteSecondMillisecondTick(1, 2, 3, 4, 5) }, // Tests for each individual field being propagated new Data(LocalTime.FromHourMinuteSecondMillisecondTick(1, 6, 7, 8, 9)) { Culture = Cultures.EnUs, Text = "06:07.0080009", Pattern = "mm:ss.FFFFFFF", Template = LocalTime.FromHourMinuteSecondMillisecondTick(1, 2, 3, 4, 5) }, new Data(LocalTime.FromHourMinuteSecondMillisecondTick(6, 2, 7, 8, 9)) { Culture = Cultures.EnUs, Text = "06:07.0080009", Pattern = "HH:ss.FFFFFFF", Template = LocalTime.FromHourMinuteSecondMillisecondTick(1, 2, 3, 4, 5) }, new Data(LocalTime.FromHourMinuteSecondMillisecondTick(6, 7, 3, 8, 9)) { Culture = Cultures.EnUs, Text = "06:07.0080009", Pattern = "HH:mm.FFFFFFF", Template = LocalTime.FromHourMinuteSecondMillisecondTick(1, 2, 3, 4, 5) }, new Data(LocalTime.FromHourMinuteSecondMillisecondTick(6, 7, 8, 4, 5)) { Culture = Cultures.EnUs, Text = "06:07:08", Pattern = "HH:mm:ss", Template = LocalTime.FromHourMinuteSecondMillisecondTick(1, 2, 3, 4, 5) }, // Hours are tricky because of the ways they can be specified new Data(new LocalTime(6, 2, 3)) { Culture = Cultures.EnUs, Text = "6", Pattern = "%h", Template = new LocalTime(1, 2, 3) }, new Data(new LocalTime(18, 2, 3)) { Culture = Cultures.EnUs, Text = "6", Pattern = "%h", Template = new LocalTime(14, 2, 3) }, new Data(new LocalTime(2, 2, 3)) { Culture = Cultures.EnUs, Text = "AM", Pattern = "tt", Template = new LocalTime(14, 2, 3) }, new Data(new LocalTime(14, 2, 3)) { Culture = Cultures.EnUs, Text = "PM", Pattern = "tt", Template = new LocalTime(14, 2, 3) }, new Data(new LocalTime(2, 2, 3)) { Culture = Cultures.EnUs, Text = "AM", Pattern = "tt", Template = new LocalTime(2, 2, 3) }, new Data(new LocalTime(14, 2, 3)) { Culture = Cultures.EnUs, Text = "PM", Pattern = "tt", Template = new LocalTime(2, 2, 3) }, new Data(new LocalTime(17, 2, 3)) { Culture = Cultures.EnUs, Text = "5 PM", Pattern = "h tt", Template = new LocalTime(1, 2, 3) }, // --------------- end of template value tests ---------------------- // Only one of the AM/PM designator is present. We should still be able to work out what is meant, by the presence // or absense of the non-empty one. new Data(5, 0, 0) { Culture = AmOnlyCulture, Text = "5 am", Pattern = "h tt" }, new Data(15, 0, 0) { Culture = AmOnlyCulture, Text = "3 ", Pattern = "h tt", Description = "Implicit PM" }, new Data(5, 0, 0) { Culture = AmOnlyCulture, Text = "5 a", Pattern = "h t" }, new Data(15, 0, 0) { Culture = AmOnlyCulture, Text = "3 ", Pattern = "h t", Description = "Implicit PM"}, new Data(5, 0, 0) { Culture = PmOnlyCulture, Text = "5 ", Pattern = "h tt" }, new Data(15, 0, 0) { Culture = PmOnlyCulture, Text = "3 pm", Pattern = "h tt" }, new Data(5, 0, 0) { Culture = PmOnlyCulture, Text = "5 ", Pattern = "h t" }, new Data(15, 0, 0) { Culture = PmOnlyCulture, Text = "3 p", Pattern = "h t" }, // AM / PM designators are both empty strings. The parsing side relies on the AM/PM value being correct on the // template value. (The template value is for the wrong actual hour, but in the right side of noon.) new Data(5, 0, 0) { Culture = NoAmOrPmCulture, Text = "5 ", Pattern = "h tt", Template = new LocalTime(2, 0, 0) }, new Data(15, 0, 0) { Culture = NoAmOrPmCulture, Text = "3 ", Pattern = "h tt", Template = new LocalTime(14, 0, 0) }, new Data(5, 0, 0) { Culture = NoAmOrPmCulture, Text = "5 ", Pattern = "h t", Template = new LocalTime(2, 0, 0) }, new Data(15, 0, 0) { Culture = NoAmOrPmCulture, Text = "3 ", Pattern = "h t", Template = new LocalTime(14, 0, 0) }, // Use of the semi-colon "comma dot" specifier new Data(16, 05, 20, 352) { Pattern = "HH:mm:ss;fff", Text = "16:05:20.352" }, new Data(16, 05, 20, 352) { Pattern = "HH:mm:ss;FFF", Text = "16:05:20.352" }, new Data(16, 05, 20, 352) { Pattern = "HH:mm:ss;FFF 'end'", Text = "16:05:20.352 end" }, new Data(16, 05, 20) { Pattern = "HH:mm:ss;FFF 'end'", Text = "16:05:20 end" }, // Check handling of F after non-period. new Data(16, 05, 20, 352) { Pattern = "HH:mm:ss'x'FFF", Text = "16:05:20x352" }, }; internal static IEnumerable<Data> ParseData = ParseOnlyData.Concat(FormatAndParseData); internal static IEnumerable<Data> FormatData = FormatOnlyData.Concat(FormatAndParseData); private static CultureInfo CreateCustomAmPmCulture(string amDesignator, string pmDesignator) { CultureInfo clone = (CultureInfo)CultureInfo.InvariantCulture.Clone(); clone.DateTimeFormat.AMDesignator = amDesignator; clone.DateTimeFormat.PMDesignator = pmDesignator; return CultureInfo.ReadOnly(clone); } [Test] public void ParseNull() => AssertParseNull(LocalTimePattern.ExtendedIso); [Test] [TestCaseSource(typeof(Cultures), nameof(Cultures.AllCultures))] public void BclLongTimePatternIsValidNodaPattern(CultureInfo culture) { if (culture is null) { return; } AssertValidNodaPattern(culture, culture.DateTimeFormat.LongTimePattern); } [Test] [TestCaseSource(typeof(Cultures), nameof(Cultures.AllCultures))] public void BclShortTimePatternIsValidNodaPattern(CultureInfo culture) { AssertValidNodaPattern(culture, culture.DateTimeFormat.ShortTimePattern); } [Test] [TestCaseSource(typeof(Cultures), nameof(Cultures.AllCultures))] public void BclLongTimePatternGivesSameResultsInNoda(CultureInfo culture) { AssertBclNodaEquality(culture, culture.DateTimeFormat.LongTimePattern); } [Test] [TestCaseSource(typeof(Cultures), nameof(Cultures.AllCultures))] public void BclShortTimePatternGivesSameResultsInNoda(CultureInfo culture) { AssertBclNodaEquality(culture, culture.DateTimeFormat.ShortTimePattern); } [Test] public void CreateWithInvariantCulture_NullPatternText() { Assert.Throws<ArgumentNullException>(() => LocalTimePattern.CreateWithInvariantCulture(null!)); } [Test] public void Create_NullFormatInfo() { Assert.Throws<ArgumentNullException>(() => LocalTimePattern.Create("HH", null!)); } [Test] public void TemplateValue_DefaultsToMidnight() { var pattern = LocalTimePattern.CreateWithInvariantCulture("HH"); Assert.AreEqual(LocalTime.Midnight, pattern.TemplateValue); } [Test] public void CreateWithCurrentCulture() { using (CultureSaver.SetCultures(Cultures.DotTimeSeparator)) { var pattern = LocalTimePattern.CreateWithCurrentCulture("HH:mm"); var text = pattern.Format(new LocalTime(13, 45)); Assert.AreEqual("13.45", text); } } [Test] public void WithTemplateValue_PropertyFetch() { LocalTime newValue = new LocalTime(1, 23, 45); var pattern = LocalTimePattern.CreateWithInvariantCulture("HH").WithTemplateValue(newValue); Assert.AreEqual(newValue, pattern.TemplateValue); } private void AssertBclNodaEquality(CultureInfo culture, string patternText) { // On Mono, some general patterns include an offset at the end. // https://github.com/nodatime/nodatime/issues/98 // For the moment, ignore them. // TODO(V1.2): Work out what to do in such cases... if (patternText.EndsWith("z")) { return; } var pattern = LocalTimePattern.Create(patternText, culture); Assert.AreEqual(SampleDateTime.ToString(patternText, culture), pattern.Format(SampleLocalTime)); } private static void AssertValidNodaPattern(CultureInfo culture, string pattern) { PatternCursor cursor = new PatternCursor(pattern); while (cursor.MoveNext()) { if (cursor.Current == '\'') { cursor.GetQuotedString('\''); } else { // We'll never do anything "special" with non-ascii characters anyway, // so we don't mind if they're not quoted. if (cursor.Current < '\u0080') { Assert.IsTrue(ExpectedCharacters.Contains(cursor.Current), "Pattern '" + pattern + "' contains unquoted, unexpected characters"); } } } // Check that the pattern parses LocalTimePattern.Create(pattern, culture); } /// <summary> /// A container for test data for formatting and parsing <see cref="LocalTime" /> objects. /// </summary> public sealed class Data : PatternTestData<LocalTime> { // Default to midnight protected override LocalTime DefaultTemplate => LocalTime.Midnight; protected override string? ValuePatternText => "HH:mm:ss.FFFFFFFFF"; public Data(LocalTime value) : base(value) { } public Data(int hours, int minutes, int seconds) : this(new LocalTime(hours, minutes, seconds)) { } public Data(int hours, int minutes, int seconds, int milliseconds) : this(new LocalTime(hours, minutes, seconds, milliseconds)) { } public Data(int hours, int minutes, int seconds, int milliseconds, int ticksWithinMillisecond) : this(LocalTime.FromHourMinuteSecondMillisecondTick(hours, minutes, seconds, milliseconds, ticksWithinMillisecond)) { } public Data(int hours, int minutes, int seconds, long nanoOfSecond) : this(new LocalTime(hours, minutes, seconds).PlusNanoseconds(nanoOfSecond)) { } public Data() : this(LocalTime.Midnight) { } internal override IPattern<LocalTime> CreatePattern() => LocalTimePattern.CreateWithInvariantCulture(Pattern!) .WithTemplateValue(Template) .WithCulture(Culture); } } }
namespace KabMan.Forms { partial class DasdManagerForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.CBarManager = new DevExpress.XtraBars.BarManager(this.components); this.CStatusBar = new DevExpress.XtraBars.Bar(); this.itemCount = new DevExpress.XtraBars.BarStaticItem(); this.bar1 = new DevExpress.XtraBars.Bar(); this.itemNew = new DevExpress.XtraBars.BarButtonItem(); this.itemDelete = new DevExpress.XtraBars.BarButtonItem(); this.itemDetails = new DevExpress.XtraBars.BarButtonItem(); this.itemExit = new DevExpress.XtraBars.BarButtonItem(); this.barDockControlTop = new DevExpress.XtraBars.BarDockControl(); this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl(); this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl(); this.barDockControlRight = new DevExpress.XtraBars.BarDockControl(); this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl(); this.CDasdGrid = new DevExpress.XtraGrid.GridControl(); this.CDasdView = new DevExpress.XtraGrid.Views.Grid.GridView(); this.gridColumn1 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn2 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn3 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn4 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn6 = new DevExpress.XtraGrid.Columns.GridColumn(); this.layoutControlGroup1 = new DevExpress.XtraLayout.LayoutControlGroup(); this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem(); ((System.ComponentModel.ISupportInitialize)(this.CBarManager)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit(); this.layoutControl1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.CDasdGrid)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CDasdView)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit(); this.SuspendLayout(); // // CBarManager // this.CBarManager.AllowCustomization = false; this.CBarManager.AllowQuickCustomization = false; this.CBarManager.AllowShowToolbarsPopup = false; this.CBarManager.Bars.AddRange(new DevExpress.XtraBars.Bar[] { this.CStatusBar, this.bar1}); this.CBarManager.DockControls.Add(this.barDockControlTop); this.CBarManager.DockControls.Add(this.barDockControlBottom); this.CBarManager.DockControls.Add(this.barDockControlLeft); this.CBarManager.DockControls.Add(this.barDockControlRight); this.CBarManager.Form = this; this.CBarManager.Items.AddRange(new DevExpress.XtraBars.BarItem[] { this.itemCount, this.itemNew, this.itemDelete, this.itemDetails, this.itemExit}); this.CBarManager.MaxItemId = 9; this.CBarManager.StatusBar = this.CStatusBar; // // CStatusBar // this.CStatusBar.BarName = "Status Bar"; this.CStatusBar.CanDockStyle = DevExpress.XtraBars.BarCanDockStyle.Bottom; this.CStatusBar.DockCol = 0; this.CStatusBar.DockRow = 0; this.CStatusBar.DockStyle = DevExpress.XtraBars.BarDockStyle.Bottom; this.CStatusBar.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.itemCount)}); this.CStatusBar.OptionsBar.AllowQuickCustomization = false; this.CStatusBar.OptionsBar.DrawDragBorder = false; this.CStatusBar.OptionsBar.UseWholeRow = true; this.CStatusBar.Text = "Status Bar"; // // itemCount // this.itemCount.Alignment = DevExpress.XtraBars.BarItemLinkAlignment.Right; this.itemCount.Caption = "0"; this.itemCount.Id = 4; this.itemCount.Name = "itemCount"; this.itemCount.TextAlignment = System.Drawing.StringAlignment.Near; // // bar1 // this.bar1.BarName = "Custom 4"; this.bar1.DockCol = 0; this.bar1.DockRow = 0; this.bar1.DockStyle = DevExpress.XtraBars.BarDockStyle.Top; this.bar1.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.itemNew), new DevExpress.XtraBars.LinkPersistInfo(this.itemDelete), new DevExpress.XtraBars.LinkPersistInfo(this.itemDetails, true), new DevExpress.XtraBars.LinkPersistInfo(this.itemExit, true)}); this.bar1.OptionsBar.AllowQuickCustomization = false; this.bar1.OptionsBar.DrawDragBorder = false; this.bar1.OptionsBar.UseWholeRow = true; this.bar1.Text = "Custom 4"; // // itemNew // this.itemNew.Caption = "New"; this.itemNew.Id = 5; this.itemNew.Name = "itemNew"; this.itemNew.PaintStyle = DevExpress.XtraBars.BarItemPaintStyle.CaptionGlyph; this.itemNew.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.itemNew_ItemClick); // // itemDelete // this.itemDelete.Caption = "Delete"; this.itemDelete.Id = 6; this.itemDelete.Name = "itemDelete"; this.itemDelete.PaintStyle = DevExpress.XtraBars.BarItemPaintStyle.CaptionGlyph; // // itemDetails // this.itemDetails.Caption = "View Details"; this.itemDetails.Id = 7; this.itemDetails.Name = "itemDetails"; this.itemDetails.PaintStyle = DevExpress.XtraBars.BarItemPaintStyle.CaptionGlyph; this.itemDetails.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.itemDetails_ItemClick); // // itemExit // this.itemExit.Caption = "Exit"; this.itemExit.Id = 8; this.itemExit.Name = "itemExit"; this.itemExit.PaintStyle = DevExpress.XtraBars.BarItemPaintStyle.CaptionGlyph; this.itemExit.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.itemExit_ItemClick); // // layoutControl1 // this.layoutControl1.AllowCustomizationMenu = false; this.layoutControl1.Appearance.DisabledLayoutGroupCaption.ForeColor = System.Drawing.SystemColors.GrayText; this.layoutControl1.Appearance.DisabledLayoutGroupCaption.Options.UseForeColor = true; this.layoutControl1.Appearance.DisabledLayoutItem.ForeColor = System.Drawing.SystemColors.GrayText; this.layoutControl1.Appearance.DisabledLayoutItem.Options.UseForeColor = true; this.layoutControl1.Controls.Add(this.CDasdGrid); this.layoutControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.layoutControl1.Location = new System.Drawing.Point(0, 24); this.layoutControl1.Name = "layoutControl1"; this.layoutControl1.Root = this.layoutControlGroup1; this.layoutControl1.Size = new System.Drawing.Size(556, 535); this.layoutControl1.TabIndex = 4; this.layoutControl1.Text = "layoutControl1"; // // CDasdGrid // this.CDasdGrid.Location = new System.Drawing.Point(7, 7); this.CDasdGrid.MainView = this.CDasdView; this.CDasdGrid.Name = "CDasdGrid"; this.CDasdGrid.Size = new System.Drawing.Size(543, 522); this.CDasdGrid.TabIndex = 4; this.CDasdGrid.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] { this.CDasdView}); this.CDasdGrid.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.CDasdGrid_MouseDoubleClick); // // CDasdView // this.CDasdView.Appearance.ColumnFilterButton.BackColor = System.Drawing.Color.Silver; this.CDasdView.Appearance.ColumnFilterButton.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212))))); this.CDasdView.Appearance.ColumnFilterButton.BorderColor = System.Drawing.Color.Silver; this.CDasdView.Appearance.ColumnFilterButton.ForeColor = System.Drawing.Color.Gray; this.CDasdView.Appearance.ColumnFilterButton.Options.UseBackColor = true; this.CDasdView.Appearance.ColumnFilterButton.Options.UseBorderColor = true; this.CDasdView.Appearance.ColumnFilterButton.Options.UseForeColor = true; this.CDasdView.Appearance.ColumnFilterButtonActive.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212))))); this.CDasdView.Appearance.ColumnFilterButtonActive.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(223)))), ((int)(((byte)(223))))); this.CDasdView.Appearance.ColumnFilterButtonActive.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212))))); this.CDasdView.Appearance.ColumnFilterButtonActive.ForeColor = System.Drawing.Color.Blue; this.CDasdView.Appearance.ColumnFilterButtonActive.Options.UseBackColor = true; this.CDasdView.Appearance.ColumnFilterButtonActive.Options.UseBorderColor = true; this.CDasdView.Appearance.ColumnFilterButtonActive.Options.UseForeColor = true; this.CDasdView.Appearance.Empty.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243))))); this.CDasdView.Appearance.Empty.Options.UseBackColor = true; this.CDasdView.Appearance.EvenRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(223)))), ((int)(((byte)(223))))); this.CDasdView.Appearance.EvenRow.BackColor2 = System.Drawing.Color.GhostWhite; this.CDasdView.Appearance.EvenRow.ForeColor = System.Drawing.Color.Black; this.CDasdView.Appearance.EvenRow.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.CDasdView.Appearance.EvenRow.Options.UseBackColor = true; this.CDasdView.Appearance.EvenRow.Options.UseForeColor = true; this.CDasdView.Appearance.FilterCloseButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.CDasdView.Appearance.FilterCloseButton.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(118)))), ((int)(((byte)(170)))), ((int)(((byte)(225))))); this.CDasdView.Appearance.FilterCloseButton.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.CDasdView.Appearance.FilterCloseButton.ForeColor = System.Drawing.Color.Black; this.CDasdView.Appearance.FilterCloseButton.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.CDasdView.Appearance.FilterCloseButton.Options.UseBackColor = true; this.CDasdView.Appearance.FilterCloseButton.Options.UseBorderColor = true; this.CDasdView.Appearance.FilterCloseButton.Options.UseForeColor = true; this.CDasdView.Appearance.FilterPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(28)))), ((int)(((byte)(80)))), ((int)(((byte)(135))))); this.CDasdView.Appearance.FilterPanel.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.CDasdView.Appearance.FilterPanel.ForeColor = System.Drawing.Color.White; this.CDasdView.Appearance.FilterPanel.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.CDasdView.Appearance.FilterPanel.Options.UseBackColor = true; this.CDasdView.Appearance.FilterPanel.Options.UseForeColor = true; this.CDasdView.Appearance.FixedLine.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(58)))), ((int)(((byte)(58))))); this.CDasdView.Appearance.FixedLine.Options.UseBackColor = true; this.CDasdView.Appearance.FocusedCell.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(225))))); this.CDasdView.Appearance.FocusedCell.ForeColor = System.Drawing.Color.Black; this.CDasdView.Appearance.FocusedCell.Options.UseBackColor = true; this.CDasdView.Appearance.FocusedCell.Options.UseForeColor = true; this.CDasdView.Appearance.FocusedRow.BackColor = System.Drawing.Color.Navy; this.CDasdView.Appearance.FocusedRow.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(50)))), ((int)(((byte)(50)))), ((int)(((byte)(178))))); this.CDasdView.Appearance.FocusedRow.ForeColor = System.Drawing.Color.White; this.CDasdView.Appearance.FocusedRow.Options.UseBackColor = true; this.CDasdView.Appearance.FocusedRow.Options.UseForeColor = true; this.CDasdView.Appearance.FooterPanel.BackColor = System.Drawing.Color.Silver; this.CDasdView.Appearance.FooterPanel.BorderColor = System.Drawing.Color.Silver; this.CDasdView.Appearance.FooterPanel.ForeColor = System.Drawing.Color.Black; this.CDasdView.Appearance.FooterPanel.Options.UseBackColor = true; this.CDasdView.Appearance.FooterPanel.Options.UseBorderColor = true; this.CDasdView.Appearance.FooterPanel.Options.UseForeColor = true; this.CDasdView.Appearance.GroupButton.BackColor = System.Drawing.Color.Silver; this.CDasdView.Appearance.GroupButton.BorderColor = System.Drawing.Color.Silver; this.CDasdView.Appearance.GroupButton.ForeColor = System.Drawing.Color.Black; this.CDasdView.Appearance.GroupButton.Options.UseBackColor = true; this.CDasdView.Appearance.GroupButton.Options.UseBorderColor = true; this.CDasdView.Appearance.GroupButton.Options.UseForeColor = true; this.CDasdView.Appearance.GroupFooter.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(202)))), ((int)(((byte)(202))))); this.CDasdView.Appearance.GroupFooter.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(202)))), ((int)(((byte)(202))))); this.CDasdView.Appearance.GroupFooter.ForeColor = System.Drawing.Color.Black; this.CDasdView.Appearance.GroupFooter.Options.UseBackColor = true; this.CDasdView.Appearance.GroupFooter.Options.UseBorderColor = true; this.CDasdView.Appearance.GroupFooter.Options.UseForeColor = true; this.CDasdView.Appearance.GroupPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(110)))), ((int)(((byte)(165))))); this.CDasdView.Appearance.GroupPanel.BackColor2 = System.Drawing.Color.White; this.CDasdView.Appearance.GroupPanel.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold); this.CDasdView.Appearance.GroupPanel.ForeColor = System.Drawing.Color.White; this.CDasdView.Appearance.GroupPanel.Options.UseBackColor = true; this.CDasdView.Appearance.GroupPanel.Options.UseFont = true; this.CDasdView.Appearance.GroupPanel.Options.UseForeColor = true; this.CDasdView.Appearance.GroupRow.BackColor = System.Drawing.Color.Gray; this.CDasdView.Appearance.GroupRow.ForeColor = System.Drawing.Color.Silver; this.CDasdView.Appearance.GroupRow.Options.UseBackColor = true; this.CDasdView.Appearance.GroupRow.Options.UseForeColor = true; this.CDasdView.Appearance.HeaderPanel.BackColor = System.Drawing.Color.Silver; this.CDasdView.Appearance.HeaderPanel.BorderColor = System.Drawing.Color.Silver; this.CDasdView.Appearance.HeaderPanel.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold); this.CDasdView.Appearance.HeaderPanel.ForeColor = System.Drawing.Color.Black; this.CDasdView.Appearance.HeaderPanel.Options.UseBackColor = true; this.CDasdView.Appearance.HeaderPanel.Options.UseBorderColor = true; this.CDasdView.Appearance.HeaderPanel.Options.UseFont = true; this.CDasdView.Appearance.HeaderPanel.Options.UseForeColor = true; this.CDasdView.Appearance.HideSelectionRow.BackColor = System.Drawing.Color.Gray; this.CDasdView.Appearance.HideSelectionRow.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.CDasdView.Appearance.HideSelectionRow.Options.UseBackColor = true; this.CDasdView.Appearance.HideSelectionRow.Options.UseForeColor = true; this.CDasdView.Appearance.HorzLine.BackColor = System.Drawing.Color.Silver; this.CDasdView.Appearance.HorzLine.Options.UseBackColor = true; this.CDasdView.Appearance.OddRow.BackColor = System.Drawing.Color.White; this.CDasdView.Appearance.OddRow.BackColor2 = System.Drawing.Color.White; this.CDasdView.Appearance.OddRow.ForeColor = System.Drawing.Color.Black; this.CDasdView.Appearance.OddRow.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.BackwardDiagonal; this.CDasdView.Appearance.OddRow.Options.UseBackColor = true; this.CDasdView.Appearance.OddRow.Options.UseForeColor = true; this.CDasdView.Appearance.Preview.BackColor = System.Drawing.Color.White; this.CDasdView.Appearance.Preview.ForeColor = System.Drawing.Color.Navy; this.CDasdView.Appearance.Preview.Options.UseBackColor = true; this.CDasdView.Appearance.Preview.Options.UseForeColor = true; this.CDasdView.Appearance.Row.BackColor = System.Drawing.Color.White; this.CDasdView.Appearance.Row.ForeColor = System.Drawing.Color.Black; this.CDasdView.Appearance.Row.Options.UseBackColor = true; this.CDasdView.Appearance.Row.Options.UseForeColor = true; this.CDasdView.Appearance.RowSeparator.BackColor = System.Drawing.Color.White; this.CDasdView.Appearance.RowSeparator.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243))))); this.CDasdView.Appearance.RowSeparator.Options.UseBackColor = true; this.CDasdView.Appearance.SelectedRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(10)))), ((int)(((byte)(10)))), ((int)(((byte)(138))))); this.CDasdView.Appearance.SelectedRow.ForeColor = System.Drawing.Color.White; this.CDasdView.Appearance.SelectedRow.Options.UseBackColor = true; this.CDasdView.Appearance.SelectedRow.Options.UseForeColor = true; this.CDasdView.Appearance.VertLine.BackColor = System.Drawing.Color.Silver; this.CDasdView.Appearance.VertLine.Options.UseBackColor = true; this.CDasdView.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] { this.gridColumn1, this.gridColumn2, this.gridColumn3, this.gridColumn4, this.gridColumn6}); this.CDasdView.GridControl = this.CDasdGrid; this.CDasdView.Name = "CDasdView"; this.CDasdView.OptionsBehavior.AllowIncrementalSearch = true; this.CDasdView.OptionsBehavior.Editable = false; this.CDasdView.OptionsCustomization.AllowFilter = false; this.CDasdView.OptionsView.EnableAppearanceEvenRow = true; this.CDasdView.OptionsView.EnableAppearanceOddRow = true; this.CDasdView.OptionsView.ShowGroupPanel = false; this.CDasdView.OptionsView.ShowIndicator = false; // // gridColumn1 // this.gridColumn1.Caption = "Name"; this.gridColumn1.FieldName = "Name"; this.gridColumn1.Name = "gridColumn1"; this.gridColumn1.Visible = true; this.gridColumn1.VisibleIndex = 0; // // gridColumn2 // this.gridColumn2.Caption = "Cu Type"; this.gridColumn2.FieldName = "CuType"; this.gridColumn2.Name = "gridColumn2"; this.gridColumn2.Visible = true; this.gridColumn2.VisibleIndex = 1; // // gridColumn3 // this.gridColumn3.Caption = "Data Center"; this.gridColumn3.FieldName = "DataCenter"; this.gridColumn3.Name = "gridColumn3"; this.gridColumn3.Visible = true; this.gridColumn3.VisibleIndex = 2; // // gridColumn4 // this.gridColumn4.Caption = "Coordinate"; this.gridColumn4.FieldName = "Coordinate"; this.gridColumn4.Name = "gridColumn4"; this.gridColumn4.Visible = true; this.gridColumn4.VisibleIndex = 3; // // gridColumn6 // this.gridColumn6.Caption = "Port Count"; this.gridColumn6.FieldName = "PortCount"; this.gridColumn6.Name = "gridColumn6"; this.gridColumn6.Visible = true; this.gridColumn6.VisibleIndex = 4; // // layoutControlGroup1 // this.layoutControlGroup1.CustomizationFormText = "layoutControlGroup1"; this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] { this.layoutControlItem1}); this.layoutControlGroup1.Location = new System.Drawing.Point(0, 0); this.layoutControlGroup1.Name = "layoutControlGroup1"; this.layoutControlGroup1.Size = new System.Drawing.Size(556, 535); this.layoutControlGroup1.Spacing = new DevExpress.XtraLayout.Utils.Padding(0, 0, 0, 0); this.layoutControlGroup1.Text = "layoutControlGroup1"; this.layoutControlGroup1.TextVisible = false; // // layoutControlItem1 // this.layoutControlItem1.Control = this.CDasdGrid; this.layoutControlItem1.CustomizationFormText = "layoutControlItem1"; this.layoutControlItem1.Location = new System.Drawing.Point(0, 0); this.layoutControlItem1.Name = "layoutControlItem1"; this.layoutControlItem1.Size = new System.Drawing.Size(554, 533); this.layoutControlItem1.Text = "layoutControlItem1"; this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem1.TextSize = new System.Drawing.Size(0, 0); this.layoutControlItem1.TextToControlDistance = 0; this.layoutControlItem1.TextVisible = false; // // DasdManagerForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(556, 582); this.Controls.Add(this.layoutControl1); this.Controls.Add(this.barDockControlLeft); this.Controls.Add(this.barDockControlRight); this.Controls.Add(this.barDockControlBottom); this.Controls.Add(this.barDockControlTop); this.Name = "DasdManagerForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Dasd Manager"; this.Load += new System.EventHandler(this.RackManagerForm_Load); ((System.ComponentModel.ISupportInitialize)(this.CBarManager)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit(); this.layoutControl1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.CDasdGrid)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CDasdView)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit(); this.ResumeLayout(false); } #endregion private DevExpress.XtraBars.BarManager CBarManager; private DevExpress.XtraBars.Bar CStatusBar; private DevExpress.XtraBars.BarDockControl barDockControlTop; private DevExpress.XtraBars.BarDockControl barDockControlBottom; private DevExpress.XtraBars.BarDockControl barDockControlLeft; private DevExpress.XtraBars.BarDockControl barDockControlRight; private DevExpress.XtraLayout.LayoutControl layoutControl1; private DevExpress.XtraGrid.GridControl CDasdGrid; private DevExpress.XtraGrid.Views.Grid.GridView CDasdView; private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup1; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1; private DevExpress.XtraBars.BarStaticItem itemCount; private DevExpress.XtraGrid.Columns.GridColumn gridColumn1; private DevExpress.XtraGrid.Columns.GridColumn gridColumn3; private DevExpress.XtraGrid.Columns.GridColumn gridColumn4; private DevExpress.XtraGrid.Columns.GridColumn gridColumn6; private DevExpress.XtraGrid.Columns.GridColumn gridColumn2; private DevExpress.XtraBars.Bar bar1; private DevExpress.XtraBars.BarButtonItem itemNew; private DevExpress.XtraBars.BarButtonItem itemDelete; private DevExpress.XtraBars.BarButtonItem itemDetails; private DevExpress.XtraBars.BarButtonItem itemExit; } }
#region License // Copyright (c) 2006-2007, ClearCanvas Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of ClearCanvas Inc. nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, // OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY // OF SUCH DAMAGE. #endregion namespace SearchComponent.View.WinForms { partial class AIMSearchCriteriaComponentControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AIMSearchCriteriaComponentControl)); this._titleBar = new Crownwood.DotNetMagic.Controls.TitleBar(); this._imageAnnotation = new System.Windows.Forms.RadioButton(); this._annotationOfAnnotation = new System.Windows.Forms.RadioButton(); this._cancelButton = new System.Windows.Forms.Button(); this._searchButton = new System.Windows.Forms.Button(); this._resetButton = new System.Windows.Forms.Button(); this._studyInstanceUid = new ClearCanvas.Desktop.View.WinForms.TextField(); this._imagingObservationCharacteristics = new ClearCanvas.Desktop.View.WinForms.TextField(); this._imagingObservations = new ClearCanvas.Desktop.View.WinForms.TextField(); this._user = new ClearCanvas.Desktop.View.WinForms.TextField(); this._anatomicEntityCharacteristics = new ClearCanvas.Desktop.View.WinForms.TextField(); this._anatomicEntities = new ClearCanvas.Desktop.View.WinForms.TextField(); this.SuspendLayout(); // // _titleBar // this._titleBar.Dock = System.Windows.Forms.DockStyle.Top; this._titleBar.Font = new System.Drawing.Font("Arial", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this._titleBar.GradientColoring = Crownwood.DotNetMagic.Controls.GradientColoring.LightBackToDarkBack; this._titleBar.Location = new System.Drawing.Point(0, 0); this._titleBar.MouseOverColor = System.Drawing.Color.Empty; this._titleBar.Name = "_titleBar"; this._titleBar.Size = new System.Drawing.Size(766, 30); this._titleBar.Style = Crownwood.DotNetMagic.Common.VisualStyle.IDE2005; this._titleBar.TabIndex = 0; this._titleBar.Text = "Search"; // // _imageAnnotation // this._imageAnnotation.AutoCheck = false; this._imageAnnotation.AutoSize = true; this._imageAnnotation.Location = new System.Drawing.Point(12, 136); this._imageAnnotation.Name = "_imageAnnotation"; this._imageAnnotation.Size = new System.Drawing.Size(108, 17); this._imageAnnotation.TabIndex = 6; this._imageAnnotation.Text = "Image Annotation"; this._imageAnnotation.UseVisualStyleBackColor = true; // // _annotationOfAnnotation // this._annotationOfAnnotation.AutoCheck = false; this._annotationOfAnnotation.AutoSize = true; this._annotationOfAnnotation.Location = new System.Drawing.Point(122, 136); this._annotationOfAnnotation.Name = "_annotationOfAnnotation"; this._annotationOfAnnotation.Size = new System.Drawing.Size(144, 17); this._annotationOfAnnotation.TabIndex = 7; this._annotationOfAnnotation.Text = "Annotation Of Annotation"; this._annotationOfAnnotation.UseVisualStyleBackColor = true; // // _cancelButton // this._cancelButton.Location = new System.Drawing.Point(659, 82); this._cancelButton.Name = "_cancelButton"; this._cancelButton.Size = new System.Drawing.Size(90, 22); this._cancelButton.TabIndex = 9; this._cancelButton.Text = "Cancel"; this._cancelButton.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText; this._cancelButton.UseVisualStyleBackColor = true; this._cancelButton.Click += new System.EventHandler(this.OnCancel); // // _searchButton // this._searchButton.Image = ((System.Drawing.Image)(resources.GetObject("_searchButton.Image"))); this._searchButton.Location = new System.Drawing.Point(659, 54); this._searchButton.Name = "_searchButton"; this._searchButton.Size = new System.Drawing.Size(90, 22); this._searchButton.TabIndex = 8; this._searchButton.Text = "Search"; this._searchButton.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText; this._searchButton.UseVisualStyleBackColor = true; this._searchButton.Click += new System.EventHandler(this.OnSearch); // // _resetButton // this._resetButton.Location = new System.Drawing.Point(659, 110); this._resetButton.Margin = new System.Windows.Forms.Padding(2); this._resetButton.Name = "_resetButton"; this._resetButton.Size = new System.Drawing.Size(90, 22); this._resetButton.TabIndex = 10; this._resetButton.Text = "Reset"; this._resetButton.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText; this._resetButton.UseVisualStyleBackColor = true; this._resetButton.Click += new System.EventHandler(this.OnReset); // // _studyInstanceUid // this._studyInstanceUid.LabelText = "Study Instance Uid"; this._studyInstanceUid.Location = new System.Drawing.Point(491, 90); this._studyInstanceUid.Margin = new System.Windows.Forms.Padding(2); this._studyInstanceUid.Mask = ""; this._studyInstanceUid.Name = "_studyInstanceUid"; this._studyInstanceUid.PasswordChar = '\0'; this._studyInstanceUid.Size = new System.Drawing.Size(146, 41); this._studyInstanceUid.TabIndex = 18; this._studyInstanceUid.ToolTip = null; this._studyInstanceUid.Value = null; // // _imagingObservationCharacteristics // this._imagingObservationCharacteristics.LabelText = "Imaging Observation Characteristics"; this._imagingObservationCharacteristics.Location = new System.Drawing.Point(250, 90); this._imagingObservationCharacteristics.Margin = new System.Windows.Forms.Padding(2); this._imagingObservationCharacteristics.Mask = ""; this._imagingObservationCharacteristics.Name = "_imagingObservationCharacteristics"; this._imagingObservationCharacteristics.PasswordChar = '\0'; this._imagingObservationCharacteristics.Size = new System.Drawing.Size(211, 41); this._imagingObservationCharacteristics.TabIndex = 17; this._imagingObservationCharacteristics.ToolTip = null; this._imagingObservationCharacteristics.Value = null; // // _imagingObservations // this._imagingObservations.LabelText = "Imaging Observations"; this._imagingObservations.Location = new System.Drawing.Point(12, 90); this._imagingObservations.Margin = new System.Windows.Forms.Padding(2); this._imagingObservations.Mask = ""; this._imagingObservations.Name = "_imagingObservations"; this._imagingObservations.PasswordChar = '\0'; this._imagingObservations.Size = new System.Drawing.Size(211, 41); this._imagingObservations.TabIndex = 16; this._imagingObservations.ToolTip = null; this._imagingObservations.Value = null; // // _user // this._user.LabelText = "User"; this._user.Location = new System.Drawing.Point(491, 45); this._user.Margin = new System.Windows.Forms.Padding(2); this._user.Mask = ""; this._user.Name = "_user"; this._user.PasswordChar = '\0'; this._user.Size = new System.Drawing.Size(146, 41); this._user.TabIndex = 15; this._user.ToolTip = null; this._user.Value = null; // // _anatomicEntityCharacteristics // this._anatomicEntityCharacteristics.LabelText = "Anatomic Entity Characteristics"; this._anatomicEntityCharacteristics.Location = new System.Drawing.Point(250, 45); this._anatomicEntityCharacteristics.Margin = new System.Windows.Forms.Padding(2); this._anatomicEntityCharacteristics.Mask = ""; this._anatomicEntityCharacteristics.Name = "_anatomicEntityCharacteristics"; this._anatomicEntityCharacteristics.PasswordChar = '\0'; this._anatomicEntityCharacteristics.Size = new System.Drawing.Size(211, 41); this._anatomicEntityCharacteristics.TabIndex = 14; this._anatomicEntityCharacteristics.ToolTip = null; this._anatomicEntityCharacteristics.Value = null; // // _anatomicEntities // this._anatomicEntities.LabelText = "Anatomic Entities"; this._anatomicEntities.Location = new System.Drawing.Point(12, 45); this._anatomicEntities.Margin = new System.Windows.Forms.Padding(2); this._anatomicEntities.Mask = ""; this._anatomicEntities.Name = "_anatomicEntities"; this._anatomicEntities.PasswordChar = '\0'; this._anatomicEntities.Size = new System.Drawing.Size(211, 41); this._anatomicEntities.TabIndex = 13; this._anatomicEntities.ToolTip = null; this._anatomicEntities.Value = null; // // AIMSearchCriteriaComponentControl // this.AcceptButton = this._searchButton; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit; this.Controls.Add(this._studyInstanceUid); this.Controls.Add(this._imagingObservationCharacteristics); this.Controls.Add(this._imagingObservations); this.Controls.Add(this._user); this.Controls.Add(this._anatomicEntityCharacteristics); this.Controls.Add(this._anatomicEntities); this.Controls.Add(this._resetButton); this.Controls.Add(this._cancelButton); this.Controls.Add(this._annotationOfAnnotation); this.Controls.Add(this._searchButton); this.Controls.Add(this._titleBar); this.Controls.Add(this._imageAnnotation); this.Name = "AIMSearchCriteriaComponentControl"; this.Size = new System.Drawing.Size(766, 177); this.ResumeLayout(false); this.PerformLayout(); } #endregion private Crownwood.DotNetMagic.Controls.TitleBar _titleBar; private System.Windows.Forms.RadioButton _imageAnnotation; private System.Windows.Forms.RadioButton _annotationOfAnnotation; private System.Windows.Forms.Button _cancelButton; private System.Windows.Forms.Button _searchButton; private System.Windows.Forms.Button _resetButton; private ClearCanvas.Desktop.View.WinForms.TextField _studyInstanceUid; private ClearCanvas.Desktop.View.WinForms.TextField _imagingObservationCharacteristics; private ClearCanvas.Desktop.View.WinForms.TextField _imagingObservations; private ClearCanvas.Desktop.View.WinForms.TextField _user; private ClearCanvas.Desktop.View.WinForms.TextField _anatomicEntityCharacteristics; private ClearCanvas.Desktop.View.WinForms.TextField _anatomicEntities; } }
// <copyright file=Plane.cs // <copyright> // Copyright (c) 2016, University of Stuttgart // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Software), // to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // </copyright> // <license>MIT License</license> // <main contributors> // Markus Funk, Thomas Kosch, Sven Mayer // </main contributors> // <co-contributors> // Paul Brombosch, Mai El-Komy, Juana Heusler, // Matthias Hoppe, Robert Konrad, Alexander Martin // </co-contributors> // <patent information> // We are aware that this software implements patterns and ideas, // which might be protected by patents in your country. // Example patents in Germany are: // Patent reference number: DE 103 20 557.8 // Patent reference number: DE 10 2013 220 107.9 // Please make sure when using this software not to violate any existing patents in your country. // </patent information> // <date> 11/2/2016 12:25:58 PM</date> using HciLab.Utilities.Mathematics.Core; using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.Serialization; using System.Text.RegularExpressions; namespace HciLab.Utilities.Mathematics.Geometry3D { /// <summary> /// Represents a plane in 3D space. /// </summary> /// <remarks> /// The plane is described by a normal and a constant (N,D) which /// denotes that the plane is consisting of points Q that /// satisfies (N dot Q)+D = 0. /// </remarks> [Serializable] [TypeConverter(typeof(PlaneConverter))] public class Plane : ISerializable, ICloneable { #region Private Fields //N0 private Vector3 _normal; //D private double _const; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Plane"/> class using given normal and constant values. /// </summary> /// <param name="normal">The plane's normal vector.</param> /// <param name="constant">The plane's constant value.</param> public Plane(Vector3 normal, double constant) { _normal = normal; _const = constant; } /// <summary> /// Initializes a new instance of the <see cref="Plane"/> class using given normal and a point. /// </summary> /// <param name="normal">The plane's normal vector.</param> /// <param name="point">A point on the plane in 3D space.</param> public Plane(Vector3 normal, Vector3 point) { _normal = normal; _const = -Vector3.DotProduct(normal, point); } /// <summary> /// Initializes a new instance of the <see cref="Plane"/> class using 3 given points. /// </summary> /// <param name="p0">A point on the plane in 3D space.</param> /// <param name="p1">A point on the plane in 3D space.</param> /// <param name="p2">A point on the plane in 3D space.</param> public Plane(Vector3 p0, Vector3 p1, Vector3 p2) { _normal = Vector3.CrossProduct(p1 - p0, p2 - p0); _normal.Normalize(); _const = -Vector3.DotProduct(_normal, p0); } /// <summary> /// Initializes a new instance of the <see cref="Plane"/> class using given a plane to assign values from. /// </summary> /// <param name="p">A 3D plane to assign values from.</param> public Plane(Plane p) { _normal = p.Normal; _const = p.Constant; } /// <summary> /// Initializes a new instance of the <see cref="Plane"/> class with serialized data. /// </summary> /// <param name="info">The object that holds the serialized object data.</param> /// <param name="context">The contextual information about the source or destination.</param> private Plane(SerializationInfo info, StreamingContext context) { _normal = (Vector3)info.GetValue("Normal", typeof(Vector3)); _const = info.GetSingle("Constant"); } #endregion #region Constants /// <summary> /// /// </summary> /// <param name="pPlane"></param> /// <param name="pPoint"></param> /// <returns></returns> public static Plane CreateParallelPlane(Plane pPlane, Vector3 pPoint) { return new Plane(pPlane.Normal.Clone(), pPoint.Clone()); } /// <summary> /// f(x,y) = a *x + b*y + c /// </summary> /// <param name="pA"></param> /// <param name="pB"></param> /// <param name="pC"></param> /// <returns></returns> public static Plane CreateFormFunctionXYCoefficient(double pA, double pB, double pC) { Vector3 v1 = new Vector3(1, 1, pA + pB + pC); Vector3 v2 = new Vector3(2, 1, pA * 2 + pB * 1 + pC); Vector3 v3 = new Vector3(1, 2, pA * 1 + pB * 2 + pC); return new Plane(v1, v2, v3); } #endregion #region Public Properties /// <summary> /// Gets or sets the plane's normal vector. /// </summary> public Vector3 Normal { get { return _normal; } set { _normal = value;} } /// <summary> /// Gets or sets the plane's constant value. /// </summary> public double Constant { get { return _const; } set { _const = value;} } #endregion #region ICloneable Members /// <summary> /// Creates an exact copy of this <see cref="Plane"/> object. /// </summary> /// <returns>The <see cref="Plane"/> object this method creates, cast as an object.</returns> object ICloneable.Clone() { return new Plane(this); } /// <summary> /// Creates an exact copy of this <see cref="Plane"/> object. /// </summary> /// <returns>The <see cref="Plane"/> object this method creates.</returns> public Plane Clone() { return new Plane(this); } #endregion #region ISerializable Members /// <summary> /// Populates a <see cref="SerializationInfo"/> with the data needed to serialize the target object. /// </summary> /// <param name="info">The <see cref="SerializationInfo"/> to populate with data. </param> /// <param name="context">The destination (see <see cref="StreamingContext"/>) for this serialization.</param> //[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter=true)] public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("Normal", _normal, typeof(Vector3)); info.AddValue("Constant", _const); } #endregion #region Public Static Parse Methods /// <summary> /// Converts the specified string to its <see cref="Plane"/> equivalent. /// </summary> /// <param name="s">A string representation of a <see cref="Plane"/></param> /// <returns>A <see cref="Plane"/> that represents the vector specified by the <paramref name="s"/> parameter.</returns> public static Plane Parse(string s) { Regex r = new Regex(@"Plane\(n=(?<normal>\([^\)]*\)), c=(?<const>.*)\)", RegexOptions.None); Match m = r.Match(s); if (m.Success) { return new Plane( Vector3.Parse(m.Result("${normal}")), double.Parse(m.Result("${const}")) ); } else { throw new ParseException("Unsuccessful Match."); } } #endregion #region Public Methods /// <summary> /// Flip the plane. /// </summary> public void Flip() { _normal = -_normal; } /// <summary> /// Creates a new flipped plane (-normal, constant). /// </summary> /// <returns>A new <see cref="Plane"/> instance.</returns> public Plane GetFlipped() { return new Plane(-_normal, _const); } /// <summary> /// Returns the points's position relative to the plane itself (i.e Front/Back/On) /// </summary> /// <param name="p">A point in 3D space.</param> /// <returns>A <see cref="MathFunctions.Sign"/>.</returns> public MathFunctions.Sign GetSign(Vector3 p) { return MathFunctions.GetSign(DistanceMethods.Distance(p,this)); } /// <summary> /// Returns the points's position relative to the plane itself (i.e Front/Back/On) /// </summary> /// <param name="p">A point in 3D space.</param> /// <param name="tolerance">The tolerance value to use.</param> /// <returns>A <see cref="MathFunctions.Sign"/>.</returns> /// <remarks> /// If the point's distance from the plane is withon the [-tolerance, tolerance] range, the point is considered to be on the plane. /// </remarks> public MathFunctions.Sign GetSign(Vector3 p, double tolerance) { return MathFunctions.GetSign(DistanceMethods.Distance(p,this), tolerance); } #endregion #region Overrides /// <summary> /// Returns the hashcode for this instance. /// </summary> /// <returns>A 32-bit signed integer hash code.</returns> public override int GetHashCode() { return _normal.GetHashCode() ^ _const.GetHashCode(); } /// <summary> /// Returns a value indicating whether this instance is equal to /// the specified object. /// </summary> /// <param name="obj">An object to compare to this instance.</param> /// <returns><see langword="true"/> if <paramref name="obj"/> is a <see cref="Vector2"/> and has the same values as this instance; otherwise, <see langword="false"/>.</returns> public override bool Equals(object obj) { if(obj is Plane) { Plane p = (Plane)obj; return (_normal == p.Normal) && (_const == p.Constant); } return false; } /// <summary> /// Returns a string representation of this object. /// </summary> /// <returns>A string representation of this object.</returns> public override string ToString() { return string.Format("Plane[n={0}, c={1}]", _normal, _const); } #endregion #region Comparison Operators /// <summary> /// Tests whether two specified planes are equal. /// </summary> /// <param name="a">The left-hand plane.</param> /// <param name="b">The right-hand plane.</param> /// <returns><see langword="true"/> if the two planes are equal; otherwise, <see langword="false"/>.</returns> public static bool operator==(Plane a, Plane b) { return ValueType.Equals(a,b); } /// <summary> /// Tests whether two specified planes are not equal. /// </summary> /// <param name="a">The left-hand plane.</param> /// <param name="b">The right-hand plane.</param> /// <returns><see langword="true"/> if the two planes are not equal; otherwise, <see langword="false"/>.</returns> public static bool operator!=(Plane a, Plane b) { return !ValueType.Equals(a,b); } #endregion /// <summary> /// Koordinatengleichung /// ax1 + bx2 + cx3 + d = 0 /// </summary> public double[] equation() { return new double[4] { _normal.X, _normal.Y, _normal.Z, _const }; } /*public Vector3D[] getParameterform() { double a = _normal.X; double b = _normal.Y; double c = _normal.Z; double d = _const; Vector3D orts, r1, r2; if (a != 0) { orts = new Vector3D(d / a, 0, 0); r1 = new Vector3D(-b / a, 1, 0); r2 = new Vector3D(-c / a, 0, 1); } else if (b != 0) { orts = new Vector3D(0, d / b, 0); r1 = new Vector3D(1, -a / b, 0); r2 = new Vector3D(0, -c / b, 1); } else if (c != 0) { orts = new Vector3D(0, 0, d / c); r1 = new Vector3D(1, 0, -a / c); r2 = new Vector3D(0, 1, -b / c); } else { throw new DivideByZeroException(); } return new Vector3D[] { orts, r1, r2 }; }*/ public List<Vector3> GetPointsOnPlane() { double a = _normal.X; double b = _normal.Y; double c = _normal.Z; double d = _const; Vector3 v1, v2, v3; if (a != 0.0) { v1 = new Vector3(-(b * 0+c *0+d)/a, 0, 0 ); v2 = new Vector3( -(b * 1+c *1+d)/a, 1, 1); v3 = new Vector3( -(b * 1+c *0+d)/a, 1, 0); } else if (b != 0.0) { v1 = new Vector3( 0, -(a * 0+c * 0+d)/b, 0); v2 = new Vector3( 1, -(a * 1+c * 1+d)/b, 1); v3 = new Vector3( 1, -(a * 1+c * 0+d)/b, 0); } else if (c != 0.0) { v1 = new Vector3(0, 0, -(d + a * 0 + b * 0) / c); v2 = new Vector3(1, 1, -(d + a * 1 + b * 1) / c); v3 = new Vector3(0, 1, -(d + a * 0 + b * 1) / c); } else throw new Exception(); return new List<Vector3>() {v1, v2, v3}; } /// <summary> /// X Plane based on ZY axis directions. /// </summary> public static Plane CreateXPlane() { return new Plane(Vector3.Zero(), Vector3.ZAxis(), Vector3.YAxis()); } /// <summary> /// Y Plane based on XZ axis directions. /// </summary> public static Plane CreateYPlane() { return new Plane(Vector3.Zero(), Vector3.XAxis(), Vector3.ZAxis()); } /// <summary> /// Z Plane based on XY axis drections. /// </summary> public static Plane CreateZPlane() { return new Plane(Vector3.Zero(), Vector3.XAxis(), Vector3.YAxis()); } /// <summary> /// Plane throgut pPoint /// </summary> /// <param name="pPoint"></param> /// <returns></returns> public static Plane CreateXPlane(Vector3 pPoint) { return new Plane(new Vector3(pPoint.X, 0, 0), Vector3.ZAxis(), Vector3.YAxis()); } /// <summary> /// Plane throgut pPoint /// </summary> /// <param name="pPoint"></param> /// <returns></returns> public static Plane CreateYPlane(Vector3 pPoint) { return new Plane(new Vector3(0, pPoint.Y, 0), Vector3.XAxis(), Vector3.ZAxis()); } /// <summary> /// Plane throgut pPoint /// </summary> /// <param name="pPoint"></param> /// <returns></returns> public static Plane CreateZPlane(Vector3 pPoint) { return new Plane(new Vector3(0, 0, pPoint.Z), Vector3.XAxis(), Vector3.ZAxis()); } } #region PlaneConverter class /// <summary> /// Converts a <see cref="Plane"/> to and from string representation. /// </summary> public class PlaneConverter : ExpandableObjectConverter { /// <summary> /// Returns whether this converter can convert an object of the given type to the type of this converter, using the specified context. /// </summary> /// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param> /// <param name="sourceType">A <see cref="Type"/> that represents the type you want to convert from.</param> /// <returns><b>true</b> if this converter can perform the conversion; otherwise, <b>false</b>.</returns> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) return true; return base.CanConvertFrom (context, sourceType); } /// <summary> /// Returns whether this converter can convert the object to the specified type, using the specified context. /// </summary> /// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param> /// <param name="destinationType">A <see cref="Type"/> that represents the type you want to convert to.</param> /// <returns><b>true</b> if this converter can perform the conversion; otherwise, <b>false</b>.</returns> public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(string)) return true; return base.CanConvertTo (context, destinationType); } /// <summary> /// Converts the given value object to the specified type, using the specified context and culture information. /// </summary> /// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param> /// <param name="culture">A <see cref="System.Globalization.CultureInfo"/> object. If a null reference (Nothing in Visual Basic) is passed, the current culture is assumed.</param> /// <param name="value">The <see cref="Object"/> to convert.</param> /// <param name="destinationType">The Type to convert the <paramref name="value"/> parameter to.</param> /// <returns>An <see cref="Object"/> that represents the converted value.</returns> public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if ((destinationType == typeof(string)) && (value is Plane)) { Plane c = (Plane)value; return c.ToString(); } return base.ConvertTo (context, culture, value, destinationType); } /// <summary> /// Converts the given object to the type of this converter, using the specified context and culture information. /// </summary> /// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param> /// <param name="culture">The <see cref="System.Globalization.CultureInfo"/> to use as the current culture. </param> /// <param name="value">The <see cref="Object"/> to convert.</param> /// <returns>An <see cref="Object"/> that represents the converted value.</returns> /// <exception cref="ParseException">Failed parsing from string.</exception> public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { if (value.GetType() == typeof(string)) { return Plane.Parse((string)value); } return base.ConvertFrom (context, culture, value); } } #endregion }
// 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 gcav = Google.Cloud.AIPlatform.V1; using sys = System; namespace Google.Cloud.AIPlatform.V1 { /// <summary>Resource name for the <c>CustomJob</c> resource.</summary> public sealed partial class CustomJobName : gax::IResourceName, sys::IEquatable<CustomJobName> { /// <summary>The possible contents of <see cref="CustomJobName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/customJobs/{custom_job}</c>. /// </summary> ProjectLocationCustomJob = 1, } private static gax::PathTemplate s_projectLocationCustomJob = new gax::PathTemplate("projects/{project}/locations/{location}/customJobs/{custom_job}"); /// <summary>Creates a <see cref="CustomJobName"/> 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="CustomJobName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static CustomJobName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new CustomJobName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="CustomJobName"/> with the pattern /// <c>projects/{project}/locations/{location}/customJobs/{custom_job}</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="customJobId">The <c>CustomJob</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="CustomJobName"/> constructed from the provided ids.</returns> public static CustomJobName FromProjectLocationCustomJob(string projectId, string locationId, string customJobId) => new CustomJobName(ResourceNameType.ProjectLocationCustomJob, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), customJobId: gax::GaxPreconditions.CheckNotNullOrEmpty(customJobId, nameof(customJobId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="CustomJobName"/> with pattern /// <c>projects/{project}/locations/{location}/customJobs/{custom_job}</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="customJobId">The <c>CustomJob</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CustomJobName"/> with pattern /// <c>projects/{project}/locations/{location}/customJobs/{custom_job}</c>. /// </returns> public static string Format(string projectId, string locationId, string customJobId) => FormatProjectLocationCustomJob(projectId, locationId, customJobId); /// <summary> /// Formats the IDs into the string representation of this <see cref="CustomJobName"/> with pattern /// <c>projects/{project}/locations/{location}/customJobs/{custom_job}</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="customJobId">The <c>CustomJob</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CustomJobName"/> with pattern /// <c>projects/{project}/locations/{location}/customJobs/{custom_job}</c>. /// </returns> public static string FormatProjectLocationCustomJob(string projectId, string locationId, string customJobId) => s_projectLocationCustomJob.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(customJobId, nameof(customJobId))); /// <summary>Parses the given resource name string into a new <see cref="CustomJobName"/> 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}/customJobs/{custom_job}</c></description> /// </item> /// </list> /// </remarks> /// <param name="customJobName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="CustomJobName"/> if successful.</returns> public static CustomJobName Parse(string customJobName) => Parse(customJobName, false); /// <summary> /// Parses the given resource name string into a new <see cref="CustomJobName"/> 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}/customJobs/{custom_job}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="customJobName">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="CustomJobName"/> if successful.</returns> public static CustomJobName Parse(string customJobName, bool allowUnparsed) => TryParse(customJobName, allowUnparsed, out CustomJobName 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="CustomJobName"/> 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}/customJobs/{custom_job}</c></description> /// </item> /// </list> /// </remarks> /// <param name="customJobName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="CustomJobName"/>, 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 customJobName, out CustomJobName result) => TryParse(customJobName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CustomJobName"/> 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}/customJobs/{custom_job}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="customJobName">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="CustomJobName"/>, 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 customJobName, bool allowUnparsed, out CustomJobName result) { gax::GaxPreconditions.CheckNotNull(customJobName, nameof(customJobName)); gax::TemplatedResourceName resourceName; if (s_projectLocationCustomJob.TryParseName(customJobName, out resourceName)) { result = FromProjectLocationCustomJob(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(customJobName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private CustomJobName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customJobId = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; CustomJobId = customJobId; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="CustomJobName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/customJobs/{custom_job}</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="customJobId">The <c>CustomJob</c> ID. Must not be <c>null</c> or empty.</param> public CustomJobName(string projectId, string locationId, string customJobId) : this(ResourceNameType.ProjectLocationCustomJob, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), customJobId: gax::GaxPreconditions.CheckNotNullOrEmpty(customJobId, nameof(customJobId))) { } /// <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>CustomJob</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomJobId { 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.ProjectLocationCustomJob: return s_projectLocationCustomJob.Expand(ProjectId, LocationId, CustomJobId); 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 CustomJobName); /// <inheritdoc/> public bool Equals(CustomJobName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(CustomJobName a, CustomJobName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(CustomJobName a, CustomJobName b) => !(a == b); } public partial class CustomJob { /// <summary> /// <see cref="gcav::CustomJobName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcav::CustomJobName CustomJobName { get => string.IsNullOrEmpty(Name) ? null : gcav::CustomJobName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class CustomJobSpec { /// <summary> /// <see cref="NetworkName"/>-typed view over the <see cref="Network"/> resource name property. /// </summary> public NetworkName NetworkAsNetworkName { get => string.IsNullOrEmpty(Network) ? null : NetworkName.Parse(Network, allowUnparsed: true); set => Network = value?.ToString() ?? ""; } /// <summary> /// <see cref="TensorboardName"/>-typed view over the <see cref="Tensorboard"/> resource name property. /// </summary> public TensorboardName TensorboardAsTensorboardName { get => string.IsNullOrEmpty(Tensorboard) ? null : TensorboardName.Parse(Tensorboard, allowUnparsed: true); set => Tensorboard = value?.ToString() ?? ""; } } }
// *********************************************************************** // Copyright (c) 2009-2015 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections.Generic; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.Framework.Internal.Builders; namespace NUnit.Framework { /// <summary> /// TestFixtureAttribute is used to mark a class that represents a TestFixture. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple=true, Inherited=true)] public class TestFixtureAttribute : NUnitAttribute, IFixtureBuilder, ITestFixtureData { private readonly NUnitTestFixtureBuilder _builder = new NUnitTestFixtureBuilder(); #region Constructors /// <summary> /// Default constructor /// </summary> public TestFixtureAttribute() : this( new object[0] ) { } /// <summary> /// Construct with a object[] representing a set of arguments. /// In .NET 2.0, the arguments may later be separated into /// type arguments and constructor arguments. /// </summary> /// <param name="arguments"></param> public TestFixtureAttribute(params object[] arguments) { RunState = RunState.Runnable; Arguments = arguments; TypeArgs = new Type[0]; Properties = new PropertyBag(); } #endregion #region ITestData Members /// <summary> /// Gets or sets the name of the test. /// </summary> /// <value>The name of the test.</value> public string TestName { get; set; } /// <summary> /// Gets or sets the RunState of this test fixture. /// </summary> public RunState RunState { get; private set; } /// <summary> /// The arguments originally provided to the attribute /// </summary> public object[] Arguments { get; private set; } /// <summary> /// Properties pertaining to this fixture /// </summary> public IPropertyBag Properties { get; private set; } #endregion #region ITestFixtureData Members /// <summary> /// Get or set the type arguments. If not set /// explicitly, any leading arguments that are /// Types are taken as type arguments. /// </summary> public Type[] TypeArgs { get; set; } #endregion #region Other Properties /// <summary> /// Descriptive text for this fixture /// </summary> public string Description { get { return Properties.Get(PropertyNames.Description) as string; } set { Properties.Set(PropertyNames.Description, value); } } /// <summary> /// The author of this fixture /// </summary> public string Author { get { return Properties.Get(PropertyNames.Author) as string; } set { Properties.Set(PropertyNames.Author, value); } } /// <summary> /// The type that this fixture is testing /// </summary> public Type TestOf { get { return _testOf; } set { _testOf = value; Properties.Set(PropertyNames.TestOf, value.FullName); } } private Type _testOf; /// <summary> /// Gets or sets the ignore reason. May set RunState as a side effect. /// </summary> /// <value>The ignore reason.</value> public string Ignore { get { return IgnoreReason; } set { IgnoreReason = value; } } /// <summary> /// Gets or sets the reason for not running the fixture. /// </summary> /// <value>The reason.</value> public string Reason { get { return this.Properties.Get(PropertyNames.SkipReason) as string; } set { this.Properties.Set(PropertyNames.SkipReason, value); } } /// <summary> /// Gets or sets the ignore reason. When set to a non-null /// non-empty value, the test is marked as ignored. /// </summary> /// <value>The ignore reason.</value> public string IgnoreReason { get { return Reason; } set { RunState = RunState.Ignored; Reason = value; } } /// <summary> /// Gets or sets a value indicating whether this <see cref="NUnit.Framework.TestFixtureAttribute"/> is explicit. /// </summary> /// <value> /// <c>true</c> if explicit; otherwise, <c>false</c>. /// </value> public bool Explicit { get { return RunState == RunState.Explicit; } set { RunState = value ? RunState.Explicit : RunState.Runnable; } } /// <summary> /// Gets and sets the category for this fixture. /// May be a comma-separated list of categories. /// </summary> public string Category { get { //return Properties.Get(PropertyNames.Category) as string; var catList = Properties[PropertyNames.Category]; if (catList == null) return null; switch (catList.Count) { case 0: return null; case 1: return catList[0] as string; default: var cats = new string[catList.Count]; int index = 0; foreach (string cat in catList) cats[index++] = cat; return string.Join(",", cats); } } set { foreach (string cat in value.Split(new char[] { ',' })) Properties.Add(PropertyNames.Category, cat); } } #endregion #region IFixtureBuilder Members /// <summary> /// Build a fixture from type provided. Normally called for a Type /// on which the attribute has been placed. /// </summary> /// <param name="typeInfo">The type info of the fixture to be used.</param> /// <returns>A an IEnumerable holding one TestFixture object.</returns> public IEnumerable<TestSuite> BuildFrom(ITypeInfo typeInfo) { yield return _builder.BuildFrom(typeInfo, this); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Reflection; using System.Collections; using System.Collections.Generic; using ActivatorTestsTestData; using Xunit; public static class ActivatorTests { [Fact] public static void TestActivatorCreateInstanceBinding() { Type t; Object[] args; Choice1 c1; // Root the constructors if (String.Empty.Length > 0) { new Choice1(); new Choice1(123); new Choice1("Hey"); new Choice1(5.1); new Choice1(new VarArgs()); new Choice1(new VarStringArgs()); new Choice1(new VarIntArgs()); } t = null; args = new Object[1]; Assert.Throws<ArgumentNullException>(() => Activator.CreateInstance(t, args)); t = typeof(Choice1); args = null; // Passing a null args is equivalent to passing an empty array of args. c1 = (Choice1)(Activator.CreateInstance(t, args)); Assert.Equal(c1.I, 1); t = typeof(Choice1); args = new Object[] { }; c1 = (Choice1)(Activator.CreateInstance(t, args)); Assert.Equal(c1.I, 1); t = typeof(Choice1); args = new Object[] { 42 }; c1 = (Choice1)(Activator.CreateInstance(t, args)); Assert.Equal(c1.I, 2); // Primitive widening is allowed by the binder. // but not by Dynamic.DelegateInvoke()... { t = typeof(Choice1); args = new Object[] { (short)(-2) }; c1 = (Choice1)(Activator.CreateInstance(t, args)); Assert.Equal(c1.I, 2); } t = typeof(Choice1); args = new Object[] { "Hello" }; c1 = (Choice1)(Activator.CreateInstance(t, args)); Assert.Equal(c1.I, 3); t = typeof(Choice1); args = new Object[] { null }; Assert.Throws<AmbiguousMatchException>(() => Activator.CreateInstance(t, args)); // "optional" parameters are not optional as far as Activator.CreateInstance() is concerned. t = typeof(Choice1); args = new Object[] { 5.1 }; Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance(t, args)); t = typeof(Choice1); args = new Object[] { 5.1, Type.Missing }; Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance(t, args)); t = typeof(Choice1); args = new Object[] { 5.1, "Yes" }; c1 = (Choice1)(Activator.CreateInstance(t, args)); Assert.Equal(c1.I, 4); // // "params" arguments are honored by Activator.CreateInstance() // VarArgs varArgs = new VarArgs(); t = typeof(Choice1); args = new Object[] { varArgs }; c1 = (Choice1)(Activator.CreateInstance(t, args)); Assert.Equal(c1.I, 5); t = typeof(Choice1); args = new Object[] { varArgs, "P1" }; c1 = (Choice1)(Activator.CreateInstance(t, args)); Assert.Equal(c1.I, 5); t = typeof(Choice1); args = new Object[] { varArgs, "P1", "P2" }; c1 = (Choice1)(Activator.CreateInstance(t, args)); Assert.Equal(c1.I, 5); VarStringArgs varStringArgs = new VarStringArgs(); t = typeof(Choice1); args = new Object[] { varStringArgs }; c1 = (Choice1)(Activator.CreateInstance(t, args)); Assert.Equal(c1.I, 6); t = typeof(Choice1); args = new Object[] { varStringArgs, "P1" }; c1 = (Choice1)(Activator.CreateInstance(t, args)); Assert.Equal(c1.I, 6); t = typeof(Choice1); args = new Object[] { varStringArgs, "P1", "P2" }; c1 = (Choice1)(Activator.CreateInstance(t, args)); Assert.Equal(c1.I, 6); t = typeof(Choice1); args = new Object[] { varStringArgs, 5, 6 }; Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance(t, args)); // // Primitive widening not supported for "params" arguments. // // (This is probably an accidental behavior on the desktop as the default binder specifically checks to see if the params arguments are widenable to the // params array element type and gives it the go-ahead if it is. Unfortunately, the binder then bollixes itself by using Array.Copy() to copy // the params arguments. Since Array.Copy() doesn't tolerate this sort of type mismatch, it throws an InvalidCastException which bubbles out // out of Activator.CreateInstance. Accidental or not, we'll inherit that behavior on .NET Native.) // VarIntArgs varIntArgs = new VarIntArgs(); t = typeof(Choice1); args = new Object[] { varIntArgs, 1, (short)2 }; Assert.Throws<InvalidCastException>(() => Activator.CreateInstance(t, args)); return; } public class TypeWithoutDefaultCtor { private TypeWithoutDefaultCtor(int x) { } } private class CustomException : Exception { } private struct StructTypeWithoutReflectionMetadata { } public class TypeWithDefaultCtorThatThrows { public TypeWithDefaultCtorThatThrows() { throw new CustomException(); } } [Fact] public static void TestActivatorOnNonActivatableTypes() { int x = 0; Assert.ThrowsAny<MissingMemberException>(() => { ++x; Activator.CreateInstance<TypeWithoutDefaultCtor>(); }); Assert.Throws<TargetInvocationException>(() => { ++x; Activator.CreateInstance<TypeWithDefaultCtorThatThrows>(); }); } [Fact] public static void TestActivatorWithDelegates() { Func<object> activate1 = Activator.CreateInstance<Choice1>; Assert.True(activate1() is Choice1); Func<DateTime> activateDateTime = Activator.CreateInstance<DateTime>; activateDateTime(); Func<StructTypeWithoutReflectionMetadata> activateStruct = Activator.CreateInstance<StructTypeWithoutReflectionMetadata>; activateStruct(); Func<object> activate2 = Activator.CreateInstance<TypeWithoutDefaultCtor>; Assert.ThrowsAny<MissingMemberException>(() => activate2()); Func<object> activate3 = Activator.CreateInstance<TypeWithDefaultCtorThatThrows>; Assert.Throws<TargetInvocationException>(() => activate3()); } } namespace ActivatorTestsTestData { public class Choice1 : Attribute { public Choice1() { I = 1; } public Choice1(int i) { I = 2; } public Choice1(String s) { I = 3; } public Choice1(double d, String optionalS = "Hey") { I = 4; } public Choice1(VarArgs varArgs, params Object[] parameters) { I = 5; } public Choice1(VarStringArgs varArgs, params String[] parameters) { I = 6; } public Choice1(VarIntArgs varArgs, params int[] parameters) { I = 7; } public int I; } public class VarArgs { } public class VarStringArgs { } public class VarIntArgs { } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Runtime; using System.Runtime.Serialization; using System.Security; using System.Text; using System.Xml; namespace System.Runtime.Serialization.Json { internal class XmlJsonWriter : XmlDictionaryWriter, IXmlJsonWriterInitializer { private const char BACK_SLASH = '\\'; private const char FORWARD_SLASH = '/'; private const char HIGH_SURROGATE_START = (char)0xd800; private const char LOW_SURROGATE_END = (char)0xdfff; private const char MAX_CHAR = (char)0xfffe; private const char WHITESPACE = ' '; private const char CARRIAGE_RETURN = '\r'; private const char NEWLINE = '\n'; private const string xmlNamespace = "http://www.w3.org/XML/1998/namespace"; private const string xmlnsNamespace = "http://www.w3.org/2000/xmlns/"; [SecurityCritical] private static BinHexEncoding s_binHexEncoding; private string _attributeText; private JsonDataType _dataType; private int _depth; private bool _endElementBuffer; private bool _isWritingDataTypeAttribute; private bool _isWritingServerTypeAttribute; private bool _isWritingXmlnsAttribute; private bool _isWritingXmlnsAttributeDefaultNs; private NameState _nameState; private JsonNodeType _nodeType; private JsonNodeWriter _nodeWriter; private JsonNodeType[] _scopes; private string _serverTypeValue; // Do not use this field's value anywhere other than the WriteState property. // It's OK to set this field's value anywhere and then change the WriteState property appropriately. // If it's necessary to check the WriteState outside WriteState, use the WriteState property. private WriteState _writeState; private bool _wroteServerTypeAttribute; private bool _indent; private string _indentChars; private int _indentLevel; public XmlJsonWriter() : this(false, null) { } public XmlJsonWriter(bool indent, string indentChars) { _indent = indent; if (indent) { if (indentChars == null) { throw new ArgumentNullException("indentChars"); } _indentChars = indentChars; } InitializeWriter(); } private enum JsonDataType { None, Null, Boolean, Number, String, Object, Array }; [Flags] private enum NameState { None = 0, IsWritingNameWithMapping = 1, IsWritingNameAttribute = 2, WrittenNameWithMapping = 4, } public override XmlWriterSettings Settings { // The XmlWriterSettings object used to create this writer instance. // If this writer was not created using the Create method, this property // returns a null reference. get { return null; } } public override WriteState WriteState { get { if (_writeState == WriteState.Closed) { return WriteState.Closed; } if (HasOpenAttribute) { return WriteState.Attribute; } switch (_nodeType) { case JsonNodeType.None: return WriteState.Start; case JsonNodeType.Element: return WriteState.Element; case JsonNodeType.QuotedText: case JsonNodeType.StandaloneText: case JsonNodeType.EndElement: return WriteState.Content; default: return WriteState.Error; } } } public override string XmlLang { get { return null; } } public override XmlSpace XmlSpace { get { return XmlSpace.None; } } private static BinHexEncoding BinHexEncoding { [SecuritySafeCritical] get { if (s_binHexEncoding == null) { s_binHexEncoding = new BinHexEncoding(); } return s_binHexEncoding; } } private bool HasOpenAttribute { get { return (_isWritingDataTypeAttribute || _isWritingServerTypeAttribute || IsWritingNameAttribute || _isWritingXmlnsAttribute); } } private bool IsClosed { get { return (WriteState == WriteState.Closed); } } private bool IsWritingCollection { get { return (_depth > 0) && (_scopes[_depth] == JsonNodeType.Collection); } } private bool IsWritingNameAttribute { get { return (_nameState & NameState.IsWritingNameAttribute) == NameState.IsWritingNameAttribute; } } private bool IsWritingNameWithMapping { get { return (_nameState & NameState.IsWritingNameWithMapping) == NameState.IsWritingNameWithMapping; } } private bool WrittenNameWithMapping { get { return (_nameState & NameState.WrittenNameWithMapping) == NameState.WrittenNameWithMapping; } } protected override void Dispose(bool disposing) { if (!IsClosed) { try { WriteEndDocument(); } finally { try { _nodeWriter.Flush(); _nodeWriter.Close(); } finally { _writeState = WriteState.Closed; if (_depth != 0) { _depth = 0; } } } } base.Dispose(disposing); } public override void Flush() { if (IsClosed) { ThrowClosed(); } _nodeWriter.Flush(); } public override string LookupPrefix(string ns) { if (ns == null) { throw new ArgumentNullException("ns"); } if (ns == Globals.XmlnsNamespace) { return Globals.XmlnsPrefix; } if (ns == xmlNamespace) { return JsonGlobals.xmlPrefix; } if (ns == string.Empty) { return string.Empty; } return null; } public void SetOutput(Stream stream, Encoding encoding, bool ownsStream) { if (stream == null) { throw new ArgumentNullException("stream"); } if (encoding == null) { throw new ArgumentNullException("encoding"); } if (encoding.WebName != Encoding.UTF8.WebName) { stream = new JsonEncodingStreamWrapper(stream, encoding, false); } else { encoding = null; } if (_nodeWriter == null) { _nodeWriter = new JsonNodeWriter(); } _nodeWriter.SetOutput(stream, ownsStream, encoding); InitializeWriter(); } public override void WriteArray(string prefix, string localName, string namespaceUri, bool[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, string localName, string namespaceUri, Int16[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, string localName, string namespaceUri, Int32[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, string localName, string namespaceUri, Int64[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, string localName, string namespaceUri, float[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, string localName, string namespaceUri, double[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, string localName, string namespaceUri, decimal[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, string localName, string namespaceUri, DateTime[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, string localName, string namespaceUri, Guid[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, string localName, string namespaceUri, TimeSpan[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, int[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, long[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, short[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteBase64(byte[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } // Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does. if (index < 0) { throw new ArgumentOutOfRangeException("index", SR.ValueMustBeNonNegative); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ValueMustBeNonNegative); } if (count > buffer.Length - index) { throw new ArgumentOutOfRangeException("count", SR.Format(SR.JsonSizeExceedsRemainingBufferSpace, buffer.Length - index)); } StartText(); _nodeWriter.WriteBase64Text(buffer, 0, buffer, index, count); } public override void WriteBinHex(byte[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } // Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does. if (index < 0) { throw new ArgumentOutOfRangeException("index", SR.ValueMustBeNonNegative); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ValueMustBeNonNegative); } if (count > buffer.Length - index) { throw new ArgumentOutOfRangeException("count", SR.Format(SR.JsonSizeExceedsRemainingBufferSpace, buffer.Length - index)); } StartText(); WriteEscapedJsonString(BinHexEncoding.GetString(buffer, index, count)); } public override void WriteCData(string text) { WriteString(text); } public override void WriteCharEntity(char ch) { WriteString(ch.ToString()); } public override void WriteChars(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } // Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does. if (index < 0) { throw new ArgumentOutOfRangeException("index", SR.ValueMustBeNonNegative); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ValueMustBeNonNegative); } if (count > buffer.Length - index) { throw new ArgumentOutOfRangeException("count", SR.Format(SR.JsonSizeExceedsRemainingBufferSpace, buffer.Length - index)); } WriteString(new string(buffer, index, count)); } public override void WriteComment(string text) { throw new NotSupportedException(SR.Format(SR.JsonMethodNotSupported, "WriteComment")); } [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "2#sysid", Justification = "This method is derived from the base")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "1#pubid", Justification = "This method is derived from the base")] public override void WriteDocType(string name, string pubid, string sysid, string subset) { throw new NotSupportedException(SR.Format(SR.JsonMethodNotSupported, "WriteDocType")); } public override void WriteEndAttribute() { if (IsClosed) { ThrowClosed(); } if (!HasOpenAttribute) { throw new XmlException(SR.JsonNoMatchingStartAttribute); } Fx.Assert(!(_isWritingDataTypeAttribute && _isWritingServerTypeAttribute), "Can not write type attribute and __type attribute at the same time."); if (_isWritingDataTypeAttribute) { switch (_attributeText) { case JsonGlobals.numberString: { ThrowIfServerTypeWritten(JsonGlobals.numberString); _dataType = JsonDataType.Number; break; } case JsonGlobals.stringString: { ThrowIfServerTypeWritten(JsonGlobals.stringString); _dataType = JsonDataType.String; break; } case JsonGlobals.arrayString: { ThrowIfServerTypeWritten(JsonGlobals.arrayString); _dataType = JsonDataType.Array; break; } case JsonGlobals.objectString: { _dataType = JsonDataType.Object; break; } case JsonGlobals.nullString: { ThrowIfServerTypeWritten(JsonGlobals.nullString); _dataType = JsonDataType.Null; break; } case JsonGlobals.booleanString: { ThrowIfServerTypeWritten(JsonGlobals.booleanString); _dataType = JsonDataType.Boolean; break; } default: throw new XmlException(SR.Format(SR.JsonUnexpectedAttributeValue, _attributeText)); } _attributeText = null; _isWritingDataTypeAttribute = false; if (!IsWritingNameWithMapping || WrittenNameWithMapping) { WriteDataTypeServerType(); } } else if (_isWritingServerTypeAttribute) { _serverTypeValue = _attributeText; _attributeText = null; _isWritingServerTypeAttribute = false; // we are writing __type after type="object" (enforced by WSE) if ((!IsWritingNameWithMapping || WrittenNameWithMapping) && _dataType == JsonDataType.Object) { WriteServerTypeAttribute(); } } else if (IsWritingNameAttribute) { WriteJsonElementName(_attributeText); _attributeText = null; _nameState = NameState.IsWritingNameWithMapping | NameState.WrittenNameWithMapping; WriteDataTypeServerType(); } else if (_isWritingXmlnsAttribute) { if (!string.IsNullOrEmpty(_attributeText) && _isWritingXmlnsAttributeDefaultNs) { throw new ArgumentException(SR.Format(SR.JsonNamespaceMustBeEmpty, _attributeText)); } _attributeText = null; _isWritingXmlnsAttribute = false; _isWritingXmlnsAttributeDefaultNs = false; } } public override void WriteEndDocument() { if (IsClosed) { ThrowClosed(); } if (_nodeType != JsonNodeType.None) { while (_depth > 0) { WriteEndElement(); } } } public override void WriteEndElement() { if (IsClosed) { ThrowClosed(); } if (_depth == 0) { throw new XmlException(SR.JsonEndElementNoOpenNodes); } if (HasOpenAttribute) { throw new XmlException(SR.Format(SR.JsonOpenAttributeMustBeClosedFirst, "WriteEndElement")); } _endElementBuffer = false; JsonNodeType token = ExitScope(); if (token == JsonNodeType.Collection) { _indentLevel--; if (_indent) { if (_nodeType == JsonNodeType.Element) { _nodeWriter.WriteText(WHITESPACE); } else { WriteNewLine(); WriteIndent(); } } _nodeWriter.WriteText(JsonGlobals.EndCollectionChar); token = ExitScope(); } else if (_nodeType == JsonNodeType.QuotedText) { // For writing " WriteJsonQuote(); } else if (_nodeType == JsonNodeType.Element) { if ((_dataType == JsonDataType.None) && (_serverTypeValue != null)) { throw new XmlException(SR.Format(SR.JsonMustSpecifyDataType, JsonGlobals.typeString, JsonGlobals.objectString, JsonGlobals.serverTypeString)); } if (IsWritingNameWithMapping && !WrittenNameWithMapping) { // Ending </item> without writing item attribute // Not providing a better error message because localization deadline has passed. throw new XmlException(SR.Format(SR.JsonMustSpecifyDataType, JsonGlobals.itemString, string.Empty, JsonGlobals.itemString)); } // the element is empty, it does not have any content, if ((_dataType == JsonDataType.None) || (_dataType == JsonDataType.String)) { _nodeWriter.WriteText(JsonGlobals.QuoteChar); _nodeWriter.WriteText(JsonGlobals.QuoteChar); } } else { // Assert on only StandaloneText and EndElement because preceding if // conditions take care of checking for QuotedText and Element. Fx.Assert((_nodeType == JsonNodeType.StandaloneText) || (_nodeType == JsonNodeType.EndElement), "nodeType has invalid value " + _nodeType + ". Expected it to be QuotedText, Element, StandaloneText, or EndElement."); } if (_depth != 0) { if (token == JsonNodeType.Element) { _endElementBuffer = true; } else if (token == JsonNodeType.Object) { _indentLevel--; if (_indent) { if (_nodeType == JsonNodeType.Element) { _nodeWriter.WriteText(WHITESPACE); } else { WriteNewLine(); WriteIndent(); } } _nodeWriter.WriteText(JsonGlobals.EndObjectChar); if ((_depth > 0) && _scopes[_depth] == JsonNodeType.Element) { ExitScope(); _endElementBuffer = true; } } } _dataType = JsonDataType.None; _nodeType = JsonNodeType.EndElement; _nameState = NameState.None; _wroteServerTypeAttribute = false; } public override void WriteEntityRef(string name) { throw new NotSupportedException(SR.Format(SR.JsonMethodNotSupported, "WriteEntityRef")); } public override void WriteFullEndElement() { WriteEndElement(); } public override void WriteProcessingInstruction(string name, string text) { if (IsClosed) { ThrowClosed(); } if (!name.Equals("xml", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException(SR.JsonXmlProcessingInstructionNotSupported, "name"); } if (WriteState != WriteState.Start) { throw new XmlException(SR.JsonXmlInvalidDeclaration); } } public override void WriteQualifiedName(string localName, string ns) { if (localName == null) { throw new ArgumentNullException("localName"); } if (localName.Length == 0) { throw new ArgumentException(SR.JsonInvalidLocalNameEmpty, "localName"); } if (ns == null) { ns = string.Empty; } base.WriteQualifiedName(localName, ns); } public override void WriteRaw(string data) { WriteString(data); } public override void WriteRaw(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } // Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does. if (index < 0) { throw new ArgumentOutOfRangeException("index", SR.ValueMustBeNonNegative); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ValueMustBeNonNegative); } if (count > buffer.Length - index) { throw new ArgumentOutOfRangeException("count", SR.Format(SR.JsonSizeExceedsRemainingBufferSpace, buffer.Length - index)); } WriteString(new string(buffer, index, count)); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")] // Microsoft, ToLowerInvariant is just used in Json error message public override void WriteStartAttribute(string prefix, string localName, string ns) { if (IsClosed) { ThrowClosed(); } if (!string.IsNullOrEmpty(prefix)) { if (IsWritingNameWithMapping && prefix == JsonGlobals.xmlnsPrefix) { if (ns != null && ns != xmlnsNamespace) { throw new ArgumentException(SR.Format(SR.XmlPrefixBoundToNamespace, "xmlns", xmlnsNamespace, ns), "ns"); } } else { throw new ArgumentException(SR.Format(SR.JsonPrefixMustBeNullOrEmpty, prefix), "prefix"); } } else { if (IsWritingNameWithMapping && ns == xmlnsNamespace && localName != JsonGlobals.xmlnsPrefix) { prefix = JsonGlobals.xmlnsPrefix; } } if (!string.IsNullOrEmpty(ns)) { if (IsWritingNameWithMapping && ns == xmlnsNamespace) { prefix = JsonGlobals.xmlnsPrefix; } else if (string.IsNullOrEmpty(prefix) && localName == JsonGlobals.xmlnsPrefix && ns == xmlnsNamespace) { prefix = JsonGlobals.xmlnsPrefix; _isWritingXmlnsAttributeDefaultNs = true; } else { throw new ArgumentException(SR.Format(SR.JsonNamespaceMustBeEmpty, ns), "ns"); } } if (localName == null) { throw new ArgumentNullException("localName"); } if (localName.Length == 0) { throw new ArgumentException(SR.JsonInvalidLocalNameEmpty, "localName"); } if ((_nodeType != JsonNodeType.Element) && !_wroteServerTypeAttribute) { throw new XmlException(SR.JsonAttributeMustHaveElement); } if (HasOpenAttribute) { throw new XmlException(SR.Format(SR.JsonOpenAttributeMustBeClosedFirst, "WriteStartAttribute")); } if (prefix == JsonGlobals.xmlnsPrefix) { _isWritingXmlnsAttribute = true; } else if (localName == JsonGlobals.typeString) { if (_dataType != JsonDataType.None) { throw new XmlException(SR.Format(SR.JsonAttributeAlreadyWritten, JsonGlobals.typeString)); } _isWritingDataTypeAttribute = true; } else if (localName == JsonGlobals.serverTypeString) { if (_serverTypeValue != null) { throw new XmlException(SR.Format(SR.JsonAttributeAlreadyWritten, JsonGlobals.serverTypeString)); } if ((_dataType != JsonDataType.None) && (_dataType != JsonDataType.Object)) { throw new XmlException(SR.Format(SR.JsonServerTypeSpecifiedForInvalidDataType, JsonGlobals.serverTypeString, JsonGlobals.typeString, _dataType.ToString().ToLowerInvariant(), JsonGlobals.objectString)); } _isWritingServerTypeAttribute = true; } else if (localName == JsonGlobals.itemString) { if (WrittenNameWithMapping) { throw new XmlException(SR.Format(SR.JsonAttributeAlreadyWritten, JsonGlobals.itemString)); } if (!IsWritingNameWithMapping) { // Don't write attribute with local name "item" if <item> element is not open. // Not providing a better error message because localization deadline has passed. throw new XmlException(SR.JsonEndElementNoOpenNodes); } _nameState |= NameState.IsWritingNameAttribute; } else { throw new ArgumentException(SR.Format(SR.JsonUnexpectedAttributeLocalName, localName), "localName"); } } public override void WriteStartDocument(bool standalone) { // In XML, writes the XML declaration with the version "1.0" and the standalone attribute. WriteStartDocument(); } public override void WriteStartDocument() { // In XML, writes the XML declaration with the version "1.0". if (IsClosed) { ThrowClosed(); } if (WriteState != WriteState.Start) { throw new XmlException(SR.Format(SR.JsonInvalidWriteState, "WriteStartDocument", WriteState.ToString())); } } public override void WriteStartElement(string prefix, string localName, string ns) { if (localName == null) { throw new ArgumentNullException("localName"); } if (localName.Length == 0) { throw new ArgumentException(SR.JsonInvalidLocalNameEmpty, "localName"); } if (!string.IsNullOrEmpty(prefix)) { if (string.IsNullOrEmpty(ns) || !TrySetWritingNameWithMapping(localName, ns)) { throw new ArgumentException(SR.Format(SR.JsonPrefixMustBeNullOrEmpty, prefix), "prefix"); } } if (!string.IsNullOrEmpty(ns)) { if (!TrySetWritingNameWithMapping(localName, ns)) { throw new ArgumentException(SR.Format(SR.JsonNamespaceMustBeEmpty, ns), "ns"); } } if (IsClosed) { ThrowClosed(); } if (HasOpenAttribute) { throw new XmlException(SR.Format(SR.JsonOpenAttributeMustBeClosedFirst, "WriteStartElement")); } if ((_nodeType != JsonNodeType.None) && _depth == 0) { throw new XmlException(SR.JsonMultipleRootElementsNotAllowedOnWriter); } switch (_nodeType) { case JsonNodeType.None: { if (!localName.Equals(JsonGlobals.rootString)) { throw new XmlException(SR.Format(SR.JsonInvalidRootElementName, localName, JsonGlobals.rootString)); } EnterScope(JsonNodeType.Element); break; } case JsonNodeType.Element: { if ((_dataType != JsonDataType.Array) && (_dataType != JsonDataType.Object)) { throw new XmlException(SR.JsonNodeTypeArrayOrObjectNotSpecified); } if (_indent) { WriteNewLine(); WriteIndent(); } if (!IsWritingCollection) { if (_nameState != NameState.IsWritingNameWithMapping) { WriteJsonElementName(localName); } } else if (!localName.Equals(JsonGlobals.itemString)) { throw new XmlException(SR.Format(SR.JsonInvalidItemNameForArrayElement, localName, JsonGlobals.itemString)); } EnterScope(JsonNodeType.Element); break; } case JsonNodeType.EndElement: { if (_endElementBuffer) { _nodeWriter.WriteText(JsonGlobals.MemberSeparatorChar); } if (_indent) { WriteNewLine(); WriteIndent(); } if (!IsWritingCollection) { if (_nameState != NameState.IsWritingNameWithMapping) { WriteJsonElementName(localName); } } else if (!localName.Equals(JsonGlobals.itemString)) { throw new XmlException(SR.Format(SR.JsonInvalidItemNameForArrayElement, localName, JsonGlobals.itemString)); } EnterScope(JsonNodeType.Element); break; } default: throw new XmlException(SR.JsonInvalidStartElementCall); } _isWritingDataTypeAttribute = false; _isWritingServerTypeAttribute = false; _isWritingXmlnsAttribute = false; _wroteServerTypeAttribute = false; _serverTypeValue = null; _dataType = JsonDataType.None; _nodeType = JsonNodeType.Element; } public override void WriteString(string text) { if (HasOpenAttribute && (text != null)) { _attributeText += text; } else { if (text == null) { text = string.Empty; } // do work only when not indenting whitespaces if (!((_dataType == JsonDataType.Array || _dataType == JsonDataType.Object || _nodeType == JsonNodeType.EndElement) && XmlConverter.IsWhitespace(text))) { StartText(); WriteEscapedJsonString(text); } } } public override void WriteSurrogateCharEntity(char lowChar, char highChar) { WriteString(string.Concat(highChar, lowChar)); } public override void WriteValue(bool value) { StartText(); _nodeWriter.WriteBoolText(value); } public override void WriteValue(decimal value) { StartText(); _nodeWriter.WriteDecimalText(value); } public override void WriteValue(double value) { StartText(); _nodeWriter.WriteDoubleText(value); } public override void WriteValue(float value) { StartText(); _nodeWriter.WriteFloatText(value); } public override void WriteValue(int value) { StartText(); _nodeWriter.WriteInt32Text(value); } public override void WriteValue(long value) { StartText(); _nodeWriter.WriteInt64Text(value); } public override void WriteValue(Guid value) { StartText(); _nodeWriter.WriteGuidText(value); } public virtual void WriteValue(DateTime value) { StartText(); _nodeWriter.WriteDateTimeText(value); } public override void WriteValue(string value) { WriteString(value); } public override void WriteValue(TimeSpan value) { StartText(); _nodeWriter.WriteTimeSpanText(value); } public override void WriteValue(UniqueId value) { if (value == null) { throw new ArgumentNullException("value"); } StartText(); _nodeWriter.WriteUniqueIdText(value); } public override void WriteValue(object value) { if (IsClosed) { ThrowClosed(); } if (value == null) { throw new ArgumentNullException("value"); } if (value is Array) { WriteValue((Array)value); } else if (value is IStreamProvider) { WriteValue((IStreamProvider)value); } else { WritePrimitiveValue(value); } } [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace", Justification = "This method is derived from the base")] public override void WriteWhitespace(string ws) { if (IsClosed) { ThrowClosed(); } if (ws == null) { throw new ArgumentNullException("ws"); } for (int i = 0; i < ws.Length; ++i) { char c = ws[i]; if (c != ' ' && c != '\t' && c != '\n' && c != '\r') { throw new ArgumentException(SR.Format(SR.JsonOnlyWhitespace, c.ToString(), "WriteWhitespace"), "ws"); } } WriteString(ws); } public override void WriteXmlAttribute(string localName, string value) { throw new NotSupportedException(SR.Format(SR.JsonMethodNotSupported, "WriteXmlAttribute")); } public override void WriteXmlAttribute(XmlDictionaryString localName, XmlDictionaryString value) { throw new NotSupportedException(SR.Format(SR.JsonMethodNotSupported, "WriteXmlAttribute")); } public override void WriteXmlnsAttribute(string prefix, string namespaceUri) { if (!IsWritingNameWithMapping) { throw new NotSupportedException(SR.Format(SR.JsonMethodNotSupported, "WriteXmlnsAttribute")); } } public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString namespaceUri) { if (!IsWritingNameWithMapping) { throw new NotSupportedException(SR.Format(SR.JsonMethodNotSupported, "WriteXmlnsAttribute")); } } internal static bool CharacterNeedsEscaping(char ch) { return (ch == FORWARD_SLASH || ch == JsonGlobals.QuoteChar || ch < WHITESPACE || ch == BACK_SLASH || (ch >= HIGH_SURROGATE_START && (ch <= LOW_SURROGATE_END || ch >= MAX_CHAR))); } private static void ThrowClosed() { throw new InvalidOperationException(SR.JsonWriterClosed); } private void CheckText(JsonNodeType nextNodeType) { if (IsClosed) { ThrowClosed(); } if (_depth == 0) { throw new InvalidOperationException(SR.XmlIllegalOutsideRoot); } if ((nextNodeType == JsonNodeType.StandaloneText) && (_nodeType == JsonNodeType.QuotedText)) { throw new XmlException(SR.JsonCannotWriteStandaloneTextAfterQuotedText); } } private void EnterScope(JsonNodeType currentNodeType) { _depth++; if (_scopes == null) { _scopes = new JsonNodeType[4]; } else if (_scopes.Length == _depth) { JsonNodeType[] newScopes = new JsonNodeType[_depth * 2]; Array.Copy(_scopes, newScopes, _depth); _scopes = newScopes; } _scopes[_depth] = currentNodeType; } private JsonNodeType ExitScope() { JsonNodeType nodeTypeToReturn = _scopes[_depth]; _scopes[_depth] = JsonNodeType.None; _depth--; return nodeTypeToReturn; } private void InitializeWriter() { _nodeType = JsonNodeType.None; _dataType = JsonDataType.None; _isWritingDataTypeAttribute = false; _wroteServerTypeAttribute = false; _isWritingServerTypeAttribute = false; _serverTypeValue = null; _attributeText = null; if (_depth != 0) { _depth = 0; } if ((_scopes != null) && (_scopes.Length > JsonGlobals.maxScopeSize)) { _scopes = null; } // Can't let writeState be at Closed if reinitializing. _writeState = WriteState.Start; _endElementBuffer = false; _indentLevel = 0; } private static bool IsUnicodeNewlineCharacter(char c) { // Newline characters in JSON strings need to be encoded on the way out (DevDiv #665974) // See Unicode 6.2, Table 5-1 (http://www.unicode.org/versions/Unicode6.2.0/ch05.pdf]) for the full list. // We only care about NEL, LS, and PS, since the other newline characters are all // control characters so are already encoded. return (c == '\u0085' || c == '\u2028' || c == '\u2029'); } private void StartText() { if (HasOpenAttribute) { throw new InvalidOperationException(SR.JsonMustUseWriteStringForWritingAttributeValues); } if ((_dataType == JsonDataType.None) && (_serverTypeValue != null)) { throw new XmlException(SR.Format(SR.JsonMustSpecifyDataType, JsonGlobals.typeString, JsonGlobals.objectString, JsonGlobals.serverTypeString)); } if (IsWritingNameWithMapping && !WrittenNameWithMapping) { // Don't write out any text content unless the local name has been written. // Not providing a better error message because localization deadline has passed. throw new XmlException(SR.Format(SR.JsonMustSpecifyDataType, JsonGlobals.itemString, string.Empty, JsonGlobals.itemString)); } if ((_dataType == JsonDataType.String) || (_dataType == JsonDataType.None)) { CheckText(JsonNodeType.QuotedText); if (_nodeType != JsonNodeType.QuotedText) { WriteJsonQuote(); } _nodeType = JsonNodeType.QuotedText; } else if ((_dataType == JsonDataType.Number) || (_dataType == JsonDataType.Boolean)) { CheckText(JsonNodeType.StandaloneText); _nodeType = JsonNodeType.StandaloneText; } else { ThrowInvalidAttributeContent(); } } private void ThrowIfServerTypeWritten(string dataTypeSpecified) { if (_serverTypeValue != null) { throw new XmlException(SR.Format(SR.JsonInvalidDataTypeSpecifiedForServerType, JsonGlobals.typeString, dataTypeSpecified, JsonGlobals.serverTypeString, JsonGlobals.objectString)); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")] // Microsoft, ToLowerInvariant is just used in Json error message private void ThrowInvalidAttributeContent() { if (HasOpenAttribute) { throw new XmlException(SR.JsonInvalidMethodBetweenStartEndAttribute); } else { throw new XmlException(SR.Format(SR.JsonCannotWriteTextAfterNonTextAttribute, _dataType.ToString().ToLowerInvariant())); } } private bool TrySetWritingNameWithMapping(string localName, string ns) { if (localName.Equals(JsonGlobals.itemString) && ns.Equals(JsonGlobals.itemString)) { _nameState = NameState.IsWritingNameWithMapping; return true; } return false; } private void WriteDataTypeServerType() { if (_dataType != JsonDataType.None) { switch (_dataType) { case JsonDataType.Array: { EnterScope(JsonNodeType.Collection); _nodeWriter.WriteText(JsonGlobals.CollectionChar); _indentLevel++; break; } case JsonDataType.Object: { EnterScope(JsonNodeType.Object); _nodeWriter.WriteText(JsonGlobals.ObjectChar); _indentLevel++; break; } case JsonDataType.Null: { _nodeWriter.WriteText(JsonGlobals.nullString); break; } default: break; } if (_serverTypeValue != null) { // dataType must be object because we throw in all other case. WriteServerTypeAttribute(); } } } [SecuritySafeCritical] private unsafe void WriteEscapedJsonString(string str) { fixed (char* chars = str) { int i = 0; int j; for (j = 0; j < str.Length; j++) { char ch = chars[j]; if (ch <= FORWARD_SLASH) { if (ch == FORWARD_SLASH || ch == JsonGlobals.QuoteChar) { _nodeWriter.WriteChars(chars + i, j - i); _nodeWriter.WriteText(BACK_SLASH); _nodeWriter.WriteText(ch); i = j + 1; } else if (ch < WHITESPACE) { _nodeWriter.WriteChars(chars + i, j - i); _nodeWriter.WriteText(BACK_SLASH); _nodeWriter.WriteText('u'); _nodeWriter.WriteText(string.Format(CultureInfo.InvariantCulture, "{0:x4}", (int)ch)); i = j + 1; } } else if (ch == BACK_SLASH) { _nodeWriter.WriteChars(chars + i, j - i); _nodeWriter.WriteText(BACK_SLASH); _nodeWriter.WriteText(ch); i = j + 1; } else if ((ch >= HIGH_SURROGATE_START && (ch <= LOW_SURROGATE_END || ch >= MAX_CHAR)) || IsUnicodeNewlineCharacter(ch)) { _nodeWriter.WriteChars(chars + i, j - i); _nodeWriter.WriteText(BACK_SLASH); _nodeWriter.WriteText('u'); _nodeWriter.WriteText(string.Format(CultureInfo.InvariantCulture, "{0:x4}", (int)ch)); i = j + 1; } } if (i < j) { _nodeWriter.WriteChars(chars + i, j - i); } } } private void WriteIndent() { for (int i = 0; i < _indentLevel; i++) { _nodeWriter.WriteText(_indentChars); } } private void WriteNewLine() { _nodeWriter.WriteText(CARRIAGE_RETURN); _nodeWriter.WriteText(NEWLINE); } private void WriteJsonElementName(string localName) { WriteJsonQuote(); WriteEscapedJsonString(localName); WriteJsonQuote(); _nodeWriter.WriteText(JsonGlobals.NameValueSeparatorChar); if (_indent) { _nodeWriter.WriteText(WHITESPACE); } } private void WriteJsonQuote() { _nodeWriter.WriteText(JsonGlobals.QuoteChar); } private void WritePrimitiveValue(object value) { if (IsClosed) { ThrowClosed(); } if (value == null) { throw new ArgumentNullException("value"); } if (value is ulong) { WriteValue((ulong)value); } else if (value is string) { WriteValue((string)value); } else if (value is int) { WriteValue((int)value); } else if (value is long) { WriteValue((long)value); } else if (value is bool) { WriteValue((bool)value); } else if (value is double) { WriteValue((double)value); } else if (value is DateTime) { WriteValue((DateTime)value); } else if (value is float) { WriteValue((float)value); } else if (value is decimal) { WriteValue((decimal)value); } else if (value is XmlDictionaryString) { WriteValue((XmlDictionaryString)value); } else if (value is UniqueId) { WriteValue((UniqueId)value); } else if (value is Guid) { WriteValue((Guid)value); } else if (value is TimeSpan) { WriteValue((TimeSpan)value); } else if (value.GetType().IsArray) { throw new ArgumentException(SR.JsonNestedArraysNotSupported, "value"); } else { base.WriteValue(value); } } private void WriteServerTypeAttribute() { string value = _serverTypeValue; JsonDataType oldDataType = _dataType; NameState oldNameState = _nameState; WriteStartElement(JsonGlobals.serverTypeString); WriteValue(value); WriteEndElement(); _dataType = oldDataType; _nameState = oldNameState; _wroteServerTypeAttribute = true; } private void WriteValue(ulong value) { StartText(); _nodeWriter.WriteUInt64Text(value); } private void WriteValue(Array array) { // This method is called only if WriteValue(object) is called with an array // The contract for XmlWriter.WriteValue(object) requires that this object array be written out as a string. // E.g. WriteValue(new int[] { 1, 2, 3}) should be equivalent to WriteString("1 2 3"). JsonDataType oldDataType = _dataType; // Set attribute mode to String because WritePrimitiveValue might write numerical text. // Calls to methods that write numbers can't be mixed with calls that write quoted text unless the attribute mode is explictly string. _dataType = JsonDataType.String; StartText(); for (int i = 0; i < array.Length; i++) { if (i != 0) { _nodeWriter.WriteText(JsonGlobals.WhitespaceChar); } WritePrimitiveValue(array.GetValue(i)); } _dataType = oldDataType; } private class JsonNodeWriter : XmlUTF8NodeWriter { [SecurityCritical] internal unsafe void WriteChars(char* chars, int charCount) { base.UnsafeWriteUTF8Chars(chars, charCount); } } } }
// Copyright (c) 2006-2007 Frank Laub // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. The name of the author may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using OpenSSL; using System.IO; using System.Runtime.InteropServices; using OpenSSL.Core; using OpenSSL.Crypto; namespace OpenSSL.CLI { interface ICommand { void Execute(string[] args); } #region NullCommand class NullCommand : ICommand { private string name; public NullCommand(string name) { this.name = name; } #region ICommand Members public void Execute(string[] args) { Console.Error.WriteLine("{0}: {1}", this.name, string.Join(" ", args)); Console.Error.WriteLine("Not implemented yet!"); } #endregion } #endregion class Program { static void Main(string[] args) { Program program = new Program(); program.Run(args); } SortedDictionary<string, ICommand> std_cmds = new SortedDictionary<string, ICommand>(); SortedDictionary<string, ICommand> md_cmds = new SortedDictionary<string, ICommand>(); SortedDictionary<string, ICommand> cipher_cmds = new SortedDictionary<string, ICommand>(); void AddNullCommand(SortedDictionary<string, ICommand> map, string name) { map.Add(name, new NullCommand(name)); } Program() { CmdCipher cmdCipher = new CmdCipher(); CmdDigest cmdDigest = new CmdDigest(); this.std_cmds.Add("dh", new CmdDH()); this.std_cmds.Add("gendh", new CmdGenDH()); this.std_cmds.Add("rsa", new CmdRSA()); this.std_cmds.Add("genrsa", new CmdGenRSA()); this.std_cmds.Add("version", new CmdVersion()); this.std_cmds.Add("enc", cmdCipher); this.std_cmds.Add("dgst", cmdDigest); #region Standard Commands AddNullCommand(std_cmds, "asn1parse"); AddNullCommand(std_cmds, "ca"); AddNullCommand(std_cmds, "ciphers"); AddNullCommand(std_cmds, "crl"); AddNullCommand(std_cmds, "crl2pkcs7"); AddNullCommand(std_cmds, "dhparam"); AddNullCommand(std_cmds, "dsa"); AddNullCommand(std_cmds, "dsaparam"); AddNullCommand(std_cmds, "ec"); AddNullCommand(std_cmds, "ecparam"); AddNullCommand(std_cmds, "engine"); AddNullCommand(std_cmds, "errstr"); AddNullCommand(std_cmds, "gendsa"); AddNullCommand(std_cmds, "nseq"); AddNullCommand(std_cmds, "ocsp"); AddNullCommand(std_cmds, "passwd"); AddNullCommand(std_cmds, "pkcs12"); AddNullCommand(std_cmds, "pkcs7"); AddNullCommand(std_cmds, "pkcs8"); AddNullCommand(std_cmds, "prime"); AddNullCommand(std_cmds, "rand"); AddNullCommand(std_cmds, "req"); AddNullCommand(std_cmds, "rsautl"); AddNullCommand(std_cmds, "s_client"); AddNullCommand(std_cmds, "s_server"); AddNullCommand(std_cmds, "s_time"); AddNullCommand(std_cmds, "sess_id"); AddNullCommand(std_cmds, "smime"); AddNullCommand(std_cmds, "speed"); AddNullCommand(std_cmds, "spkac"); AddNullCommand(std_cmds, "verify"); AddNullCommand(std_cmds, "x509"); #endregion #region Message Digest commands foreach (string name in MessageDigest.AllNames) { this.md_cmds.Add(name, cmdDigest); } #endregion #region Cipher commands foreach (string name in Cipher.AllNames) { this.cipher_cmds.Add(name, cmdCipher); } #endregion } ICommand FindCommand(string name) { if (std_cmds.ContainsKey(name)) return std_cmds[name]; if (md_cmds.ContainsKey(name)) return md_cmds[name]; if (cipher_cmds.ContainsKey(name)) return cipher_cmds[name]; return null; } void PrintCommands(IEnumerable<string> cmds) { const int COLUMN_WIDTH = 15; int col = 0; foreach (string cmd in cmds) { if (cmd == cmd.ToUpper()) continue; if (cmd.Length > COLUMN_WIDTH) { if (col > 0) Console.Error.WriteLine(); Console.Error.Write(cmd.PadRight(COLUMN_WIDTH)); Console.Error.WriteLine(); col = 0; } else { Console.Error.Write(cmd.PadRight(COLUMN_WIDTH)); if (col++ == 4) { Console.Error.WriteLine(); col = 0; continue; } } } Console.Error.WriteLine(); } void Usage() { Console.Error.WriteLine("Standard commands"); PrintCommands(std_cmds.Keys); Console.Error.WriteLine(); Console.Error.WriteLine("Message Digest commands"); PrintCommands(md_cmds.Keys); Console.Error.WriteLine(); Console.Error.WriteLine("Cipher commands"); PrintCommands(cipher_cmds.Keys); } void Run(string[] args) { if (args.Length == 0) { Usage(); return; } ICommand cmd = FindCommand(args[0]); if (cmd == null) { Usage(); return; } cmd.Execute(args); } public static int OnGenerator(int p, int n, object arg) { TextWriter cout = Console.Error; switch (p) { case 0: cout.Write('.'); break; case 1: cout.Write('+'); break; case 2: cout.Write('*'); break; case 3: cout.WriteLine(); break; } return 1; } private static string ReadPassword() { Console.TreatControlCAsInput = true; StringBuilder sb = new StringBuilder(); while (true) { ConsoleKeyInfo key = Console.ReadKey(true); if (key.Key == ConsoleKey.Enter) break; if (key.Key == ConsoleKey.C && key.Modifiers == ConsoleModifiers.Control) { Console.Error.WriteLine(); throw new Exception("Cancelled"); } sb.Append(key.KeyChar); } Console.TreatControlCAsInput = false; return sb.ToString(); } public static string OnPassword(bool verify, object arg) { string passout = arg as string; if (!string.IsNullOrEmpty(passout)) return File.ReadAllText(passout); while (true) { Console.Error.Write("Enter pass phrase:"); string strPassword = ReadPassword(); Console.Error.WriteLine(); if (strPassword.Length == 0) continue; if (!verify) return strPassword; Console.Error.Write("Verifying - Enter pass phrase:"); string strVerify = ReadPassword(); Console.Error.WriteLine(); if (strPassword == strVerify) return strPassword; Console.Error.WriteLine("Passwords don't match, try again."); } } public static BIO GetInFile(string infile) { BIO bio; if (string.IsNullOrEmpty(infile)) { bio = BIO.MemoryBuffer(); Stream cin = Console.OpenStandardInput(); byte[] buf = new byte[1024]; while (true) { int len = cin.Read(buf, 0, buf.Length); if (len == 0) break; bio.Write(buf, len); } return bio; } return BIO.File(infile, "r"); } } }
/* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 Antlr.Runtime.Tree { using System.Collections.Generic; using IList = System.Collections.IList; /** <summary> * A generic list of elements tracked in an alternative to be used in * a -> rewrite rule. We need to subclass to fill in the next() method, * which returns either an AST node wrapped around a token payload or * an existing subtree. * </summary> * * <remarks> * Once you start next()ing, do not try to add more elements. It will * break the cursor tracking I believe. * * TODO: add mechanism to detect/puke on modification after reading from stream * </remarks> * * <see cref="RewriteRuleSubtreeStream"/> * <see cref="RewriteRuleTokenStream"/> */ [System.Serializable] public abstract class RewriteRuleElementStream { /** <summary> * Cursor 0..n-1. If singleElement!=null, cursor is 0 until you next(), * which bumps it to 1 meaning no more elements. * </summary> */ protected int cursor = 0; /** <summary>Track single elements w/o creating a list. Upon 2nd add, alloc list */ protected object singleElement; /** <summary>The list of tokens or subtrees we are tracking */ protected IList elements; /** <summary>Once a node / subtree has been used in a stream, it must be dup'd * from then on. Streams are reset after subrules so that the streams * can be reused in future subrules. So, reset must set a dirty bit. * If dirty, then next() always returns a dup.</summary> */ protected bool dirty = false; /** <summary>The element or stream description; usually has name of the token or * rule reference that this list tracks. Can include rulename too, but * the exception would track that info. */ protected string elementDescription; protected ITreeAdaptor adaptor; public RewriteRuleElementStream( ITreeAdaptor adaptor, string elementDescription ) { this.elementDescription = elementDescription; this.adaptor = adaptor; } /** <summary>Create a stream with one element</summary> */ public RewriteRuleElementStream( ITreeAdaptor adaptor, string elementDescription, object oneElement ) : this( adaptor, elementDescription ) { Add( oneElement ); } /** <summary>Create a stream, but feed off an existing list</summary> */ public RewriteRuleElementStream( ITreeAdaptor adaptor, string elementDescription, IList elements ) : this( adaptor, elementDescription ) { this.singleElement = null; this.elements = elements; } /** <summary> * Reset the condition of this stream so that it appears we have * not consumed any of its elements. Elements themselves are untouched. * Once we reset the stream, any future use will need duplicates. Set * the dirty bit. * </summary> */ public virtual void Reset() { cursor = 0; dirty = true; } public virtual void Add( object el ) { //System.out.println("add '"+elementDescription+"' is "+el); if ( el == null ) { return; } if ( elements != null ) { // if in list, just add elements.Add( el ); return; } if ( singleElement == null ) { // no elements yet, track w/o list singleElement = el; return; } // adding 2nd element, move to list elements = new List<object>( 5 ); elements.Add( singleElement ); singleElement = null; elements.Add( el ); } /** <summary> * Return the next element in the stream. If out of elements, throw * an exception unless size()==1. If size is 1, then return elements[0]. * Return a duplicate node/subtree if stream is out of elements and * size==1. If we've already used the element, dup (dirty bit set). * </summary> */ public virtual object NextTree() { int n = Count; if ( dirty || ( cursor >= n && n == 1 ) ) { // if out of elements and size is 1, dup object el = NextCore(); return Dup( el ); } // test size above then fetch object el2 = NextCore(); return el2; } /** <summary> * Do the work of getting the next element, making sure that it's * a tree node or subtree. Deal with the optimization of single- * element list versus list of size > 1. Throw an exception * if the stream is empty or we're out of elements and size>1. * protected so you can override in a subclass if necessary. * </summary> */ protected virtual object NextCore() { int n = Count; if ( n == 0 ) { throw new RewriteEmptyStreamException( elementDescription ); } if ( cursor >= n ) { // out of elements? if ( n == 1 ) { // if size is 1, it's ok; return and we'll dup return ToTree( singleElement ); } // out of elements and size was not 1, so we can't dup throw new RewriteCardinalityException( elementDescription ); } // we have elements if ( singleElement != null ) { cursor++; // move cursor even for single element list return ToTree( singleElement ); } // must have more than one in list, pull from elements object o = ToTree( elements[cursor] ); cursor++; return o; } /** <summary> * When constructing trees, sometimes we need to dup a token or AST * subtree. Dup'ing a token means just creating another AST node * around it. For trees, you must call the adaptor.dupTree() unless * the element is for a tree root; then it must be a node dup. * </summary> */ protected abstract object Dup( object el ); /** <summary> * Ensure stream emits trees; tokens must be converted to AST nodes. * AST nodes can be passed through unmolested. * </summary> */ protected virtual object ToTree( object el ) { return el; } public virtual bool HasNext { get { return ( singleElement != null && cursor < 1 ) || ( elements != null && cursor < elements.Count ); } } public virtual int Count { get { int n = 0; if ( singleElement != null ) { n = 1; } if ( elements != null ) { return elements.Count; } return n; } } public virtual string Description { get { return elementDescription; } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Web.HttpContextWrapper.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Web { public partial class HttpContextWrapper : HttpContextBase { #region Methods and constructors public override void AddError(Exception errorInfo) { } public override void ClearError() { } public override Object GetGlobalResourceObject(string classKey, string resourceKey) { return default(Object); } public override Object GetGlobalResourceObject(string classKey, string resourceKey, System.Globalization.CultureInfo culture) { return default(Object); } public override Object GetLocalResourceObject(string virtualPath, string resourceKey, System.Globalization.CultureInfo culture) { return default(Object); } public override Object GetLocalResourceObject(string virtualPath, string resourceKey) { return default(Object); } public override Object GetSection(string sectionName) { return default(Object); } public override Object GetService(Type serviceType) { return default(Object); } public HttpContextWrapper(HttpContext httpContext) { } public override void RemapHandler(IHttpHandler handler) { } public override void RewritePath(string path) { } public override void RewritePath(string path, bool rebaseClientPath) { } public override void RewritePath(string filePath, string pathInfo, string queryString) { } public override void RewritePath(string filePath, string pathInfo, string queryString, bool setClientFilePath) { } public override void SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior sessionStateBehavior) { } #endregion #region Properties and indexers public override Exception[] AllErrors { get { return default(Exception[]); } } public override HttpApplicationStateBase Application { get { return default(HttpApplicationStateBase); } } public override HttpApplication ApplicationInstance { get { return default(HttpApplication); } set { } } public override System.Web.Caching.Cache Cache { get { return default(System.Web.Caching.Cache); } } public override IHttpHandler CurrentHandler { get { return default(IHttpHandler); } } public override RequestNotification CurrentNotification { get { return default(RequestNotification); } } public override Exception Error { get { return default(Exception); } } public override IHttpHandler Handler { get { return default(IHttpHandler); } set { } } public override bool IsCustomErrorEnabled { get { return default(bool); } } public override bool IsDebuggingEnabled { get { return default(bool); } } public override bool IsPostNotification { get { return default(bool); } } public override System.Collections.IDictionary Items { get { return default(System.Collections.IDictionary); } } public override IHttpHandler PreviousHandler { get { return default(IHttpHandler); } } public override System.Web.Profile.ProfileBase Profile { get { return default(System.Web.Profile.ProfileBase); } } public override HttpRequestBase Request { get { return default(HttpRequestBase); } } public override HttpResponseBase Response { get { return default(HttpResponseBase); } } public override HttpServerUtilityBase Server { get { return default(HttpServerUtilityBase); } } public override HttpSessionStateBase Session { get { return default(HttpSessionStateBase); } } public override bool SkipAuthorization { get { return default(bool); } set { } } public override DateTime Timestamp { get { return default(DateTime); } } public override TraceContext Trace { get { return default(TraceContext); } } public override System.Security.Principal.IPrincipal User { get { return default(System.Security.Principal.IPrincipal); } set { } } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.OperatorOverloadsHaveNamedAlternatesAnalyzer, Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.OperatorOverloadsHaveNamedAlternatesFixer>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.OperatorOverloadsHaveNamedAlternatesAnalyzer, Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.OperatorOverloadsHaveNamedAlternatesFixer>; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests { public class OperatorOverloadsHaveNamedAlternatesTests { #region Boilerplate private static DiagnosticResult GetCA2225CSharpDefaultResultAt(int line, int column, string alternateName, string operatorName) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic(OperatorOverloadsHaveNamedAlternatesAnalyzer.DefaultRule) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(alternateName, operatorName); private static DiagnosticResult GetCA2225CSharpPropertyResultAt(int line, int column, string alternateName, string operatorName) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic(OperatorOverloadsHaveNamedAlternatesAnalyzer.PropertyRule) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(alternateName, operatorName); private static DiagnosticResult GetCA2225CSharpMultipleResultAt(int line, int column, string alternateName1, string alternateName2, string operatorName) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic(OperatorOverloadsHaveNamedAlternatesAnalyzer.MultipleRule) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(alternateName1, alternateName2, operatorName); private static DiagnosticResult GetCA2225CSharpVisibilityResultAt(int line, int column, string alternateName, string operatorName) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic(OperatorOverloadsHaveNamedAlternatesAnalyzer.VisibilityRule) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(alternateName, operatorName); private static DiagnosticResult GetCA2225BasicDefaultResultAt(int line, int column, string alternateName, string operatorName) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic(OperatorOverloadsHaveNamedAlternatesAnalyzer.DefaultRule) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(alternateName, operatorName); #endregion #region C# tests [Fact] public async Task HasAlternateMethod_CSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { public static C operator +(C left, C right) { return new C(); } public static C Add(C left, C right) { return new C(); } } "); } [Fact] public async Task HasMultipleAlternatePrimary_CSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { public static C operator %(C left, C right) { return new C(); } public static C Mod(C left, C right) { return new C(); } } "); } [Fact] public async Task HasMultipleAlternateSecondary_CSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { public static C operator %(C left, C right) { return new C(); } public static C Remainder(C left, C right) { return new C(); } } "); } [Fact] public async Task HasAppropriateConversionAlternate_CSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { public static implicit operator int(C item) { return 0; } public int ToInt32() { return 0; } } "); } [Fact, WorkItem(1717, "https://github.com/dotnet/roslyn-analyzers/issues/1717")] public async Task HasAppropriateConversionAlternate02_CSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Other { public int i {get; set;} public Other(int i) => this.i = i; } public class SomeClass { public int i {get; set;} public SomeClass(int i) => this.i = i; public static implicit operator SomeClass(Other b) => new SomeClass(b.i); public static SomeClass FromOther(Other b) => new SomeClass(b.i); } "); } [Fact] public async Task MissingAlternateMethod_CSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { public static C operator +(C left, C right) { return new C(); } } ", GetCA2225CSharpDefaultResultAt(4, 30, "Add", "op_Addition")); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task MissingAlternateMethod_CSharp_InternalAsync() { await VerifyCS.VerifyAnalyzerAsync(@" class C { public static C operator +(C left, C right) { return new C(); } } public class C2 { private class C3 { public static C3 operator +(C3 left, C3 right) { return new C3(); } } } "); } [Fact] public async Task MissingAlternateProperty_CSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { public static bool operator true(C item) { return true; } public static bool operator false(C item) { return false; } } ", GetCA2225CSharpPropertyResultAt(4, 33, "IsTrue", "op_True")); } [Fact] public async Task MissingMultipleAlternates_CSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { public static C operator %(C left, C right) { return new C(); } } ", GetCA2225CSharpMultipleResultAt(4, 30, "Mod", "Remainder", "op_Modulus")); } [Fact] public async Task ImproperAlternateMethodVisibility_CSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { public static C operator +(C left, C right) { return new C(); } protected static C Add(C left, C right) { return new C(); } } ", GetCA2225CSharpVisibilityResultAt(5, 24, "Add", "op_Addition")); } [Fact] public async Task ImproperAlternatePropertyVisibility_CSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { public static bool operator true(C item) { return true; } public static bool operator false(C item) { return false; } private bool IsTrue => true; } ", GetCA2225CSharpVisibilityResultAt(6, 18, "IsTrue", "op_True")); } [Fact] public async Task StructHasAlternateMethod_CSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" struct C { public static C operator +(C left, C right) { return new C(); } public static C Add(C left, C right) { return new C(); } } "); } [Fact] public async Task ImplicitCastToArrayAsync() { await VerifyCS.VerifyAnalyzerAsync( @" public struct MyStruct { public static implicit operator byte[](MyStruct myStruct) { return new byte[1]; } }", VerifyCS.Diagnostic(OperatorOverloadsHaveNamedAlternatesAnalyzer.MultipleRule).WithSpan(4, 37, 4, 43).WithArguments("ToByteArray", "FromMyStruct", "op_Implicit")); } [Fact] public async Task ExplicitCastToArrayAsync() { await VerifyCS.VerifyAnalyzerAsync( @" public struct MyStruct { public static explicit operator byte[](MyStruct myStruct) { return new byte[1]; } }", VerifyCS.Diagnostic(OperatorOverloadsHaveNamedAlternatesAnalyzer.MultipleRule).WithSpan(4, 37, 4, 43).WithArguments("ToByteArray", "FromMyStruct", "op_Explicit")); } [Fact] public async Task ImplicitCastToMultidimensionalArrayAsync() { await VerifyCS.VerifyAnalyzerAsync( @" public struct MyStruct { public static implicit operator byte[,](MyStruct myStruct) { return new byte[1,1]; } }", VerifyCS.Diagnostic(OperatorOverloadsHaveNamedAlternatesAnalyzer.MultipleRule).WithSpan(4, 37, 4, 44).WithArguments("ToByteArray", "FromMyStruct", "op_Implicit")); } [Fact] public async Task ExplicitCastToMultidimensionalArrayAsync() { await VerifyCS.VerifyAnalyzerAsync( @" public struct MyStruct { public static explicit operator byte[,](MyStruct myStruct) { return new byte[1,1]; } }", VerifyCS.Diagnostic(OperatorOverloadsHaveNamedAlternatesAnalyzer.MultipleRule).WithSpan(4, 37, 4, 44).WithArguments("ToByteArray", "FromMyStruct", "op_Explicit")); } [Fact] public async Task ImplicitCastToJaggedArrayAsync() { await VerifyCS.VerifyAnalyzerAsync( @" public struct MyStruct { public static implicit operator byte[][](MyStruct myStruct) { return new byte[1][]; } }", VerifyCS.Diagnostic(OperatorOverloadsHaveNamedAlternatesAnalyzer.MultipleRule).WithSpan(4, 37, 4, 45).WithArguments("ToByteArray", "FromMyStruct", "op_Implicit")); } [Fact] public async Task ExplicitCastToJaggedArrayAsync() { await VerifyCS.VerifyAnalyzerAsync( @" public struct MyStruct { public static explicit operator byte[][](MyStruct myStruct) { return new byte[1][]; } }", VerifyCS.Diagnostic(OperatorOverloadsHaveNamedAlternatesAnalyzer.MultipleRule).WithSpan(4, 37, 4, 45).WithArguments("ToByteArray", "FromMyStruct", "op_Explicit")); } #endregion // // Since the analyzer is symbol-based, only a few VB tests are added as a sanity check // #region VB tests [Fact] public async Task HasAlternateMethod_VisualBasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class C Public Shared Operator +(left As C, right As C) As C Return New C() End Operator Public Shared Function Add(left As C, right As C) As C Return New C() End Function End Class "); } [Fact] public async Task MissingAlternateMethod_VisualBasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class C Public Shared Operator +(left As C, right As C) As C Return New C() End Operator End Class ", GetCA2225BasicDefaultResultAt(3, 28, "Add", "op_Addition")); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task MissingAlternateMethod_VisualBasic_InternalAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Class C Public Shared Operator +(left As C, right As C) As C Return New C() End Operator End Class Public Class C2 Private Class C3 Public Shared Operator +(left As C3, right As C3) As C3 Return New C3() End Operator End Class End Class "); } [Fact] public async Task StructHasAlternateMethod_VisualBasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Structure C Public Shared Operator +(left As C, right As C) As C Return New C() End Operator Public Shared Function Add(left As C, right As C) As C Return New C() End Function End Structure "); } #endregion } }
/* * @author Valentin Simonov / http://va.lent.in/ * Based on http://pastebin.com/69QP1s45 */ #if TOUCHSCRIPT_DEBUG using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Rendering; #if UNITY_EDITOR using UnityEditor; using UnityEditor.Build; #endif namespace TouchScript.Debugging.GL { public class GLDebug : MonoBehaviour { public static readonly Color MULTIPLY = new Color(0, 0, 0, 0); public static readonly Vector2 DEFAULT_SCREEN_SPACE_SCALE = new Vector2(10, 10); private static GLDebug instance { get { if (!_instance && Application.isPlaying) { if (Camera.main) { _instance = Camera.main.gameObject.AddComponent<GLDebug>(); } else { var go = new GameObject("GLDebug"); var camera = go.AddComponent<Camera>(); camera.clearFlags = CameraClearFlags.Nothing; camera.depth = 9000; _instance = go.AddComponent<GLDebug>(); } } return _instance; } } public KeyCode ToggleKey; public bool DisplayLines = true; private static GLDebug _instance; private static int nextFigureId = 1; private Material materialDepthTest; private Material materialNoDepthTest; private Material materialMultiplyDepthTest; private Material materialMultiplyNoDepthTest; private Dictionary<int, Figure> figuresDepthTest; private Dictionary<int, Figure> figuresMultiplyDepthTest; private Dictionary<int, Figure> figuresNoDepthTest; private Dictionary<int, Figure> figuresMultiplyNoDepthTest; private Dictionary<int, Figure> figuresScreenSpace; private Dictionary<int, Figure> figuresMultiplyScreenSpace; private Dictionary<int, Figure> figuresTmp; private WaitForEndOfFrame wait; #region Public methods public static void RemoveFigure(int id) { instance.figuresDepthTest.Remove(id); instance.figuresNoDepthTest.Remove(id); instance.figuresScreenSpace.Remove(id); instance.figuresMultiplyDepthTest.Remove(id); instance.figuresMultiplyNoDepthTest.Remove(id); instance.figuresMultiplyScreenSpace.Remove(id); } #region Line public static int DrawLine(Vector3 start, Vector3 end, Color? color = null, float duration = 0, bool depthTest = false) { return DrawLine(null, start, end, color, duration, depthTest); } public static int DrawLine(int? id, Vector3 start, Vector3 end, Color? color = null, float duration = 0, bool depthTest = false) { return drawFigure(id, new List<Line>() {new Line(start, end)}, color ?? Color.white, duration, depthTest); } public static int DrawLineScreenSpace(Vector2 start, Vector2 end, Color? color = null, float duration = 0) { return DrawLineScreenSpace(null, start, end, color, duration); } public static int DrawLineScreenSpace(int? id, Vector2 start, Vector2 end, Color? color = null, float duration = 0) { return drawFigureScreenSpace(id, new List<Line>() {new Line(start, end)}, color ?? Color.white, duration); } #endregion #region Ray public static int DrawRay(Vector3 start, Vector3 dir, Color? color = null, float duration = 0, bool depthTest = false) { return DrawRay(null, start, dir, color, duration, depthTest); } public static int DrawRay(int? id, Vector3 start, Vector3 dir, Color? color = null, float duration = 0, bool depthTest = false) { if (dir == Vector3.zero) return 0; return DrawLine(start, start + dir, color, duration, depthTest); } #endregion #region Cross public static int DrawCross(Vector3 pos, Quaternion? rot = null, Vector3? scale = null, Color? color = null, float duration = 0, bool depthTest = false) { return DrawCross(null, Matrix4x4.TRS(pos, rot ?? Quaternion.identity, scale ?? Vector3.one), color, duration, depthTest); } public static int DrawCross(int? id, Vector3 pos, Quaternion? rot = null, Vector3? scale = null, Color? color = null, float duration = 0, bool depthTest = false) { return DrawCross(id, Matrix4x4.TRS(pos, rot ?? Quaternion.identity, scale ?? Vector3.one), color, duration, depthTest); } public static int DrawCross(Matrix4x4 matrix, Color? color = null, float duration = 0, bool depthTest = false) { return DrawCross(null, matrix, color, duration, depthTest); } public static int DrawCross(int? id, Matrix4x4 matrix, Color? color = null, float duration = 0, bool depthTest = false) { return drawFigure(id, createCrossLines(matrix), color ?? Color.white, duration, depthTest); } public static int DrawCrossScreenSpace(Vector2 pos, float rot = 0, Vector2? scale = null, Color? color = null, float duration = 0) { return DrawCrossScreenSpace(null, pos, rot, scale, color, duration); } public static int DrawCrossScreenSpace(int? id, Vector2 pos, float rot = 0, Vector2? scale = null, Color? color = null, float duration = 0) { return drawFigureScreenSpace(id, createScreenSpaceCrossLines(pos, rot, scale ?? DEFAULT_SCREEN_SPACE_SCALE), color ?? Color.white, duration); } #endregion #region Arrow public static int DrawArrow(Vector3 start, Vector3 end, float arrowHeadLength = 0.25f, float arrowHeadAngle = 20, Color? color = null, float duration = 0, bool depthTest = false) { return DrawArrow(null, start, end, arrowHeadLength, arrowHeadAngle, color, duration, depthTest); } public static int DrawArrow(int? id, Vector3 start, Vector3 end, float arrowHeadLength = 0.25f, float arrowHeadAngle = 20, Color? color = null, float duration = 0, bool depthTest = false) { if (start == end) return 0; return drawFigure(id, createArrowLines(start, end, arrowHeadLength, arrowHeadAngle), color ?? Color.white, duration, depthTest); } #endregion #region Plane with normal public static int DrawPlaneWithNormal(Vector3 pos, Vector3 normal, float scale = 1f, Color? color = null, float duration = 0, bool depthTest = false) { return DrawPlaneWithNormal(null, pos, normal, scale, color, duration, depthTest); } public static int DrawPlaneWithNormal(int? id, Vector3 pos, Vector3 normal, float scale = 1f, Color? color = null, float duration = 0, bool depthTest = false) { var lines = createArrowLines(pos, pos + normal); lines.AddRange(createCrossLines(Matrix4x4.TRS(pos, Quaternion.LookRotation(normal) * Quaternion.Euler(0, 0, 45f), Vector3.one))); lines.AddRange(createSquareLines(Matrix4x4.TRS(pos, Quaternion.FromToRotation(Vector3.up, normal), Vector3.one * scale))); return drawFigure(id, lines, color ?? Color.white, duration, depthTest); } #endregion #region Line with cross public static int DrawLineWithCross(Vector3 start, Vector3 end, float crossRelativePosition = 0.5f, Vector3? scale = null, Color? color = null, float duration = 0, bool depthTest = false) { return DrawLineWithCross(null, start, end, crossRelativePosition, scale, color, duration, depthTest); } public static int DrawLineWithCross(int? id, Vector3 start, Vector3 end, float crossRelativePosition = 0.5f, Vector3? scale = null, Color? color = null, float duration = 0, bool depthTest = false) { var lines = new List<Line>() {new Line(start, end)}; // TODO: Calculate cross rotation lines.AddRange(createCrossLines(Matrix4x4.TRS(Vector3.Lerp(start, end, crossRelativePosition), Quaternion.identity, scale ?? Vector3.one))); return drawFigure(id, lines, color ?? Color.white, duration, depthTest); } public static int DrawLineWithCrossScreenSpace(Vector2 start, Vector2 end, float crossRelativePosition, Vector2? scale = null, Color? color = null, float duration = 0) { return DrawLineWithCrossScreenSpace(null, start, end, crossRelativePosition, scale, color, duration); } public static int DrawLineWithCrossScreenSpace(int? id, Vector2 start, Vector2 end, float crossRelativePosition, Vector2? scale = null, Color? color = null, float duration = 0) { var lines = new List<Line>() {new Line(start, end)}; lines.AddRange(createScreenSpaceCrossLines(Vector2.Lerp(start, end, crossRelativePosition), Mathf.Atan2(end.y - start.y, end.x - start.x) * Mathf.Rad2Deg + 45f, scale ?? Vector2.one * 10)); return drawFigureScreenSpace(id, lines, color ?? Color.white, duration); } #endregion #region Square public static int DrawSquare(Vector3 pos, Quaternion? rot = null, Vector3? scale = null, Color? color = null, float duration = 0, bool depthTest = false) { return DrawSquare(null, pos, rot, scale, color, duration, depthTest); } public static int DrawSquare(int? id, Vector3 pos, Quaternion? rot = null, Vector3? scale = null, Color? color = null, float duration = 0, bool depthTest = false) { return DrawSquare(Matrix4x4.TRS(pos, rot ?? Quaternion.identity, scale ?? Vector3.one), color, duration, depthTest); } public static int DrawSquare(Matrix4x4 matrix, Color? color = null, float duration = 0, bool depthTest = false) { return DrawSquare(null, matrix, color, duration, depthTest); } public static int DrawSquare(int? id, Matrix4x4 matrix, Color? color = null, float duration = 0, bool depthTest = false) { return drawFigure(id, createSquareLines(matrix), color ?? Color.white, duration, depthTest); } public static int DrawSquareScreenSpace(Vector2 pos, float rot = 0, Vector2? scale = null, Color? color = null, float duration = 0) { return DrawSquareScreenSpace(null, pos, rot, scale, color, duration); } public static int DrawSquareScreenSpace(int? id, Vector2 pos, float rot = 0, Vector2? scale = null, Color? color = null, float duration = 0) { return drawFigureScreenSpace(id, createScreenSpaceSquareLines(pos, rot, scale ?? DEFAULT_SCREEN_SPACE_SCALE), color ?? Color.white, duration); } #endregion #region Cube public static int DrawCube(Vector3 pos, Quaternion? rot = null, Vector3? scale = null, Color? color = null, float duration = 0, bool depthTest = false) { return DrawCube(null, pos, rot, scale, color, duration, depthTest); } public static int DrawCube(int? id, Vector3 pos, Quaternion? rot = null, Vector3? scale = null, Color? color = null, float duration = 0, bool depthTest = false) { return DrawCube(Matrix4x4.TRS(pos, rot ?? Quaternion.identity, scale ?? Vector3.one), color, duration, depthTest); } public static int DrawCube(Matrix4x4 matrix, Color? color = null, float duration = 0, bool depthTest = false) { return DrawCube(null, matrix, color, duration, depthTest); } public static int DrawCube(int? id, Matrix4x4 matrix, Color? color = null, float duration = 0, bool depthTest = false) { return drawFigure(id, createCubeLines(matrix), color ?? Color.white, duration, depthTest); } #endregion #endregion #region Unity methods private void Awake() { if (_instance) { Destroy(this); return; } _instance = this; figuresDepthTest = new Dictionary<int, Figure>(); figuresNoDepthTest = new Dictionary<int, Figure>(); figuresScreenSpace = new Dictionary<int, Figure>(); figuresMultiplyDepthTest = new Dictionary<int, Figure>(); figuresMultiplyNoDepthTest = new Dictionary<int, Figure>(); figuresMultiplyScreenSpace = new Dictionary<int, Figure>(); figuresTmp = new Dictionary<int, Figure>(); wait = new WaitForEndOfFrame(); setMaterials(); } private void Update() { if (Input.GetKeyDown(ToggleKey)) DisplayLines = !DisplayLines; } private IEnumerator OnPostRender() { if (!DisplayLines) yield break; yield return wait; materialDepthTest.SetPass(0); UnityEngine.GL.Begin(UnityEngine.GL.LINES); figuresDepthTest = draw(figuresDepthTest); UnityEngine.GL.End(); materialMultiplyDepthTest.SetPass(0); UnityEngine.GL.Begin(UnityEngine.GL.LINES); figuresMultiplyDepthTest = draw(figuresMultiplyDepthTest); UnityEngine.GL.End(); materialNoDepthTest.SetPass(0); UnityEngine.GL.Begin(UnityEngine.GL.LINES); figuresNoDepthTest = draw(figuresNoDepthTest); UnityEngine.GL.End(); materialMultiplyNoDepthTest.SetPass(0); UnityEngine.GL.Begin(UnityEngine.GL.LINES); figuresMultiplyNoDepthTest = draw(figuresMultiplyNoDepthTest); UnityEngine.GL.End(); UnityEngine.GL.PushMatrix(); UnityEngine.GL.LoadPixelMatrix(); materialNoDepthTest.SetPass(0); UnityEngine.GL.Begin(UnityEngine.GL.LINES); figuresScreenSpace = draw(figuresScreenSpace); UnityEngine.GL.End(); materialMultiplyNoDepthTest.SetPass(0); UnityEngine.GL.Begin(UnityEngine.GL.LINES); figuresMultiplyScreenSpace = draw(figuresMultiplyScreenSpace); UnityEngine.GL.End(); UnityEngine.GL.PopMatrix(); } #endregion #region Private functions #region Misc private Dictionary<int, Figure> draw(Dictionary<int, Figure> figures) { figuresTmp.Clear(); var newFigures = figuresTmp; foreach (var key in figures.Keys) { var value = figures[key]; value.Duration = value.Draw(); if (value.Duration > 0) { newFigures[key] = value; } } figuresTmp = figures; return newFigures; } private void setMaterials() { materialDepthTest = new Material(Shader.Find("Hidden/DebugDepthTest")); materialNoDepthTest = new Material(Shader.Find("Hidden/DebugNoDepthTest")); materialMultiplyDepthTest = new Material(Shader.Find("Hidden/DebugMultiplyDepthTest")); materialMultiplyNoDepthTest = new Material(Shader.Find("Hidden/DebugMultiplyNoDepthTest")); materialDepthTest.hideFlags = HideFlags.HideAndDontSave; materialNoDepthTest.hideFlags = HideFlags.HideAndDontSave; materialMultiplyDepthTest.hideFlags = HideFlags.HideAndDontSave; materialMultiplyNoDepthTest.hideFlags = HideFlags.HideAndDontSave; } #endregion #region Figure creation private static int drawFigure(int? id, List<Line> lines, Color color, float duration = 0, bool depthTest = false) { if (duration == 0 && !instance.DisplayLines) return 0; int figureId; if (id.HasValue) { figureId = id.Value; RemoveFigure(figureId); } else { figureId = nextFigureId++; } if (depthTest) { if (color == MULTIPLY) instance.figuresMultiplyDepthTest.Add(figureId, new Figure(figureId, lines, Color.white, duration)); else instance.figuresDepthTest.Add(figureId, new Figure(figureId, lines, color, duration)); } else { if (color == MULTIPLY) instance.figuresMultiplyNoDepthTest.Add(figureId, new Figure(figureId, lines, Color.white, duration)); else instance.figuresNoDepthTest.Add(figureId, new Figure(figureId, lines, color, duration)); } return figureId; } private static int drawFigureScreenSpace(int? id, List<Line> lines, Color color, float duration = 0) { if (duration == 0 && !instance.DisplayLines) return 0; int figureId; if (id.HasValue) { figureId = id.Value; RemoveFigure(figureId); } else { figureId = nextFigureId++; } if (color == MULTIPLY) instance.figuresMultiplyScreenSpace.Add(figureId, new Figure(figureId, lines, Color.white, duration)); else instance.figuresScreenSpace.Add(figureId, new Figure(figureId, lines, color, duration)); return figureId; } #endregion #region Line helpers private static List<Line> createCrossLines(Matrix4x4 matrix) { Vector3 p_1 = matrix.MultiplyPoint3x4(new Vector3(-.5f, 0, 0)), p_2 = matrix.MultiplyPoint3x4(new Vector3(.5f, 0, 0)), p_3 = matrix.MultiplyPoint3x4(new Vector3(0, -.5f, 0)), p_4 = matrix.MultiplyPoint3x4(new Vector3(0, .5f, 0)); return new List<Line>() { new Line(p_1, p_2), new Line(p_3, p_4), }; } private static List<Line> createScreenSpaceCrossLines(Vector2 pos, float rot, Vector2 scale) { Vector2 p_1, p_2, p_3, p_4; float x = .5f * scale.x; float y = .5f * scale.y; if (rot == 0) { p_1 = new Vector2(-x, 0) + pos; p_2 = new Vector2(x, 0) + pos; p_3 = new Vector2(0, -y) + pos; p_4 = new Vector2(0, y) + pos; } else { var cos = Mathf.Cos(rot * Mathf.Deg2Rad); var sin = Mathf.Sin(rot * Mathf.Deg2Rad); p_1 = new Vector2(-x * cos, -x * sin) + pos; p_2 = new Vector2(x * cos, x * sin) + pos; p_3 = new Vector2(y * sin, -y * cos) + pos; p_4 = new Vector2(-y * sin, y * cos) + pos; } return new List<Line>() { new Line(p_1, p_2), new Line(p_3, p_4), }; } private static List<Line> createArrowLines(Vector3 start, Vector3 end, float arrowHeadLength = 0.25f, float arrowHeadAngle = 20) { var dir = end - start; Vector3 right = Quaternion.LookRotation(dir) * Quaternion.Euler(0, 180 + arrowHeadAngle, 0) * Vector3.forward; Vector3 left = Quaternion.LookRotation(dir) * Quaternion.Euler(0, 180 - arrowHeadAngle, 0) * Vector3.forward; return new List<Line>() { new Line(start, end), new Line(end, end + right * arrowHeadLength), new Line(end, end + left * arrowHeadLength) }; } private static List<Line> createSquareLines(Matrix4x4 matrix) { Vector3 p_1 = matrix.MultiplyPoint3x4(new Vector3(.5f, 0, .5f)), p_2 = matrix.MultiplyPoint3x4(new Vector3(.5f, 0, -.5f)), p_3 = matrix.MultiplyPoint3x4(new Vector3(-.5f, 0, -.5f)), p_4 = matrix.MultiplyPoint3x4(new Vector3(-.5f, 0, .5f)); return new List<Line>() { new Line(p_1, p_2), new Line(p_2, p_3), new Line(p_3, p_4), new Line(p_4, p_1) }; } private static List<Line> createScreenSpaceSquareLines(Vector2 pos, float rot, Vector2 scale) { Vector2 p_1, p_2, p_3, p_4; float x = .5f * scale.x; float y = .5f * scale.y; if (rot == 0) { p_1 = new Vector2(x, y) + pos; p_2 = new Vector2(x, -y) + pos; p_3 = new Vector2(-x, -y) + pos; p_4 = new Vector2(-x, y) + pos; } else { var cos = Mathf.Cos(rot * Mathf.Deg2Rad); var sin = Mathf.Sin(rot * Mathf.Deg2Rad); p_1 = new Vector2(x * cos - y * sin, x * sin + y * cos) + pos; p_2 = new Vector2(x * cos + y * sin, x * sin - y * cos) + pos; p_3 = new Vector2(-x * cos + y * sin, -x * sin - y * cos) + pos; p_4 = new Vector2(-x * cos - y * sin, -x * sin + y * cos) + pos; } return new List<Line>() { new Line(p_1, p_2), new Line(p_2, p_3), new Line(p_3, p_4), new Line(p_4, p_1) }; } private static List<Line> createCubeLines(Matrix4x4 matrix) { Vector3 down_1 = matrix.MultiplyPoint3x4(new Vector3(.5f, -.5f, .5f)), down_2 = matrix.MultiplyPoint3x4(new Vector3(.5f, -.5f, -.5f)), down_3 = matrix.MultiplyPoint3x4(new Vector3(-.5f, -.5f, -.5f)), down_4 = matrix.MultiplyPoint3x4(new Vector3(-.5f, -.5f, .5f)), up_1 = matrix.MultiplyPoint3x4(new Vector3(.5f, .5f, .5f)), up_2 = matrix.MultiplyPoint3x4(new Vector3(.5f, .5f, -.5f)), up_3 = matrix.MultiplyPoint3x4(new Vector3(-.5f, .5f, -.5f)), up_4 = matrix.MultiplyPoint3x4(new Vector3(-.5f, .5f, .5f)); return new List<Line>() { new Line(down_1, down_2), new Line(down_2, down_3), new Line(down_3, down_4), new Line(down_4, down_1), new Line(down_1, up_1), new Line(down_2, up_2), new Line(down_3, up_3), new Line(down_4, up_4), new Line(up_1, up_2), new Line(up_2, up_3), new Line(up_3, up_4), new Line(up_4, up_1) }; } #endregion #endregion #region Structs private struct Figure { public int Id; public Color Color; public float Duration; public List<Line> Lines; public Figure(int id, List<Line> lines, Color color, float duration) { Id = id; Color = color; Duration = duration; Lines = lines; } public float Draw() { UnityEngine.GL.Color(Color); for (var i = 0; i < Lines.Count; i++) { Lines[i].Draw(); } return Duration - Time.unscaledDeltaTime; } } private struct Line { public Vector3 start; public Vector3 end; public Line(Vector3 start, Vector3 end) { this.start = start; this.end = end; } public void Draw() { UnityEngine.GL.Vertex(start); UnityEngine.GL.Vertex(end); } } #endregion } #if UNITY_EDITOR internal class BuildProcessor : IPreprocessBuild, IPostprocessBuild { public int callbackOrder { get { return 0; } } public void OnPreprocessBuild(BuildTarget target, string path) { // Add hidden shaders to the build. var objs = Resources.FindObjectsOfTypeAll<GraphicsSettings>(); var graphicsSettings = new SerializedObject(objs[0]); var alwaysIncludedShaders = graphicsSettings.FindProperty("m_AlwaysIncludedShaders"); insertShaderInProperty(alwaysIncludedShaders, "Hidden/DebugDepthTest"); insertShaderInProperty(alwaysIncludedShaders, "Hidden/DebugNoDepthTest"); insertShaderInProperty(alwaysIncludedShaders, "Hidden/DebugMultiplyDepthTest"); insertShaderInProperty(alwaysIncludedShaders, "Hidden/DebugMultiplyNoDepthTest"); graphicsSettings.ApplyModifiedProperties(); } public void OnPostprocessBuild(BuildTarget target, string path) { // Reverd GraphicsSettings. var objs = Resources.FindObjectsOfTypeAll<GraphicsSettings>(); var graphicsSettings = new SerializedObject(objs[0]); var alwaysIncludedShaders = graphicsSettings.FindProperty("m_AlwaysIncludedShaders"); alwaysIncludedShaders.arraySize = alwaysIncludedShaders.arraySize - 4; graphicsSettings.ApplyModifiedProperties(); } private void insertShaderInProperty(SerializedProperty prop, string shaderName) { var index = prop.arraySize; prop.InsertArrayElementAtIndex(index); prop.GetArrayElementAtIndex(index).objectReferenceValue = Shader.Find(shaderName); } } #endif } #endif
// ByteFX.Data data access components for .Net // Copyright (C) 2002-2003 ByteFX, Inc. // // 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA using System; using System.Data; using System.Collections; namespace ByteFX.Data.MySqlClient { /// <summary> /// Provides a means of reading a forward-only stream of rows from a MySQL database. This class cannot be inherited. /// </summary> /// <include file='docs/MySqlDataReader.xml' path='MyDocs/MyMembers[@name="Class"]/*'/> public sealed class MySqlDataReader : MarshalByRefObject, IEnumerable, IDataReader, IDisposable, IDataRecord { // The DataReader should always be open when returned to the user. private bool isOpen = true; // Keep track of the results and position // within the resultset (starts prior to first record). private MySqlField[] _fields; private CommandBehavior commandBehavior; private MySqlCommand command; private bool canRead; private bool hasRows; private CommandResult currentResult; /* * Keep track of the connection in order to implement the * CommandBehavior.CloseConnection flag. A null reference means * normal behavior (do not automatically close). */ private MySqlConnection connection = null; /* * Because the user should not be able to directly create a * DataReader object, the constructors are * marked as internal. */ internal MySqlDataReader( MySqlCommand cmd, CommandBehavior behavior) { this.command = cmd; connection = (MySqlConnection)command.Connection; commandBehavior = behavior; } /// <summary> /// Gets a value indicating the depth of nesting for the current row. This method is not /// supported currently and always returns 0. /// </summary> public int Depth { get { return 0; } } /// <summary> /// Gets a value indicating whether the data reader is closed. /// </summary> public bool IsClosed { get { return ! isOpen; } } void IDisposable.Dispose() { if (isOpen) Close(); } /// <summary> /// Gets the number of rows changed, inserted, or deleted by execution of the SQL statement. /// </summary> public int RecordsAffected { // RecordsAffected returns the number of rows affected in batch // statments from insert/delete/update statments. This property // is not completely accurate until .Close() has been called. get { return command.UpdateCount; } } /// <summary> /// Gets a value indicating whether the MySqlDataReader contains one or more rows. /// </summary> public bool HasRows { get { return hasRows; } } /// <summary> /// Closes the MySqlDataReader object. /// </summary> public void Close() { if (! isOpen) return; // finish any current command if (currentResult != null) currentResult.Clear(); command.ExecuteBatch(false); connection.Reader = null; if (0 != (commandBehavior & CommandBehavior.CloseConnection)) connection.Close(); isOpen = false; } /// <summary> /// Gets the number of columns in the current row. /// </summary> public int FieldCount { // Return the count of the number of columns, which in // this case is the size of the column metadata // array. get { if (_fields != null) return _fields.Length; return 0; } } /// <summary> /// Overloaded. Gets the value of a column in its native format. /// In C#, this property is the indexer for the MySqlDataReader class. /// </summary> public object this [ int i ] { get { return this.GetValue(i); } } /// <summary> /// Gets the value of a column in its native format. /// [C#] In C#, this property is the indexer for the MySqlDataReader class. /// </summary> public object this [ String name ] { // Look up the ordinal and return // the value at that position. get { return this[GetOrdinal(name)]; } } private MySqlField GetField(int i) { if (i >= _fields.Length) throw new IndexOutOfRangeException(); return _fields[i]; } #region TypeSafe Accessors /// <summary> /// Gets the value of the specified column as a Boolean. /// </summary> /// <param name="i"></param> /// <returns></returns> public bool GetBoolean(int i) { return Convert.ToBoolean(GetValue(i)); } /// <summary> /// Gets the value of the specified column as a byte. /// </summary> /// <param name="i"></param> /// <returns></returns> public byte GetByte(int i) { return Convert.ToByte(GetValue(i)); } /// <summary> /// Reads a stream of bytes from the specified column offset into the buffer an array starting at the given buffer offset. /// </summary> /// <param name="i">The zero-based column ordinal. </param> /// <param name="dataIndex">The index within the field from which to begin the read operation. </param> /// <param name="buffer">The buffer into which to read the stream of bytes. </param> /// <param name="bufferIndex">The index for buffer to begin the read operation. </param> /// <param name="length">The maximum length to copy into the buffer. </param> /// <returns>The actual number of bytes read.</returns> public long GetBytes(int i, long dataIndex, byte[] buffer, int bufferIndex, int length) { if (i >= _fields.Length) throw new IndexOutOfRangeException(); long bufLen = _fields[i].BufferLength; if (buffer == null) return bufLen; if (bufferIndex >= buffer.Length || bufferIndex < 0) throw new IndexOutOfRangeException("Buffer index must be a valid index in buffer"); if (buffer.Length < (bufferIndex + length)) throw new ArgumentException( "Buffer is not large enough to hold the requested data" ); if (dataIndex < 0 || dataIndex >= bufLen ) throw new IndexOutOfRangeException( "Data index must be a valid index in the field" ); byte[] bytes = _fields[i].Buffer; long fieldIndex = _fields[i].BufferIndex; // adjust the length so we don't run off the end if ( bufLen < (dataIndex+length)) { length = (int)((long)bytes.Length - dataIndex); } for (long x=0; x < length; x++) { buffer[bufferIndex+x] = bytes[fieldIndex+dataIndex+x]; } return length; } /// <summary> /// Gets the value of the specified column as a single character. /// </summary> /// <param name="i"></param> /// <returns></returns> public char GetChar(int i) { return Convert.ToChar(GetValue(i)); } /// <summary> /// Reads a stream of characters from the specified column offset into the buffer as an array starting at the given buffer offset. /// </summary> /// <param name="i"></param> /// <param name="fieldOffset"></param> /// <param name="buffer"></param> /// <param name="bufferoffset"></param> /// <param name="length"></param> /// <returns></returns> public long GetChars(int i, long fieldOffset, char[] buffer, int bufferoffset, int length) { if (i >= _fields.Length) throw new IndexOutOfRangeException(); // retrieve the bytes of the column long bytesize = GetBytes(i, 0, null, 0, 0); byte[] bytes = new byte[bytesize]; GetBytes(i, 0, bytes, 0, (int)bytesize); char[] chars = System.Text.Encoding.UTF8.GetChars(bytes, 0, (int)bytesize); if (buffer == null) return chars.Length; // adjust the length so we don't run off the end if (chars.Length < (fieldOffset+length)) { length = (int)(chars.Length - fieldOffset); } for (int x=0; x < length; x++) { buffer[bufferoffset+x] = chars[fieldOffset+x]; } return length; } /// <summary> /// Gets the name of the source data type. /// </summary> /// <param name="i"></param> /// <returns></returns> public String GetDataTypeName(int i) { if (! isOpen) throw new Exception("No current query in data reader"); if (i >= _fields.Length) throw new IndexOutOfRangeException(); // return the name of the type used on the backend return _fields[i].GetFieldTypeName(); } /// <summary> /// Gets the value of the specified column as a DateTime object. /// </summary> /// <param name="i"></param> /// <returns></returns> public DateTime GetDateTime(int i) { return Convert.ToDateTime(GetValue(i)); } /// <summary> /// Gets the value of the specified column as a Decimal object. /// </summary> /// <param name="i"></param> /// <returns></returns> public Decimal GetDecimal(int i) { return Convert.ToDecimal(GetValue(i)); } /// <summary> /// Gets the value of the specified column as a double-precision floating point number. /// </summary> /// <param name="i"></param> /// <returns></returns> public double GetDouble(int i) { return Convert.ToDouble(GetValue(i)); } /// <summary> /// Gets the Type that is the data type of the object. /// </summary> /// <param name="i"></param> /// <returns></returns> public Type GetFieldType(int i) { if (! isOpen) throw new Exception("No current query in data reader"); if (i >= _fields.Length) throw new IndexOutOfRangeException(); return _fields[i].GetFieldType(); } /// <summary> /// Gets the value of the specified column as a single-precision floating point number. /// </summary> /// <param name="i"></param> /// <returns></returns> public float GetFloat(int i) { return Convert.ToSingle(GetValue(i)); } /// <summary> /// Gets the value of the specified column as a globally-unique identifier (GUID). /// This is currently not supported. /// </summary> /// <param name="i"></param> /// <returns></returns> public Guid GetGuid(int i) { return new Guid( GetString(i) ); } /// <summary> /// Gets the value of the specified column as a 16-bit signed integer. /// </summary> /// <param name="i"></param> /// <returns></returns> public Int16 GetInt16(int i) { return Convert.ToInt16(GetValue(i)); } /// <summary> /// Gets the value of the specified column as a 32-bit signed integer. /// </summary> /// <param name="i"></param> /// <returns></returns> public Int32 GetInt32(int i) { return Convert.ToInt32(GetValue(i)); } /// <summary> /// Gets the value of the specified column as a 64-bit signed integer. /// </summary> /// <param name="i"></param> /// <returns></returns> public Int64 GetInt64(int i) { return Convert.ToInt64(GetValue(i)); } /// <summary> /// Gets the name of the specified column. /// </summary> /// <param name="i"></param> /// <returns></returns> public String GetName(int i) { return _fields[i].ColumnName; } /// <summary> /// Gets the column ordinal, given the name of the column. /// </summary> /// <param name="name"></param> /// <returns></returns> public int GetOrdinal(string name) { if (! isOpen) throw new Exception("No current query in data reader"); for (int i=0; i < _fields.Length; i ++) { if (_fields[i].ColumnName.ToLower().Equals(name.ToLower())) return i; } // Throw an exception if the ordinal cannot be found. throw new IndexOutOfRangeException("Could not find specified column in results"); } /// <summary> /// Returns a DataTable that describes the column metadata of the MySqlDataReader. /// </summary> /// <returns></returns> public DataTable GetSchemaTable() { // Only Results from SQL SELECT Queries // get a DataTable for schema of the result // otherwise, DataTable is null reference if (_fields.Length == 0) return null; DataTable dataTableSchema = new DataTable ("SchemaTable"); dataTableSchema.Columns.Add ("ColumnName", typeof (string)); dataTableSchema.Columns.Add ("ColumnOrdinal", typeof (int)); dataTableSchema.Columns.Add ("ColumnSize", typeof (int)); dataTableSchema.Columns.Add ("NumericPrecision", typeof (int)); dataTableSchema.Columns.Add ("NumericScale", typeof (int)); dataTableSchema.Columns.Add ("IsUnique", typeof (bool)); dataTableSchema.Columns.Add ("IsKey", typeof (bool)); DataColumn dc = dataTableSchema.Columns["IsKey"]; dc.AllowDBNull = true; // IsKey can have a DBNull dataTableSchema.Columns.Add ("BaseCatalogName", typeof (string)); dataTableSchema.Columns.Add ("BaseColumnName", typeof (string)); dataTableSchema.Columns.Add ("BaseSchemaName", typeof (string)); dataTableSchema.Columns.Add ("BaseTableName", typeof (string)); dataTableSchema.Columns.Add ("DataType", typeof(Type)); dataTableSchema.Columns.Add ("AllowDBNull", typeof (bool)); dataTableSchema.Columns.Add ("ProviderType", typeof (int)); dataTableSchema.Columns.Add ("IsAliased", typeof (bool)); dataTableSchema.Columns.Add ("IsExpression", typeof (bool)); dataTableSchema.Columns.Add ("IsIdentity", typeof (bool)); dataTableSchema.Columns.Add ("IsAutoIncrement", typeof (bool)); dataTableSchema.Columns.Add ("IsRowVersion", typeof (bool)); dataTableSchema.Columns.Add ("IsHidden", typeof (bool)); dataTableSchema.Columns.Add ("IsLong", typeof (bool)); dataTableSchema.Columns.Add ("IsReadOnly", typeof (bool)); int ord = 1; foreach (MySqlField f in _fields) { DataRow r = dataTableSchema.NewRow(); r["ColumnName"] = f.ColumnName; r["ColumnOrdinal"] = ord++; r["ColumnSize"] = f.ColumnLength; int prec = f.NumericPrecision; int pscale = f.NumericScale; if (prec != -1) r["NumericPrecision"] = (short)prec; if (pscale != -1) r["NumericScale"] = (short)pscale; r["DataType"] = f.GetFieldType(); r["ProviderType"] = (int)f.Type; r["IsLong"] = f.IsBlob() && f.ColumnLength > 255; r["AllowDBNull"] = f.AllowsNull(); r["IsReadOnly"] = false; r["IsRowVersion"] = false; r["IsUnique"] = f.IsUnique(); r["IsKey"] = f.IsPrimaryKey(); r["IsAutoIncrement"] = f.IsAutoIncrement(); r["BaseSchemaName"] = null; r["BaseCatalogName"] = null; r["BaseTableName"] = f.TableName; r["BaseColumnName"] = f.ColumnName; dataTableSchema.Rows.Add( r ); } return dataTableSchema; } /// <summary> /// Gets the value of the specified column as a string. /// </summary> /// <param name="i"></param> /// <returns></returns> public String GetString(int i) { return GetValue(i).ToString(); } /// <summary> /// Gets the value of the specified column in its native format. /// </summary> /// <param name="i"></param> /// <returns></returns> public object GetValue(int i) { if (! isOpen) throw new Exception("No current query in data reader"); if (i >= _fields.Length) throw new IndexOutOfRangeException(); return _fields[i].GetValue(); } /// <summary> /// Gets all attribute columns in the collection for the current row. /// </summary> /// <param name="values"></param> /// <returns></returns> public int GetValues(object[] values) { for (int i=0; i < _fields.Length; i ++) { values[i] = GetValue(i); } return 0; } /// <summary> /// Gets the value of the specified column as a 16-bit unsigned integer. /// </summary> /// <param name="i"></param> /// <returns></returns> public UInt16 GetUInt16( int i ) { return Convert.ToUInt16(GetValue(i)); } /// <summary> /// Gets the value of the specified column as a 32-bit unsigned integer. /// </summary> /// <param name="i"></param> /// <returns></returns> public UInt32 GetUInt32( int i ) { return Convert.ToUInt32(GetValue(i)); } /// <summary> /// Gets the value of the specified column as a 64-bit unsigned integer. /// </summary> /// <param name="i"></param> /// <returns></returns> public UInt64 GetUInt64( int i ) { return Convert.ToUInt64(GetValue(i)); } #endregion IDataReader IDataRecord.GetData(int i) { throw new NotSupportedException("GetData not supported."); } /// <summary> /// Gets a value indicating whether the column contains non-existent or missing values. /// </summary> /// <param name="i"></param> /// <returns></returns> public bool IsDBNull(int i) { return DBNull.Value == GetValue(i); } /// <summary> /// Advances the data reader to the next result, when reading the results of batch SQL statements. /// </summary> /// <returns></returns> public bool NextResult() { if (! isOpen) throw new MySqlException("Invalid attempt to NextResult when reader is closed."); // clear any rows that have not been read from the last rowset if (currentResult != null) currentResult.Clear(); // tell our command to continue execution of the SQL batch until it its // another resultset currentResult = command.ExecuteBatch(true); // if there was no more resultsets, then signal done if (currentResult == null) { canRead = false; return false; } // When executing query statements, the result byte that is returned // from MySql is the column count. That is why we reference the LastResult // property here to dimension our field array connection.SetState( ConnectionState.Fetching ); _fields = new MySqlField[ currentResult.ColumnCount ]; for (int x=0; x < _fields.Length; x++) _fields[x] = currentResult.GetField(); hasRows = currentResult.CheckForRows(); canRead = hasRows; connection.SetState( ConnectionState.Open ); return true; } /// <summary> /// Advances the MySqlDataReader to the next record. /// </summary> /// <returns></returns> public bool Read() { if (! isOpen) throw new MySqlException("Invalid attempt to Read when reader is closed."); if (! canRead) return false; Driver driver = connection.InternalConnection.Driver; connection.SetState( ConnectionState.Fetching ); try { if (! currentResult.ReadDataRow()) { canRead = false; return false; } for (int col=0; col < _fields.Length; col++) { byte[] buf = currentResult.GetFieldBuffer(); int index = currentResult.GetFieldIndex(); long len = currentResult.GetFieldLength(); _fields[col].SetValueData( buf, index, len, driver.Version ); currentResult.NextField(); } } catch (Exception ex) { System.Diagnostics.Trace.WriteLine("MySql error: " + ex.Message); throw ex; } finally { connection.SetState( ConnectionState.Open ); } return true; } /* * Implementation specific methods. */ private int _cultureAwareCompare(string strA, string strB) { // return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); return 0; } #region IEnumerator IEnumerator IEnumerable.GetEnumerator() { return new System.Data.Common.DbEnumerator(this); } #endregion } }
// // BaseWidgetAccessible.cs // // Author: // Gabriel Burt <[email protected]> // // Copyright (C) 2009 Novell, Inc. // // 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.Linq; using System.Collections.Generic; using Atk; namespace Hyena.Gui { public class BaseWidgetAccessible : Gtk.Accessible, Atk.ComponentImplementor { private Gtk.Widget widget; private uint focus_id = 0; private Dictionary<uint, Atk.FocusHandler> focus_handlers = new Dictionary<uint, Atk.FocusHandler> (); public BaseWidgetAccessible (Gtk.Widget widget) { this.widget = widget; widget.SizeAllocated += OnAllocated; widget.Mapped += OnMap; widget.Unmapped += OnMap; widget.FocusInEvent += OnFocus; widget.FocusOutEvent += OnFocus; widget.AddNotification ("sensitive", (o, a) => NotifyStateChange (StateType.Sensitive, widget.Sensitive)); widget.AddNotification ("visible", (o, a) => NotifyStateChange (StateType.Visible, widget.Visible)); } public virtual new Atk.Layer Layer { get { return Layer.Widget; } } protected override Atk.StateSet OnRefStateSet () { var s = base.OnRefStateSet (); AddStateIf (s, widget.CanFocus, StateType.Focusable); AddStateIf (s, widget.HasFocus, StateType.Focused); AddStateIf (s, widget.Sensitive, StateType.Sensitive); AddStateIf (s, widget.Sensitive, StateType.Enabled); AddStateIf (s, widget.HasDefault, StateType.Default); AddStateIf (s, widget.Visible, StateType.Visible); AddStateIf (s, widget.Visible && widget.IsMapped, StateType.Showing); return s; } private static void AddStateIf (StateSet s, bool condition, StateType t) { if (condition) { s.AddState (t); } } private void OnFocus (object o, EventArgs args) { NotifyStateChange (StateType.Focused, widget.HasFocus); var handler = FocusChanged; if (handler != null) { handler (this, widget.HasFocus); } } private void OnMap (object o, EventArgs args) { NotifyStateChange (StateType.Showing, widget.Visible && widget.IsMapped); } private void OnAllocated (object o, EventArgs args) { var a = widget.Allocation; var bounds = new Atk.Rectangle () { X = a.X, Y = a.Y, Width = a.Width, Height = a.Height }; GLib.Signal.Emit (this, "bounds_changed", bounds); /*var handler = BoundsChanged; if (handler != null) { handler (this, new BoundsChangedArgs () { Args = new object [] { bounds } }); }*/ } private event FocusHandler FocusChanged; #region Atk.Component public uint AddFocusHandler (Atk.FocusHandler handler) { if (!focus_handlers.ContainsValue (handler)) { FocusChanged += handler; focus_handlers[++focus_id] = handler; return focus_id; } return 0; } public bool Contains (int x, int y, Atk.CoordType coordType) { int x_extents, y_extents, w, h; GetExtents (out x_extents, out y_extents, out w, out h, coordType); Gdk.Rectangle extents = new Gdk.Rectangle (x_extents, y_extents, w, h); return extents.Contains (x, y); } public virtual Atk.Object RefAccessibleAtPoint (int x, int y, Atk.CoordType coordType) { return new NoOpObject (widget); } public void GetExtents (out int x, out int y, out int w, out int h, Atk.CoordType coordType) { w = widget.Allocation.Width; h = widget.Allocation.Height; GetPosition (out x, out y, coordType); } public void GetPosition (out int x, out int y, Atk.CoordType coordType) { Gdk.Window window = null; if (!widget.IsDrawable) { x = y = Int32.MinValue; return; } if (widget.Parent != null) { x = widget.Allocation.X; y = widget.Allocation.Y; window = widget.ParentWindow; } else { x = 0; y = 0; window = widget.GdkWindow; } int x_window, y_window; window.GetOrigin (out x_window, out y_window); x += x_window; y += y_window; if (coordType == Atk.CoordType.Window) { window = widget.GdkWindow.Toplevel; int x_toplevel, y_toplevel; window.GetOrigin (out x_toplevel, out y_toplevel); x -= x_toplevel; y -= y_toplevel; } } public void GetSize (out int w, out int h) { w = widget.Allocation.Width; h = widget.Allocation.Height; } public bool GrabFocus () { if (!widget.CanFocus) { return false; } widget.GrabFocus (); var toplevel_window = widget.Toplevel as Gtk.Window; if (toplevel_window != null) { toplevel_window.Present (); } return true; } public void RemoveFocusHandler (uint handlerId) { if (focus_handlers.ContainsKey (handlerId)) { FocusChanged -= focus_handlers[handlerId]; focus_handlers.Remove (handlerId); } } public bool SetExtents (int x, int y, int w, int h, Atk.CoordType coordType) { return SetSizeAndPosition (x, y, w, h, coordType, true); } public bool SetPosition (int x, int y, Atk.CoordType coordType) { return SetSizeAndPosition (x, y, 0, 0, coordType, false); } private bool SetSizeAndPosition (int x, int y, int w, int h, Atk.CoordType coordType, bool setSize) { if (!widget.IsTopLevel) { return false; } if (coordType == CoordType.Window) { int x_off, y_off; widget.GdkWindow.GetOrigin (out x_off, out y_off); x += x_off; y += y_off; if (x < 0 || y < 0) { return false; } } #pragma warning disable 0612 widget.SetUposition (x, y); #pragma warning restore 0612 if (setSize) { widget.SetSizeRequest (w, h); } return true; } public bool SetSize (int w, int h) { if (widget.IsTopLevel) { widget.SetSizeRequest (w, h); return true; } else { return false; } } public double Alpha { get { return 1.0; } } #endregion Atk.Component } }
namespace Coop_Listing_Site.Migrations { using System; using System.Data.Entity.Migrations; public partial class Initial_Migration : DbMigration { public override void Up() { CreateTable( "dbo.Application", c => new { ApplicationId = c.Int(nullable: false, identity: true), Resume = c.Binary(), CoverLetter = c.Binary(), DriverLicense = c.Binary(), Other = c.Binary(), Message = c.String(nullable: false), FileName_Resume = c.String(), FileName_CoverLetter = c.String(), FileName_DriverLicense = c.String(), FileName_Other = c.String(), Resume_ContentType = c.String(), CoverLetter_ContentType = c.String(), DriverLicense_ContentType = c.String(), Other_ContentType = c.String(), Opportunity_OpportunityID = c.Int(), User_Id = c.String(maxLength: 128), }) .PrimaryKey(t => t.ApplicationId) .ForeignKey("dbo.Opportunity", t => t.Opportunity_OpportunityID) .ForeignKey("dbo.AspNetUsers", t => t.User_Id) .Index(t => t.Opportunity_OpportunityID) .Index(t => t.User_Id); CreateTable( "dbo.Opportunity", c => new { OpportunityID = c.Int(nullable: false, identity: true), PDF = c.Int(nullable: false), UserID = c.Int(nullable: false), CompanyID = c.Int(nullable: false), CompanyName = c.String(), ContactName = c.String(), ContactNumber = c.String(), ContactEmail = c.String(), Location = c.String(), CompanyWebsite = c.String(), AboutCompany = c.String(), AboutDepartment = c.String(), CoopPositionTitle = c.String(), CoopPositionDuties = c.String(), Qualifications = c.String(), GPA = c.Double(nullable: false), Paid = c.Boolean(nullable: false), Wage = c.String(), Stippened = c.Boolean(nullable: false), Amount = c.String(), UnPaid = c.Boolean(nullable: false), Duration = c.String(), OpeningsAvailable = c.Int(nullable: false), TermAvailable = c.String(), DepartmentID = c.Int(nullable: false), }) .PrimaryKey(t => t.OpportunityID); CreateTable( "dbo.AspNetUsers", c => new { Id = c.String(nullable: false, maxLength: 128), FirstName = c.String(), LastName = c.String(), Email = c.String(maxLength: 256), Enabled = c.Boolean(nullable: false), EmailConfirmed = c.Boolean(nullable: false), PasswordHash = c.String(), SecurityStamp = c.String(), PhoneNumber = c.String(), PhoneNumberConfirmed = c.Boolean(nullable: false), TwoFactorEnabled = c.Boolean(nullable: false), LockoutEndDateUtc = c.DateTime(), LockoutEnabled = c.Boolean(nullable: false), AccessFailedCount = c.Int(nullable: false), UserName = c.String(nullable: false, maxLength: 256), }) .PrimaryKey(t => t.Id) .Index(t => t.UserName, unique: true, name: "UserNameIndex"); CreateTable( "dbo.AspNetUserClaims", c => new { Id = c.Int(nullable: false, identity: true), UserId = c.String(nullable: false, maxLength: 128), ClaimType = c.String(), ClaimValue = c.String(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AspNetUserLogins", c => new { LoginProvider = c.String(nullable: false, maxLength: 128), ProviderKey = c.String(nullable: false, maxLength: 128), UserId = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => new { t.LoginProvider, t.ProviderKey, t.UserId }) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AspNetUserRoles", c => new { UserId = c.String(nullable: false, maxLength: 128), RoleId = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => new { t.UserId, t.RoleId }) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .ForeignKey("dbo.AspNetRoles", t => t.RoleId, cascadeDelete: true) .Index(t => t.UserId) .Index(t => t.RoleId); CreateTable( "dbo.CoordinatorInfo", c => new { CoordInfoID = c.Int(nullable: false, identity: true), User_Id = c.String(maxLength: 128), }) .PrimaryKey(t => t.CoordInfoID) .ForeignKey("dbo.AspNetUsers", t => t.User_Id) .Index(t => t.User_Id); CreateTable( "dbo.Major", c => new { MajorID = c.Int(nullable: false, identity: true), MajorName = c.String(), Department_DepartmentID = c.Int(), CoordinatorInfo_CoordInfoID = c.Int(), }) .PrimaryKey(t => t.MajorID) .ForeignKey("dbo.Department", t => t.Department_DepartmentID) .ForeignKey("dbo.CoordinatorInfo", t => t.CoordinatorInfo_CoordInfoID) .Index(t => t.Department_DepartmentID) .Index(t => t.CoordinatorInfo_CoordInfoID); CreateTable( "dbo.Department", c => new { DepartmentID = c.Int(nullable: false, identity: true), DepartmentName = c.String(), }) .PrimaryKey(t => t.DepartmentID); CreateTable( "dbo.Course", c => new { CourseID = c.Int(nullable: false, identity: true), CourseNumber = c.String(), }) .PrimaryKey(t => t.CourseID); CreateTable( "dbo.EmailInfo", c => new { EmailInfoID = c.Int(nullable: false, identity: true), SMTPAccountName = c.String(), SMTPPassword = c.String(), SMTPAddress = c.String(), Domain = c.String(), }) .PrimaryKey(t => t.EmailInfoID); CreateTable( "dbo.RegisterInvite", c => new { RegisterInviteID = c.String(nullable: false, maxLength: 128), Email = c.String(nullable: false), UserType = c.Int(nullable: false), }) .PrimaryKey(t => t.RegisterInviteID); CreateTable( "dbo.PasswordReset", c => new { Id = c.String(nullable: false, maxLength: 128), Email = c.String(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AspNetRoles", c => new { Id = c.String(nullable: false, maxLength: 128), Name = c.String(nullable: false, maxLength: 256), }) .PrimaryKey(t => t.Id) .Index(t => t.Name, unique: true, name: "RoleNameIndex"); CreateTable( "dbo.StudentInfo", c => new { LNumber = c.String(nullable: false, maxLength: 128), GPA = c.Double(nullable: false), Major_MajorID = c.Int(), User_Id = c.String(maxLength: 128), }) .PrimaryKey(t => t.LNumber) .ForeignKey("dbo.Major", t => t.Major_MajorID) .ForeignKey("dbo.AspNetUsers", t => t.User_Id) .Index(t => t.Major_MajorID) .Index(t => t.User_Id); } public override void Down() { DropForeignKey("dbo.StudentInfo", "User_Id", "dbo.AspNetUsers"); DropForeignKey("dbo.StudentInfo", "Major_MajorID", "dbo.Major"); DropForeignKey("dbo.AspNetUserRoles", "RoleId", "dbo.AspNetRoles"); DropForeignKey("dbo.CoordinatorInfo", "User_Id", "dbo.AspNetUsers"); DropForeignKey("dbo.Major", "CoordinatorInfo_CoordInfoID", "dbo.CoordinatorInfo"); DropForeignKey("dbo.Major", "Department_DepartmentID", "dbo.Department"); DropForeignKey("dbo.Application", "User_Id", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserRoles", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserLogins", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserClaims", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.Application", "Opportunity_OpportunityID", "dbo.Opportunity"); DropIndex("dbo.StudentInfo", new[] { "User_Id" }); DropIndex("dbo.StudentInfo", new[] { "Major_MajorID" }); DropIndex("dbo.AspNetRoles", "RoleNameIndex"); DropIndex("dbo.Major", new[] { "CoordinatorInfo_CoordInfoID" }); DropIndex("dbo.Major", new[] { "Department_DepartmentID" }); DropIndex("dbo.CoordinatorInfo", new[] { "User_Id" }); DropIndex("dbo.AspNetUserRoles", new[] { "RoleId" }); DropIndex("dbo.AspNetUserRoles", new[] { "UserId" }); DropIndex("dbo.AspNetUserLogins", new[] { "UserId" }); DropIndex("dbo.AspNetUserClaims", new[] { "UserId" }); DropIndex("dbo.AspNetUsers", "UserNameIndex"); DropIndex("dbo.Application", new[] { "User_Id" }); DropIndex("dbo.Application", new[] { "Opportunity_OpportunityID" }); DropTable("dbo.StudentInfo"); DropTable("dbo.AspNetRoles"); DropTable("dbo.PasswordReset"); DropTable("dbo.RegisterInvite"); DropTable("dbo.EmailInfo"); DropTable("dbo.Course"); DropTable("dbo.Department"); DropTable("dbo.Major"); DropTable("dbo.CoordinatorInfo"); DropTable("dbo.AspNetUserRoles"); DropTable("dbo.AspNetUserLogins"); DropTable("dbo.AspNetUserClaims"); DropTable("dbo.AspNetUsers"); DropTable("dbo.Opportunity"); DropTable("dbo.Application"); } } }
/* Copyright (c) 2005-2006 Tomas Matousek and Martin Maly. The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ /* not implemented yet: # mb_ check_ encoding # mb_ convert_ case # mb_ convert_ encoding # mb_ convert_ kana # mb_ convert_ variables # mb_ decode_ mimeheader # mb_ decode_ numericentity # mb_ detect_ encoding # mb_ detect_ order # mb_ encode_ mimeheader # mb_ encode_ numericentity # mb_ encoding_ aliases # mb_ ereg_ match # mb_ ereg_ replace # mb_ ereg_ search_ getpos # mb_ ereg_ search_ getregs # mb_ ereg_ search_ init # mb_ ereg_ search_ pos # mb_ ereg_ search_ regs # mb_ ereg_ search_ setpos # mb_ ereg_ search # mb_ ereg # mb_ eregi_ replace # mb_ eregi # mb_ get_ info # mb_ http_ input # mb_ http_ output # mb_ output_ handler */ using System; using System.Data; using System.Collections; using System.Text; using System.Data.SqlClient; using PHP.Core; using System.Collections.Generic; namespace PHP.Library.Strings { /// <summary> /// Implements PHP functions provided by multi-byte-string extension. /// </summary> public static class MultiByteString { #region Constants [Flags] public enum OverloadConstants { [ImplementsConstant("MB_OVERLOAD_MAIL")] MB_OVERLOAD_MAIL = 1, [ImplementsConstant("MB_OVERLOAD_STRING")] MB_OVERLOAD_STRING = 2, [ImplementsConstant("MB_OVERLOAD_REGEX")] MB_OVERLOAD_REGEX = 4, } [Flags] public enum CaseConstants { [ImplementsConstant("MB_CASE_UPPER")] MB_CASE_UPPER = 0, [ImplementsConstant("MB_CASE_LOWER")] MB_CASE_LOWER = 1, [ImplementsConstant("MB_CASE_TITLE")] MB_CASE_TITLE = 2, } #endregion #region Encodings private static Dictionary<string, Encoding> _encodings = null; public static Dictionary<string, Encoding>/*!*/Encodings { get { if (_encodings == null) { Dictionary<string, Encoding> enc = new Dictionary<string, Encoding>(180, StringComparer.OrdinalIgnoreCase); // encoding names used in PHP //enc["pass"] = Encoding.Default; // TODO: "pass" encoding enc["auto"] = Configuration.Application.Globalization.PageEncoding; enc["wchar"] = Encoding.Unicode; //byte2be //byte2le //byte4be //byte4le //BASE64 //UUENCODE //HTML-ENTITIES //Quoted-Printable //7bit //8bit //UCS-4 //UCS-4BE //UCS-4LE //UCS-2 //UCS-2BE //UCS-2LE //UTF-32 //UTF-32BE //UTF-32LE //UTF-16 //UTF-16BE enc["UTF-16LE"] = Encoding.Unicode; // alias UTF-16 //UTF-8 //UTF-7 //UTF7-IMAP enc["ASCII"] = Encoding.ASCII; // alias us-ascii //EUC-JP //SJIS //eucJP-win //SJIS-win //CP51932 //JIS //ISO-2022-JP //ISO-2022-JP-MS //Windows-1252 //Windows-1254 //ISO-8859-1 //ISO-8859-2 //ISO-8859-3 //ISO-8859-4 //ISO-8859-5 //ISO-8859-6 //ISO-8859-7 //ISO-8859-8 //ISO-8859-9 //ISO-8859-10 //ISO-8859-13 //ISO-8859-14 //ISO-8859-15 //ISO-8859-16 //EUC-CN //CP936 //HZ //EUC-TW //BIG-5 //EUC-KR //UHC //ISO-2022-KR //Windows-1251 //CP866 //KOI8-R //KOI8-U //ArmSCII-8 //CP850 // .NET encodings foreach (var encoding in Encoding.GetEncodings()) enc[encoding.Name] = encoding.GetEncoding(); _encodings = enc; } return _encodings; } } /// <summary> /// Get encoding based on the PHP name. Can return null is such encoding is not defined. /// </summary> /// <param name="encodingName"></param> /// <returns></returns> public static Encoding GetEncoding(string encodingName) { Encoding encoding; if (!Encodings.TryGetValue(encodingName, out encoding)) return null; return encoding; } #endregion #region Object conversion using specified encoding private delegate Encoding getEncoding(); /// <summary> /// Converts PhpBytes using specified encoding. If any other object is provided, encoding is not performed. /// </summary> /// <param name="str"></param> /// <param name="encodingGetter"></param> /// <returns></returns> private static string ObjectToString(object str, getEncoding encodingGetter) { if (str is PhpBytes) { PhpBytes bytes = (PhpBytes)str; Encoding encoding = encodingGetter(); if (encoding == null) return null; return encoding.GetString(bytes.ReadonlyData, 0, bytes.Length); } else { // .NET String should be always UTF-16, given encoding is irrelevant return PHP.Core.Convert.ObjectToString(str); } } #endregion #region mb_internal_encoding, mb_preferred_mime_name /// <summary> /// Multi Byte String Internal Encoding. /// </summary> public static Encoding/*!*/InternalEncoding { get { return _internalEncoding ?? Configuration.Application.Globalization.PageEncoding; } private set { _internalEncoding = value; } } /// <summary> /// Multi Byte String Internal Encoding IANA name. /// </summary> public static string InternalEncodingName { get { return InternalEncoding.WebName; } } [ThreadStatic] private static Encoding _internalEncoding = null; /// <summary> /// Get encoding used by default in the extension. /// </summary> /// <returns></returns> [ImplementsFunction("mb_internal_encoding")] public static string GetInternalEncoding() { return InternalEncoding.WebName; } /// <summary> /// Set the encoding used by the extension. /// </summary> /// <param name="encodingName"></param> /// <returns>True is encoding was set, otherwise false.</returns> [ImplementsFunction("mb_internal_encoding")] public static bool SetInternalEncoding(string encodingName) { Encoding enc = GetEncoding(encodingName); if (enc != null) { InternalEncoding = enc; return true; } else { return false; } } /// <summary> /// Get a MIME charset string for a specific encoding. /// </summary> /// <param name="encoding_name">The encoding being checked. Its WebName or PHP/Phalanger name.</param> /// <returns>The MIME charset string for given character encoding.</returns> [ImplementsFunction("mb_preferred_mime_name")] public static string GetPreferredMimeName(string encoding_name) { Encoding encoding; if ( (encoding = Encoding.GetEncoding(encoding_name)) == null && // .NET encodings (by their WebName) (encoding = GetEncoding(encoding_name)) == null //try PHP internal encodings too (by PHP/Phalanger name) ) { PhpException.ArgumentValueNotSupported("encoding_name", encoding); return null; } return encoding.BodyName; // it seems to return right MIME } #endregion #region mb_regex_encoding, mb_regex_set_options /// <summary> /// Multi Byte String Internal Encoding. /// </summary> public static Encoding/*!*/RegexEncoding { get { return _regexEncoding ?? Configuration.Application.Globalization.PageEncoding; } private set { _regexEncoding = value; } } /// <summary> /// Multi Byte String regex Encoding IANA name. /// </summary> public static string RegexEncodingName { get { return RegexEncoding.WebName; } } [ThreadStatic] private static Encoding _regexEncoding = null; /// <summary> /// Get encoding used by regex in the extension. /// </summary> /// <returns></returns> [ImplementsFunction("mb_regex_encoding")] public static string GetRegexEncoding() { return RegexEncoding.WebName; } /// <summary> /// Set the encoding used by the extension in regex functions. /// </summary> /// <param name="encodingName"></param> /// <returns>True is encoding was set, otherwise false.</returns> [ImplementsFunction("mb_regex_encoding")] public static bool SetRegexEncoding(string encodingName) { Encoding enc = GetEncoding(encodingName); if (enc != null) { RegexEncoding = enc; return true; } else { return false; } } #region regex options [Flags] private enum RegexOptions { None = 0, /// <summary> /// i /// </summary> AmbiguityMatch = 1, /// <summary> /// x /// </summary> ExtendedPatternForm = 2, /// <summary> /// m /// </summary> DotMatchesNewLine = 4, /// <summary> /// s /// </summary> ConvertMatchBeginEnd = 8, /// <summary> /// l /// </summary> FindLongestMatch = 16, /// <summary> /// n /// </summary> IgnoreEmptyMatch = 32, /// <summary> /// e /// </summary> EvalResultingCode = 64, } private enum RegexSyntaxModes { /// <summary> /// d /// </summary> POSIXExtendedRegex, } [ThreadStatic] private static RegexOptions _regexOptions = RegexOptions.DotMatchesNewLine | RegexOptions.ConvertMatchBeginEnd; [ThreadStatic] private static RegexSyntaxModes _regexSyntaxMode = RegexSyntaxModes.POSIXExtendedRegex; /// <summary> /// Determines if given combination of options is enabled. /// </summary> /// <param name="opt">Option or mask of options to test.</param> /// <returns>True if given option mask is enabled.</returns> private static bool OptionEnabled(RegexOptions opt) { return (_regexOptions & opt) != 0; } /// <summary> /// Determines if given syntax mode is set. /// </summary> /// <param name="opt">Syntax mode to test.</param> /// <returns>True if given syntax mode is enabled.</returns> private static bool OptionEnabled(RegexSyntaxModes opt) { return (_regexSyntaxMode == opt); } #endregion /// <summary> /// Get currently set regex options. /// </summary> /// <returns>Option string.</returns> [ImplementsFunction("mb_regex_set_options")] public static string GetRegexOptions() { string optionString = string.Empty; if (OptionEnabled(RegexOptions.AmbiguityMatch)) optionString += 'i'; if (OptionEnabled(RegexOptions.ExtendedPatternForm)) optionString += 'x'; if (OptionEnabled(RegexOptions.DotMatchesNewLine)) optionString += 'm'; if (OptionEnabled(RegexOptions.ConvertMatchBeginEnd)) optionString += 's'; if (OptionEnabled(RegexOptions.FindLongestMatch)) optionString += 'l'; if (OptionEnabled(RegexOptions.IgnoreEmptyMatch)) optionString += 'n'; if (OptionEnabled(RegexOptions.EvalResultingCode)) optionString += 'e'; if (OptionEnabled(RegexSyntaxModes.POSIXExtendedRegex)) optionString += 'd'; else throw new NotImplementedException("syntax mode not catch by mb_regex_set_options()!"); return optionString; } /// <summary> /// Set new regex options. /// </summary> /// <param name="options">Option string.</param> /// <returns>New option string.</returns> /// <remarks> /// Regex options: /// Option Meaning /// i Ambiguity match on /// x Enables extended pattern form /// m '.' matches with newlines /// s '^' -> '\A', '$' -> '\Z' /// p Same as both the m and s options /// l Finds longest matches /// n Ignores empty matches /// e eval() resulting code /// /// Regex syntax modes: /// Mode Meaning /// j (not supported) Java (Sun java.util.regex) /// u (not supported) GNU regex /// g (not supported) grep /// c (not supported) Emacs /// r (not supported) Ruby /// z (not supported) Perl /// b (not supported) POSIX Basic regex /// d POSIX Extended regex /// </remarks> [ImplementsFunction("mb_regex_set_options")] public static string SetRegexOptions(string options) { RegexOptions newRegexOptions = RegexOptions.None; RegexSyntaxModes newRegexSyntaxModes = RegexSyntaxModes.POSIXExtendedRegex; foreach (char c in options) { switch (c) { case 'i': newRegexOptions |= RegexOptions.AmbiguityMatch; break; case 'x': newRegexOptions |= RegexOptions.ExtendedPatternForm; break; case 'm': newRegexOptions |= RegexOptions.DotMatchesNewLine; break; case 's': newRegexOptions |= RegexOptions.ConvertMatchBeginEnd; break; case 'p': newRegexOptions |= RegexOptions.DotMatchesNewLine | RegexOptions.ConvertMatchBeginEnd; break; case 'l': newRegexOptions |= RegexOptions.FindLongestMatch; break; case 'n': newRegexOptions |= RegexOptions.IgnoreEmptyMatch; break; case 'e': newRegexOptions |= RegexOptions.EvalResultingCode; break; case 'd': newRegexSyntaxModes = RegexSyntaxModes.POSIXExtendedRegex; break; default: PhpException.ArgumentValueNotSupported("options", c); break; } } // _regexOptions = newRegexOptions; _regexSyntaxMode = newRegexSyntaxModes; return GetRegexOptions(); } #endregion #region mb_substr, mb_strcut #region mb_substr implementation [ImplementsFunction("mb_substr")] [return: CastToFalse] public static string SubString(object str, int start) { return SubString(str, start, -1, () => InternalEncoding); } [ImplementsFunction("mb_substr")] [return: CastToFalse] public static string SubString(object str, int start, int length) { return SubString(str, start, length, () => InternalEncoding); } [ImplementsFunction("mb_substr")] [return:CastToFalse] public static string SubString(object str, int start, int length, string encoding) { return SubString(str, start, length, () => GetEncoding(encoding)); } #endregion #region mb_strcut (in PHP it behaves differently, but in .NET it is an alias for mb_substr) [ImplementsFunction("mb_strcut")] [return: CastToFalse] public static string CutString(object str, int start) { return SubString(str, start, -1, () => InternalEncoding); } [ImplementsFunction("mb_strcut")] [return: CastToFalse] public static string CutString(object str, int start, int length) { return SubString(str, start, length, () => InternalEncoding); } [ImplementsFunction("mb_strcut")] [return: CastToFalse] public static string CutString(object str, int start, int length, string encoding) { return SubString(str, start, length, () => GetEncoding(encoding)); } #endregion private static string SubString(object str, int start, int length, getEncoding encodingGetter) { // get the Unicode representation of the string string ustr = ObjectToString(str, encodingGetter); if (ustr == null) return null; // start counting from the end of the string if (start < 0) start = ustr.Length + start; // can result in negative start again -> invalid if (length == -1) length = ustr.Length; // check boundaries if (start >= ustr.Length || length < 0 || start < 0) return null; if (length == 0) return string.Empty; // return the substring return (start + length > ustr.Length) ? ustr.Substring(start) : ustr.Substring(start, length); } #endregion #region mb_substr_count [ImplementsFunction("mb_substr_count")] public static int SubStringCount(string haystack , string needle ) { return SubStringCount(haystack, needle, () => InternalEncoding); } [ImplementsFunction("mb_substr_count")] public static int SubStringCount(string haystack, string needle, string encoding) { return SubStringCount(haystack, needle, () => GetEncoding(encoding)); } private static int SubStringCount(string haystack, string needle, getEncoding encodingGetter) { string uhaystack = ObjectToString(haystack, encodingGetter); string uneedle = ObjectToString(needle, encodingGetter); if (uhaystack == null || uneedle == null) return 0; return PhpStrings.SubstringCount(uhaystack, uneedle); } #endregion #region mb_substitute_character [ImplementsFunction("mb_substitute_character")] public static object GetSubstituteCharacter() { PhpException.FunctionNotSupported(); return false; } [ImplementsFunction("mb_substitute_character")] public static object SetSubstituteCharacter(object substrchar) { PhpException.FunctionNotSupported(); return "none"; } #endregion #region mb_strwidth, mb_strimwidth /// <summary> /// Determines the char width. /// </summary> /// <param name="c">Character.</param> /// <returns>The width of the character.</returns> private static int CharWidth(char c) { //Chars Width //U+0000 - U+0019 0 //U+0020 - U+1FFF 1 //U+2000 - U+FF60 2 //U+FF61 - U+FF9F 1 //U+FFA0 - 2 if (c <= 0x0019) return 0; else if (c <= 0x1fff) return 1; else if (c <= 0xff60) return 2; else if (c <= 0xff9f) return 1; else return 2; } private static int StringWidth(string str) { if (str == null) return 0; int width = 0; foreach (char c in str) width += CharWidth(c); return width; } /// <summary> /// /// </summary> /// <param name="str"></param> /// <param name="width">Characters remaining.</param> /// <returns></returns> private static string StringTrimByWidth(string/*!*/str, ref int width) { if (str == null) return null; int i = 0; foreach (char c in str) { int w = CharWidth(c); if (w < width) { ++i; width -= w; } else if (w == width) { ++i; width = 0; break; } else break; } return (i < str.Length) ? str.Remove(i) : str; } #region mb_strwidth implementation [ImplementsFunction("mb_strwidth")] public static int StringWidth(object str) { return StringWidth(str, () => InternalEncoding); } /// <summary> /// The string width. Not the string length. /// Multi-byte characters are usually twice the width of single byte characters. /// </summary> /// <param name="str">The string being decoded. </param> /// <param name="encoding">The encoding parameter is the character encoding in case of PhpBytes is used. If it is omitted, the internal character encoding value will be used.</param> /// <returns>The width of string str.</returns> /// <remarks> /// Chars Width /// U+0000 - U+0019 0 /// U+0020 - U+1FFF 1 /// U+2000 - U+FF60 2 /// U+FF61 - U+FF9F 1 /// U+FFA0 - 2 /// </remarks> [ImplementsFunction("mb_strwidth")] public static int StringWidth(object str, string encoding) { return StringWidth(str, () =>GetEncoding(encoding)); } private static int StringWidth(object str, getEncoding encodingGetter) { return StringWidth(ObjectToString(str, encodingGetter)); } #endregion #region mb_strimwidth implementation [ImplementsFunction("mb_strimwidth")] public static string STrimWidth(object str, int start, int width) { return StringTrimByWidth(str, start, width, null, () => InternalEncoding); } [ImplementsFunction("mb_strimwidth")] public static string STrimWidth(object str, int start, int width, string trimmarker) { return StringTrimByWidth(str, start, width, trimmarker, () => InternalEncoding); } [ImplementsFunction("mb_strimwidth")] public static string STrimWidth(object str, int start, int width, string trimmarker, string encoding) { return StringTrimByWidth(str, start, width, trimmarker, () => GetEncoding(encoding)); } private static string StringTrimByWidth(object str, int start, int width, string trimmarker, getEncoding encodingGetter) { string ustr = ObjectToString(str, encodingGetter); if (start >= ustr.Length) return string.Empty; ustr = ustr.Substring(start); int ustrWidth = StringWidth(ustr); if (ustrWidth <= width) return ustr; // trim the string int trimmarkerWidth = StringWidth(trimmarker); width -= trimmarkerWidth; string trimmedStr = StringTrimByWidth(ustr, ref width); width += trimmarkerWidth; string trimmedTrimMarker = StringTrimByWidth(trimmarker, ref width); // return trimmedStr + trimmedTrimMarker; } #endregion #endregion #region mb_strtoupper, mb_strtolower [ImplementsFunction("mb_strtoupper")] public static string StrToUpper(object str) { return StrToUpper(str, () => InternalEncoding); } [ImplementsFunction("mb_strtoupper")] public static string StrToUpper(object str, string encoding) { return StrToUpper(str, () => GetEncoding(encoding)); } private static string StrToUpper(object str, getEncoding encodingGetter) { string ustr = ObjectToString(str, encodingGetter); return ustr.ToUpperInvariant(); } [ImplementsFunction("mb_strtolower")] public static string StrToLower(object str) { return StrToLower(str, () => InternalEncoding); } [ImplementsFunction("mb_strtolower")] public static string StrToLower(object str, string encoding) { return StrToLower(str, () => GetEncoding(encoding)); } private static string StrToLower(object str, getEncoding encodingGetter) { string ustr = ObjectToString(str, encodingGetter); return ustr.ToLowerInvariant(); } #endregion #region mb_strstr, mb_stristr [ImplementsFunction("mb_strstr")] [return:CastToFalse] public static string StrStr(object haystack, object needle) { return StrStr(haystack, needle, false, () => InternalEncoding, false); } [ImplementsFunction("mb_strstr")] [return: CastToFalse] public static string StrStr(object haystack, object needle, bool part/*=FALSE*/) { return StrStr(haystack, needle, part, () => InternalEncoding, false); } [ImplementsFunction("mb_strstr")] [return: CastToFalse] public static string StrStr(object haystack, object needle, bool part/*=FALSE*/, string encoding) { return StrStr(haystack, needle, part, () => GetEncoding(encoding), false); } [ImplementsFunction("mb_stristr")] [return: CastToFalse] public static string StriStr(object haystack, object needle) { return StrStr(haystack, needle, false, () => InternalEncoding, true); } [ImplementsFunction("mb_stristr")] [return: CastToFalse] public static string StriStr(object haystack, object needle, bool part/*=FALSE*/) { return StrStr(haystack, needle, part, () => InternalEncoding, true); } [ImplementsFunction("mb_stristr")] [return: CastToFalse] public static string StriStr(object haystack, object needle, bool part/*=FALSE*/, string encoding) { return StrStr(haystack, needle, part, () => GetEncoding(encoding), true); } /// <summary> /// mb_strstr() finds the first occurrence of needle in haystack and returns the portion of haystack. If needle is not found, it returns FALSE. /// </summary> /// <param name="haystack">The string from which to get the first occurrence of needle</param> /// <param name="needle">The string to find in haystack</param> /// <param name="part">Determines which portion of haystack this function returns. If set to TRUE, it returns all of haystack from the beginning to the first occurrence of needle. If set to FALSE, it returns all of haystack from the first occurrence of needle to the end.</param> /// <param name="encodingGetter">Character encoding name to use. If it is omitted, internal character encoding is used. </param> /// <param name="ignoreCase">Case insensitive.</param> /// <returns>Returns the portion of haystack, or FALSE (-1) if needle is not found.</returns> private static string StrStr(object haystack, object needle, bool part/* = false*/ , getEncoding encodingGetter, bool ignoreCase) { string uhaystack = ObjectToString(haystack, encodingGetter); string uneedle = ObjectToString(needle, encodingGetter); if (uhaystack == null || uneedle == null) // never happen return null; if (uneedle == String.Empty) { PhpException.InvalidArgument("needle", LibResources.GetString("arg:empty")); return null; } int index = (ignoreCase) ? uhaystack.ToLower().IndexOf(uneedle.ToLower()) : uhaystack.IndexOf(uneedle); return (index == -1) ? null : (part ? uhaystack.Substring(0, index) : uhaystack.Substring(index)); } #endregion #region mb_strpos, mb_stripos, mb_strrpos, mb_strripos #region mb_strpos stub [ImplementsFunction("mb_strpos")] [return: CastToFalse] public static int Strpos(object haystack, object needle) { return Strpos(haystack, needle, 0, () => InternalEncoding, false); } [ImplementsFunction("mb_strpos")] [return: CastToFalse] public static int Strpos(object haystack, object needle, int offset) { return Strpos(haystack, needle, offset, () => InternalEncoding, false); } [ImplementsFunction("mb_strpos")] [return:CastToFalse] public static int Strpos(object haystack, object needle, int offset, string encoding) { return Strpos(haystack, needle, offset, () => GetEncoding(encoding), false); } #endregion #region mb_stripos stub [ImplementsFunction("mb_stripos")] [return: CastToFalse] public static int Stripos(object haystack, object needle) { return Strpos(haystack, needle, 0, () => InternalEncoding, true); } [ImplementsFunction("mb_stripos")] [return: CastToFalse] public static int Stripos(object haystack, object needle, int offset) { return Strpos(haystack, needle, offset, () => InternalEncoding, true); } [ImplementsFunction("mb_stripos")] [return: CastToFalse] public static int Stripos(object haystack, object needle, int offset, string encoding) { return Strpos(haystack, needle, offset, () => GetEncoding(encoding), true); } #endregion #region mb_strrpos stub [ImplementsFunction("mb_strrpos")] [return: CastToFalse] public static int Strrpos(object haystack, object needle) { return Strrpos(haystack, needle, 0, () => InternalEncoding, false); } [ImplementsFunction("mb_strrpos")] [return: CastToFalse] public static int Strrpos(object haystack, object needle, int offset) { return Strrpos(haystack, needle, offset, () => InternalEncoding, false); } [ImplementsFunction("mb_strrpos")] [return: CastToFalse] public static int Strrpos(object haystack, object needle, int offset, string encoding) { return Strrpos(haystack, needle, offset, () => GetEncoding(encoding), false); } #endregion #region mb_strripos stub [ImplementsFunction("mb_strripos")] [return: CastToFalse] public static int Strripos(object haystack, object needle) { return Strrpos(haystack, needle, 0, () => InternalEncoding, true); } [ImplementsFunction("mb_strripos")] [return: CastToFalse] public static int Strripos(object haystack, object needle, int offset) { return Strrpos(haystack, needle, offset, () => InternalEncoding, true); } [ImplementsFunction("mb_strripos")] [return: CastToFalse] public static int Strripos(object haystack, object needle, int offset, string encoding) { return Strrpos(haystack, needle, offset, () => GetEncoding(encoding), true); } #endregion /// <summary> /// Implementation of <c>mb_str[i]pos</c> functions. /// </summary> private static int Strpos(object haystack, object needle, int offset, getEncoding encodingGetter, bool ignoreCase) { string uhaystack = ObjectToString(haystack, encodingGetter); string uneedle = ObjectToString(needle, encodingGetter); if (uhaystack == null || uneedle == null) return -1; if (offset < 0 || offset >= uhaystack.Length) { if (offset != uhaystack.Length) PhpException.InvalidArgument("offset", LibResources.GetString("arg:out_of_bounds")); return -1; } if (uneedle == String.Empty) { PhpException.InvalidArgument("needle", LibResources.GetString("arg:empty")); return -1; } if (ignoreCase) return uhaystack.ToLower().IndexOf(uneedle.ToLower(), offset); else return uhaystack.IndexOf(uneedle, offset); } /// <summary> /// Implementation of <c>mb_strr[i]pos</c> functions. /// </summary> private static int Strrpos(object haystack, object needle, int offset, getEncoding encodingGetter, bool ignoreCase) { string uhaystack = ObjectToString(haystack, encodingGetter); string uneedle = ObjectToString(needle, encodingGetter); if (uhaystack == null || uneedle == null) return -1; int end = uhaystack.Length - 1; if (offset > end || offset < -end - 1) { PhpException.InvalidArgument("offset", LibResources.GetString("arg:out_of_bounds")); return -1; } if (offset < 0) { end += uneedle.Length + offset; offset = 0; } if (uneedle.Length == 0) { PhpException.InvalidArgument("needle", LibResources.GetString("arg:empty")); return -1; } if (ignoreCase) return uhaystack.ToLower().LastIndexOf(uneedle.ToLower(), end, end - offset + 1); else return uhaystack.LastIndexOf(uneedle, end, end - offset + 1); } #endregion #region mb_strlen [ImplementsFunction("mb_strlen")] public static int StrLen(object str) { return StrLen(str, () => InternalEncoding); } [ImplementsFunction("mb_strlen")] public static int StrLen(object str, string encoding) { return StrLen(str, ()=>GetEncoding(encoding)); } /// <summary> /// Counts characters in a Unicode string or multi-byte string in PhpBytes. /// </summary> /// <param name="str">String or PhpBytes to use.</param> /// <param name="encodingGetter">Encoding used to encode PhpBytes</param> /// <returns>Number of unicode characters in given object.</returns> private static int StrLen(object str, getEncoding encodingGetter) { if (str == null) return 0; if (str.GetType() == typeof(string)) { return ((string)str).Length; } else if (str.GetType() == typeof(PhpBytes)) { Encoding encoding = encodingGetter(); if (encoding == null) throw new NotImplementedException(); return encoding.GetCharCount(((PhpBytes)str).ReadonlyData); } else { return (ObjectToString(str, encodingGetter) ?? string.Empty).Length; } } #endregion #region mb_strrchr, mb_strrichr #region mb_strrchr stub [ImplementsFunction("mb_strrchr")] [return: CastToFalse] public static string StrrChr(object haystack, object needle) { return StrrChr(haystack, needle, false, () => InternalEncoding, false); } [ImplementsFunction("mb_strrchr")] [return: CastToFalse] public static string StrrChr(object haystack, object needle, bool part/*=false*/) { return StrrChr(haystack, needle, part, () => InternalEncoding, false); } [ImplementsFunction("mb_strrchr")] [return:CastToFalse] public static string StrrChr(object haystack, object needle, bool part/*=false*/, string encoding) { return StrrChr(haystack, needle, part, () => GetEncoding(encoding), false); } #endregion #region mb_strrichr stub [ImplementsFunction("mb_strrichr")] [return: CastToFalse] public static string StrriChr(object haystack, object needle) { return StrrChr(haystack, needle, false, () => InternalEncoding, true); } [ImplementsFunction("mb_strrichr")] [return: CastToFalse] public static string StrriChr(object haystack, object needle, bool part/*=false*/) { return StrrChr(haystack, needle, part, () => InternalEncoding, true); } [ImplementsFunction("mb_strrichr")] [return: CastToFalse] public static string StrriChr(object haystack, object needle, bool part/*=false*/, string encoding) { return StrrChr(haystack, needle, part, () => GetEncoding(encoding), true); } #endregion private static string StrrChr(object haystack, object needle, bool beforeNeedle/*=false*/, getEncoding encodingGetter, bool ignoreCase) { string uhaystack = ObjectToString(haystack, encodingGetter); char cneedle; { string uneedle; if (needle is string) uneedle = (string)needle; else if (needle is PhpString) uneedle = ((IPhpConvertible)needle).ToString(); else if (needle is PhpBytes) { Encoding encoding = encodingGetter(); if (encoding == null) return null; PhpBytes bytes = (PhpBytes)needle; uneedle = encoding.GetString(bytes.ReadonlyData, 0, bytes.Length); } else { // needle as a character number Encoding encoding = encodingGetter(); if (encoding == null) return null; uneedle = encoding.GetString(new byte[] { unchecked((byte)Core.Convert.ObjectToInteger(needle)) }, 0, 1); } if (string.IsNullOrEmpty(uneedle)) return null; cneedle = uneedle[0]; } int index = (ignoreCase) ? uhaystack.ToLower().LastIndexOf(char.ToLower(cneedle)) : uhaystack.LastIndexOf(cneedle); if (index < 0) return null; return (beforeNeedle) ? uhaystack.Remove(index) : uhaystack.Substring(index); } #endregion #region mb_split [ImplementsFunction("mb_split")] public static PhpArray Split(object pattern, object str) { return Split(pattern,str,-1); } [ImplementsFunction("mb_split")] public static PhpArray Split(object pattern, object str, int limit /*= -1*/) { return Library.PosixRegExp.DoSplit( ObjectToString(pattern, ()=>RegexEncoding), ObjectToString(str, ()=>RegexEncoding), limit, limit != -1, false); } #endregion #region mb_language, mb_send_mail /*/// <summary> /// Multi Byte String language used by mail functions. /// </summary> public static string MailLanguage { get { return _mailLanguage ?? "uni"; } set { _mailLanguage = value; // TODO: check the value } } [ThreadStatic] private static string _mailLanguage = null;*/ /// <summary> /// Get language used by mail functions. /// </summary> /// <returns></returns> [ImplementsFunction("mb_language")] public static string GetMailLanguage() { return "uni";//MailLanguage; } /// <summary> /// Set the language used by mail functions. /// </summary> /// <param name="language"></param> /// <returns>True if language was set, otherwise false.</returns> [ImplementsFunction("mb_language")] public static bool SetMailLanguage(string language) { PhpException.FunctionNotSupported(); return false; //try //{ // MailLanguage = language; // return true; //} //catch //{ // return false; //} } #region mb_send_mail(), TODO: use mb_language [ImplementsFunction("mb_send_mail")] public static bool SendMail(string to, string subject, string message ) { return PHP.Library.Mailer.Mail(to, subject, message); } [ImplementsFunction("mb_send_mail")] public static bool SendMail(string to, string subject, string message, string additional_headers /*= NULL*/ ) { return PHP.Library.Mailer.Mail(to, subject, message, additional_headers); } [ImplementsFunction("mb_send_mail")] public static bool SendMail( string to, string subject, string message , string additional_headers /*= NULL*/, string additional_parameter /*= NULL*/ ) { return PHP.Library.Mailer.Mail(to, subject, message, additional_headers, additional_parameter); } #endregion #endregion #region mb_parse_str [ImplementsFunction("mb_parse_str")] public static bool ParseStr(string encoded_string, PhpReference array) { try { PhpArray result = new PhpArray(); foreach (var x in ParseUrlEncodedGetParameters(encoded_string)) result.Add(x.Key, x.Value); array.Value = result; return true; } catch { return false; } } [ImplementsFunction("mb_parse_str")] public static bool ParseStr(string encoded_string) { try { PhpArray result = ScriptContext.CurrentContext.GlobalVariables; foreach (var x in ParseUrlEncodedGetParameters(encoded_string)) result.Add(x.Key, x.Value); return true; } catch { return false; } } /// <summary> /// Decodes URL encoded string and parses GET parameters. /// </summary> /// <param name="getParams">URL encoded GET parameters string.</param> /// <returns>Enumerator of decoded and parsed GET parameters as pairs of (name, value).</returns> private static IEnumerable<KeyValuePair<string,string>> ParseUrlEncodedGetParameters(string getParams) { foreach (var str in System.Web.HttpUtility.UrlDecode(getParams).Split(new char[]{'&'})) { if (str.Length == 0) continue; int eqPos = str.IndexOf('='); if (eqPos > 0) { // name = value yield return new KeyValuePair<string, string>(str.Substring(0, eqPos), str.Substring(eqPos + 1)); } else if (eqPos == 0) { // ignore, no variable name } else { // just variable name yield return new KeyValuePair<string, string>(str, null); } } } #endregion } }
using System; using System.Data; using System.Data.SqlClient; using DevExpress.XtraEditors; using System.Windows.Forms; namespace KabMan.Server { /// <summary> /// ADO.NET data access using the SQL Server Managed Provider. /// </summary> public class DatabaseLib : IDisposable { private const string connectionString = @"Data Source=ORION\SQL2008; Initial Catalog=KabMan; Integrated Security=True"; // connection to data source private SqlConnection con; #region IDisposable Members /// <summary> /// Release resources. /// </summary> public void Dispose() { // make sure connection is closed if (con != null) { con.Dispose(); con = null; } } #endregion /// <summary> /// Run Sql query. /// </summary> /// <returns>Execute Non Query</returns> public void RunSqlQuery(string queryString, out SqlDataReader dataReader) { SqlCommand cmd = CreateCommand(queryString); dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); } public void RunSqlQuery(string queryString, out DataSet dataSet) { SqlCommand cmd = CreateCommand(queryString); using (SqlDataAdapter dap = new SqlDataAdapter(cmd)) { dataSet = new DataSet(); dap.Fill(dataSet); } } public void RunSqlQuery(string queryString) { SqlCommand cmd = CreateCommand(queryString); cmd.ExecuteNonQuery(); cmd.Dispose(); } /// <summary> /// Run stored procedure. /// </summary> /// <param name="procName">Name of stored procedure.</param> /// <returns>Stored procedure return value.</returns> /* public int RunProc(string procName) { SqlCommand cmd = CreateCommand(procName, null); cmd.ExecuteNonQuery(); Close(); return (int) cmd.Parameters["@ReturnValue"].Value; } */ /// <summary> /// Run stored procedure. /// </summary> /// <param name="procName">Name of stored procedure.</param> /// <param name="prams">Stored procedure params.</param> /// <returns>Stored procedure return value.</returns> public int RunProc(string procName, SqlParameter[] prams) { SqlCommand cmd = CreateCommand(procName, prams); cmd.ExecuteNonQuery(); Close(); return (int) cmd.Parameters["@ReturnValue"].Value; } /// <summary> /// Run stored procedure. /// </summary> /// <param name="procName">Name of stored procedure.</param> /// <param name="dataSet">Return result of procedure.</param> public void RunProc(string procName, out DataSet dataSet) { SqlCommand cmd = CreateCommand(procName, null); //dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); using (SqlDataAdapter dap = new SqlDataAdapter(cmd)) { dataSet = new DataSet(); dap.Fill(dataSet); } } /// <summary> /// Run stored procedure. /// </summary> /// <param name="procName">Name of stored procedure.</param> /// <param name="prams">Stored procedure params.</param> /// <param name="dataSet">Return result of procedure.</param> public void RunProc(string procName, SqlParameter[] prams, out DataSet dataSet) { SqlCommand cmd = CreateCommand(procName, prams); using (SqlDataAdapter dap = new SqlDataAdapter(cmd)) { dataSet = new DataSet(); dap.Fill(dataSet); } } /// <summary> /// Run stored procedure. /// </summary> /// <param name="procName">Name of stored procedure.</param> /// <param name="dataReader">Return result of procedure.</param> public void RunProc(string procName, out SqlDataReader dataReader) { SqlCommand cmd = CreateCommand(procName, null); dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); } /// <summary> /// Run stored procedure. /// </summary> /// <param name="procName">Name of stored procedure.</param> /// <param name="prams">Stored procedure params.</param> /// <param name="dataReader">Return result of procedure.</param> public void RunProc(string procName, SqlParameter[] prams, out SqlDataReader dataReader) { SqlCommand cmd = CreateCommand(procName, prams); dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); } /// <summary> /// Create command object used to call stored procedure. /// </summary> /// <param name="procName">Name of stored procedure.</param> /// <param name="prams">Params to stored procedure.</param> /// <returns>Command object.</returns> private SqlCommand CreateCommand(string procName, SqlParameter[] prams) { // make sure connection is open Open(); SqlCommand cmd = new SqlCommand(procName, con) { CommandType = CommandType.StoredProcedure }; // add proc parameters if (prams != null) { foreach (SqlParameter parameter in prams) cmd.Parameters.Add(parameter); } // return param cmd.Parameters.Add( new SqlParameter("@ReturnValue", SqlDbType.Int, 4, ParameterDirection.ReturnValue, false, 0, 0, string.Empty, DataRowVersion.Default, null)); return cmd; } private SqlCommand CreateCommand(string queryString) { // make sure connection is open Open(); SqlCommand cmd = new SqlCommand(queryString, con) { CommandType = CommandType.Text }; return cmd; } /// <summary> /// Open the connection. /// </summary> private void Open() { try { // open connection if (con == null) { con = new SqlConnection(connectionString); con.Open(); } } catch (Exception ex) { XtraMessageBox.Show(ex.Message, "Database Connection", MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); } } /// <summary> /// Close the connection. /// </summary> public void Close() { if (con != null) con.Close(); } /// <summary> /// Make input param. /// </summary> /// <param name="ParamName">Name of param.</param> /// <param name="DbType">Param type.</param> /// <param name="Value">Param value.</param> /// <returns>New parameter.</returns> public SqlParameter MakeInParam(string ParamName, SqlDbType DbType, object Value) { if (Value == null) { Value = DBNull.Value; return MakeParam(ParamName, DbType, ParameterDirection.Input, Value); } else return MakeParam(ParamName, DbType, ParameterDirection.Input, Value); } public SqlParameter MakeInParam(string ParamName, object Value) { if (Value == null) { Value = DBNull.Value; return MakeParam(ParamName, ParameterDirection.Input, Value); } else return MakeParam(ParamName, ParameterDirection.Input, Value); } /// <summary> /// Make input param. /// </summary> /// <param name="ParamName">Name of param.</param> /// <param name="DbType">Param type.</param> /// <param name="Size">Param size.</param> /// <returns>New parameter.</returns> public SqlParameter MakeOutParam(string ParamName, SqlDbType DbType) { return MakeParam(ParamName, DbType, ParameterDirection.Output, null); } /// <summary> /// Make stored procedure param. /// </summary> /// <param name="ParamName">Name of param.</param> /// <param name="DbType">Param type.</param> /// <param name="Direction">Parm direction.</param> /// <param name="Value">Param value.</param> /// <returns>New parameter.</returns> public SqlParameter MakeParam(string ParamName, SqlDbType DbType, ParameterDirection Direction, object Value) { SqlParameter param; //if(Size > 0) // param = new SqlParameter(ParamName, DbType, Size); //else param = new SqlParameter(ParamName, DbType); param.Direction = Direction; if (!(Direction == ParameterDirection.Output && Value == null)) param.Value = Value; return param; } public SqlParameter MakeParam(string ParamName, ParameterDirection Direction, object Value) { SqlParameter param = new SqlParameter(ParamName, Value); //if(Size > 0) // param = new SqlParameter(ParamName, DbType, Size); //else param.Direction = Direction; if (!(Direction == ParameterDirection.Output && Value == null)) param.Value = Value; return param; } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Graphics.Containers; using osu.Framework.Testing; using osu.Game.Beatmaps; using osu.Game.Graphics.UserInterface; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Online.API.Requests.Responses; using osu.Game.Overlays; using osu.Game.Overlays.BeatmapListing; using osu.Game.Rulesets; using osu.Game.Scoring; using osu.Game.Users; using osuTK.Input; namespace osu.Game.Tests.Visual.Online { public class TestSceneBeatmapListingOverlay : OsuManualInputManagerTestScene { private readonly List<APIBeatmapSet> setsForResponse = new List<APIBeatmapSet>(); private BeatmapListingOverlay overlay; private BeatmapListingSearchControl searchControl => overlay.ChildrenOfType<BeatmapListingSearchControl>().Single(); [SetUpSteps] public void SetUpSteps() { AddStep("setup overlay", () => { Child = overlay = new BeatmapListingOverlay { State = { Value = Visibility.Visible } }; setsForResponse.Clear(); }); AddStep("initialize dummy", () => { var api = (DummyAPIAccess)API; api.HandleRequest = req => { if (!(req is SearchBeatmapSetsRequest searchBeatmapSetsRequest)) return false; searchBeatmapSetsRequest.TriggerSuccess(new SearchBeatmapSetsResponse { BeatmapSets = setsForResponse, }); return true; }; // non-supporter user api.LocalUser.Value = new User { Username = "TestBot", Id = API.LocalUser.Value.Id + 1, }; }); } [Test] public void TestHideViaBack() { AddAssert("is visible", () => overlay.State.Value == Visibility.Visible); AddStep("hide", () => InputManager.Key(Key.Escape)); AddUntilStep("is hidden", () => overlay.State.Value == Visibility.Hidden); } [Test] public void TestHideViaBackWithSearch() { AddAssert("is visible", () => overlay.State.Value == Visibility.Visible); AddStep("search something", () => overlay.ChildrenOfType<SearchTextBox>().First().Text = "search"); AddStep("kill search", () => InputManager.Key(Key.Escape)); AddAssert("search textbox empty", () => string.IsNullOrEmpty(overlay.ChildrenOfType<SearchTextBox>().First().Text)); AddAssert("is visible", () => overlay.State.Value == Visibility.Visible); AddStep("hide", () => InputManager.Key(Key.Escape)); AddUntilStep("is hidden", () => overlay.State.Value == Visibility.Hidden); } [Test] public void TestHideViaBackWithScrolledSearch() { AddAssert("is visible", () => overlay.State.Value == Visibility.Visible); AddStep("show many results", () => fetchFor(Enumerable.Repeat(CreateBeatmap(Ruleset.Value).BeatmapInfo.BeatmapSet, 100).ToArray())); AddUntilStep("placeholder hidden", () => !overlay.ChildrenOfType<BeatmapListingOverlay.NotFoundDrawable>().Any(d => d.IsPresent)); AddStep("scroll to bottom", () => overlay.ChildrenOfType<OverlayScrollContainer>().First().ScrollToEnd()); AddStep("kill search", () => InputManager.Key(Key.Escape)); AddUntilStep("search textbox empty", () => string.IsNullOrEmpty(overlay.ChildrenOfType<SearchTextBox>().First().Text)); AddUntilStep("is scrolled to top", () => overlay.ChildrenOfType<OverlayScrollContainer>().First().Current == 0); AddAssert("is visible", () => overlay.State.Value == Visibility.Visible); AddStep("hide", () => InputManager.Key(Key.Escape)); AddUntilStep("is hidden", () => overlay.State.Value == Visibility.Hidden); } [Test] public void TestNoBeatmapsPlaceholder() { AddStep("fetch for 0 beatmaps", () => fetchFor()); AddUntilStep("placeholder shown", () => overlay.ChildrenOfType<BeatmapListingOverlay.NotFoundDrawable>().SingleOrDefault()?.IsPresent == true); AddStep("fetch for 1 beatmap", () => fetchFor(CreateBeatmap(Ruleset.Value).BeatmapInfo.BeatmapSet)); AddUntilStep("placeholder hidden", () => !overlay.ChildrenOfType<BeatmapListingOverlay.NotFoundDrawable>().Any(d => d.IsPresent)); AddStep("fetch for 0 beatmaps", () => fetchFor()); AddUntilStep("placeholder shown", () => overlay.ChildrenOfType<BeatmapListingOverlay.NotFoundDrawable>().SingleOrDefault()?.IsPresent == true); // fetch once more to ensure nothing happens in displaying placeholder again when it already is present. AddStep("fetch for 0 beatmaps again", () => fetchFor()); AddUntilStep("placeholder shown", () => overlay.ChildrenOfType<BeatmapListingOverlay.NotFoundDrawable>().SingleOrDefault()?.IsPresent == true); } [Test] public void TestUserWithoutSupporterUsesSupporterOnlyFiltersWithoutResults() { AddStep("fetch for 0 beatmaps", () => fetchFor()); AddStep("set dummy as non-supporter", () => ((DummyAPIAccess)API).LocalUser.Value.IsSupporter = false); // only Rank Achieved filter setRankAchievedFilter(new[] { ScoreRank.XH }); supporterRequiredPlaceholderShown(); setRankAchievedFilter(Array.Empty<ScoreRank>()); notFoundPlaceholderShown(); // only Played filter setPlayedFilter(SearchPlayed.Played); supporterRequiredPlaceholderShown(); setPlayedFilter(SearchPlayed.Any); notFoundPlaceholderShown(); // both RankAchieved and Played filters setRankAchievedFilter(new[] { ScoreRank.XH }); setPlayedFilter(SearchPlayed.Played); supporterRequiredPlaceholderShown(); setRankAchievedFilter(Array.Empty<ScoreRank>()); setPlayedFilter(SearchPlayed.Any); notFoundPlaceholderShown(); } [Test] public void TestUserWithSupporterUsesSupporterOnlyFiltersWithoutResults() { AddStep("fetch for 0 beatmaps", () => fetchFor()); AddStep("set dummy as supporter", () => ((DummyAPIAccess)API).LocalUser.Value.IsSupporter = true); // only Rank Achieved filter setRankAchievedFilter(new[] { ScoreRank.XH }); notFoundPlaceholderShown(); setRankAchievedFilter(Array.Empty<ScoreRank>()); notFoundPlaceholderShown(); // only Played filter setPlayedFilter(SearchPlayed.Played); notFoundPlaceholderShown(); setPlayedFilter(SearchPlayed.Any); notFoundPlaceholderShown(); // both Rank Achieved and Played filters setRankAchievedFilter(new[] { ScoreRank.XH }); setPlayedFilter(SearchPlayed.Played); notFoundPlaceholderShown(); setRankAchievedFilter(Array.Empty<ScoreRank>()); setPlayedFilter(SearchPlayed.Any); notFoundPlaceholderShown(); } [Test] public void TestUserWithoutSupporterUsesSupporterOnlyFiltersWithResults() { AddStep("fetch for 1 beatmap", () => fetchFor(CreateBeatmap(Ruleset.Value).BeatmapInfo.BeatmapSet)); AddStep("set dummy as non-supporter", () => ((DummyAPIAccess)API).LocalUser.Value.IsSupporter = false); // only Rank Achieved filter setRankAchievedFilter(new[] { ScoreRank.XH }); supporterRequiredPlaceholderShown(); setRankAchievedFilter(Array.Empty<ScoreRank>()); noPlaceholderShown(); // only Played filter setPlayedFilter(SearchPlayed.Played); supporterRequiredPlaceholderShown(); setPlayedFilter(SearchPlayed.Any); noPlaceholderShown(); // both Rank Achieved and Played filters setRankAchievedFilter(new[] { ScoreRank.XH }); setPlayedFilter(SearchPlayed.Played); supporterRequiredPlaceholderShown(); setRankAchievedFilter(Array.Empty<ScoreRank>()); setPlayedFilter(SearchPlayed.Any); noPlaceholderShown(); } [Test] public void TestUserWithSupporterUsesSupporterOnlyFiltersWithResults() { AddStep("fetch for 1 beatmap", () => fetchFor(CreateBeatmap(Ruleset.Value).BeatmapInfo.BeatmapSet)); AddStep("set dummy as supporter", () => ((DummyAPIAccess)API).LocalUser.Value.IsSupporter = true); // only Rank Achieved filter setRankAchievedFilter(new[] { ScoreRank.XH }); noPlaceholderShown(); setRankAchievedFilter(Array.Empty<ScoreRank>()); noPlaceholderShown(); // only Played filter setPlayedFilter(SearchPlayed.Played); noPlaceholderShown(); setPlayedFilter(SearchPlayed.Any); noPlaceholderShown(); // both Rank Achieved and Played filters setRankAchievedFilter(new[] { ScoreRank.XH }); setPlayedFilter(SearchPlayed.Played); noPlaceholderShown(); setRankAchievedFilter(Array.Empty<ScoreRank>()); setPlayedFilter(SearchPlayed.Any); noPlaceholderShown(); } private static int searchCount; private void fetchFor(params BeatmapSetInfo[] beatmaps) { setsForResponse.Clear(); setsForResponse.AddRange(beatmaps.Select(b => new TestAPIBeatmapSet(b))); // trigger arbitrary change for fetching. searchControl.Query.Value = $"search {searchCount++}"; } private void setRankAchievedFilter(ScoreRank[] ranks) { AddStep($"set Rank Achieved filter to [{string.Join(',', ranks)}]", () => { searchControl.Ranks.Clear(); searchControl.Ranks.AddRange(ranks); }); } private void setPlayedFilter(SearchPlayed played) { AddStep($"set Played filter to {played}", () => searchControl.Played.Value = played); } private void supporterRequiredPlaceholderShown() { AddUntilStep("\"supporter required\" placeholder shown", () => overlay.ChildrenOfType<BeatmapListingOverlay.SupporterRequiredDrawable>().SingleOrDefault()?.IsPresent == true); } private void notFoundPlaceholderShown() { AddUntilStep("\"no maps found\" placeholder shown", () => overlay.ChildrenOfType<BeatmapListingOverlay.NotFoundDrawable>().SingleOrDefault()?.IsPresent == true); } private void noPlaceholderShown() { AddUntilStep("no placeholder shown", () => !overlay.ChildrenOfType<BeatmapListingOverlay.SupporterRequiredDrawable>().Any(d => d.IsPresent) && !overlay.ChildrenOfType<BeatmapListingOverlay.NotFoundDrawable>().Any(d => d.IsPresent)); } private class TestAPIBeatmapSet : APIBeatmapSet { private readonly BeatmapSetInfo beatmapSet; public TestAPIBeatmapSet(BeatmapSetInfo beatmapSet) { this.beatmapSet = beatmapSet; } public override BeatmapSetInfo ToBeatmapSet(RulesetStore rulesets) => beatmapSet; } } }
using System; using System.Globalization; using System.IO; using System.Numerics; namespace Json5.Parsing { /// <summary> /// Converts a stream of text into a stream of JSON5 tokens. /// </summary> class Json5Lexer { private Json5TextReader reader; //private State state; /// <summary> /// Contructs a new <see cref="Json5Lexer"/> using a <see cref="string"/>. /// </summary> /// <param name="source">The JSON5 text.</param> public Json5Lexer(string source) : this(new StringReader(source)) { } /// <summary> /// Contructs a new <see cref="Json5Lexer"/> using a <see cref="TextReader"/>. /// </summary> /// <param name="reader">The reader that reads JSON5 text.</param> public Json5Lexer(TextReader reader) { this.reader = new Json5TextReader(reader); } /// <summary> /// Gets the next token in the text. /// </summary> /// <returns>The next token in the text.</returns> public Json5Token Read() { State state = State.Default; string inputBuffer = ""; string valueBuffer = ""; double sign = 1; bool doubleQuote = false; int? line = null; int? column = null; char c; start: int r = this.reader.Peek(); switch (state) { case State.Default: switch (r) { case '\t': case '\v': case '\f': case ' ': case 0x00A0: case 0xFEFF: case '\n': case '\r': case 0x2028: case 0x2029: // Skip whitespace. // More whitespace is checked for at the end // of this switch statement. this.reader.Read(); goto start; case '/': state = State.Comment; this.reader.Read(); goto start; case '$': case '_': // More identifier characters are checked for // at the end of this switch statement. state = State.Identifier; inputBuffer += c = (char)this.reader.Read(); valueBuffer += c; goto start; case '\\': state = State.IdentifierStartEscapeSlash; inputBuffer += (char)this.reader.Read(); goto start; case '{': case '}': case '[': case ']': case ',': case ':': return Token(Json5TokenType.Punctuator, (char)this.reader.Read()); case '+': state = State.Sign; inputBuffer += (char)this.reader.Read(); goto start; case '-': state = State.Sign; sign = -1; inputBuffer += (char)this.reader.Read(); goto start; case '0': state = State.Zero; inputBuffer += (char)this.reader.Read(); goto start; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': state = State.DecimalInteger; inputBuffer += (char)this.reader.Read(); goto start; case '.': state = State.DecimalPointLeading; inputBuffer += (char)this.reader.Read(); goto start; case '"': state = State.String; doubleQuote = true; inputBuffer += (char)this.reader.Read(); line = this.reader.Line; column = this.reader.Column; goto start; case '\'': state = State.String; inputBuffer += (char)this.reader.Read(); line = this.reader.Line; column = this.reader.Column; goto start; case -1: return Token(Json5TokenType.Eof); } if (char.GetUnicodeCategory((char)r) == UnicodeCategory.SpaceSeparator) { // Skip whitespace. this.reader.Read(); goto start; } if (IsLetter((char)r)) { state = State.Identifier; inputBuffer += c = (char)this.reader.Read(); valueBuffer += c; goto start; } throw UnexpectedCharacter((char)r); case State.Comment: switch (r) { case '*': state = State.MultiLineComment; this.reader.Read(); goto start; case '/': state = State.SingleLineComment; this.reader.Read(); goto start; case -1: throw UnexpectedEndOfInput(); } throw UnexpectedCharacter((char)r); case State.MultiLineComment: switch (r) { case '*': state = State.MultiLineCommentAsterisk; break; case -1: throw UnexpectedEndOfInput(); } this.reader.Read(); goto start; case State.MultiLineCommentAsterisk: if (r == -1) throw UnexpectedEndOfInput(); state = r == '/' ? State.Default : State.MultiLineComment; this.reader.Read(); goto start; case State.SingleLineComment: switch (r) { case '\n': case '\r': case 0x2028: case 0x2029: state = State.Default; break; case -1: return Token(Json5TokenType.Eof); } this.reader.Read(); goto start; case State.Identifier: switch (r) { case '$': case '_': inputBuffer += c = (char)this.reader.Read(); valueBuffer += c; goto start; case '\\': state = State.IdentifierEscapeSlash; inputBuffer += (char)this.reader.Read(); goto start; } if (IsIdentifierChar((char)r)) { inputBuffer += c = (char)this.reader.Read(); valueBuffer += c; goto start; } return Token(Json5TokenType.Identifier, valueBuffer, inputBuffer); case State.IdentifierStartEscapeSlash: if (r == -1) throw UnexpectedEndOfInput(); if (r != 'u') throw UnexpectedCharacter((char)r); inputBuffer += (char)this.reader.Read(); string hexBuffer = ""; int count = 4; while (count-- > 0) { if ((r = this.reader.Peek()) == -1) throw UnexpectedEndOfInput(); if (!IsHexDigit(r)) throw UnexpectedCharacter((char)r); inputBuffer += c = (char)this.reader.Read(); hexBuffer += c; } char u = (char)int.Parse(hexBuffer, NumberStyles.HexNumber); if (u == '$' || u == '_' || IsLetter(u)) { state = State.Identifier; valueBuffer += u; goto start; } throw InvalidUnicodeEscape(u); case State.IdentifierEscapeSlash: if (r == -1) throw UnexpectedEndOfInput(); if (r != 'u') throw UnexpectedCharacter((char)r); inputBuffer += (char)this.reader.Read(); hexBuffer = ""; count = 4; while (count-- > 0) { if ((r = this.reader.Peek()) == -1) throw UnexpectedEndOfInput(); if (!IsHexDigit(r)) throw UnexpectedCharacter((char)r); inputBuffer += c = (char)this.reader.Read(); hexBuffer += c; } u = (char)int.Parse(hexBuffer, NumberStyles.HexNumber); if (u == '$' || u == '_' || IsIdentifierChar(u)) { state = State.Identifier; valueBuffer += u; goto start; } throw InvalidUnicodeEscape(u); case State.Sign: switch (r) { case '0': state = State.Zero; inputBuffer += (char)this.reader.Read(); goto start; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': state = State.DecimalInteger; inputBuffer += (char)this.reader.Read(); goto start; case '.': state = State.DecimalPointLeading; inputBuffer += (char)this.reader.Read(); goto start; case 'I': inputBuffer += (char)this.reader.Read(); foreach (char i in "nfinity") { if ((r = this.reader.Peek()) == -1) throw UnexpectedEndOfInput(); if (r != i) throw UnexpectedCharacter((char)r); inputBuffer += (char)this.reader.Read(); } return Token(Json5TokenType.Number, sign * double.PositiveInfinity, inputBuffer); case 'N': inputBuffer += (char)this.reader.Read(); if ((r = this.reader.Peek()) == -1) throw UnexpectedEndOfInput(); if (r != 'a') throw UnexpectedCharacter((char)r); inputBuffer += (char)this.reader.Read(); if ((r = this.reader.Peek()) == -1) throw UnexpectedEndOfInput(); if (r != 'N') throw UnexpectedCharacter((char)r); inputBuffer += (char)this.reader.Read(); return Token(Json5TokenType.Number, double.NaN, inputBuffer); case -1: throw UnexpectedEndOfInput(); } throw UnexpectedCharacter((char)r); case State.Zero: switch (r) { case '.': state = State.DecimalPoint; inputBuffer += (char)this.reader.Read(); goto start; case 'e': case 'E': state = State.DecimalExponent; inputBuffer += (char)this.reader.Read(); goto start; case 'x': case 'X': state = State.Hexadecimal; inputBuffer += (char)this.reader.Read(); valueBuffer = ""; goto start; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': throw Error(new NotSupportedException("Octal numbers are not supported.")); // Node.js supports the following; JSON does not: case '8': case '9': throw Error(new InvalidOperationException("Integer parts must not begin with 0.")); } return Token(Json5TokenType.Number, 0D, inputBuffer); case State.DecimalInteger: switch (r) { case '.': state = State.DecimalPoint; inputBuffer += (char)this.reader.Read(); goto start; case 'e': case 'E': state = State.DecimalExponent; inputBuffer += (char)this.reader.Read(); goto start; } if (IsDigit(r)) { inputBuffer += (char)this.reader.Read(); goto start; } return Token(Json5TokenType.Number, double.Parse(inputBuffer, CultureInfo.InvariantCulture), inputBuffer); case State.DecimalPointLeading: if (r == -1) throw UnexpectedEndOfInput(); if (IsDigit(r)) { state = State.DecimalFraction; inputBuffer += (char)this.reader.Read(); goto start; } throw UnexpectedCharacter((char)r); case State.DecimalPoint: switch (r) { case 'e': case 'E': state = State.DecimalExponent; inputBuffer += (char)this.reader.Read(); goto start; } if (IsDigit(r)) { state = State.DecimalFraction; inputBuffer += (char)this.reader.Read(); goto start; } return Token(Json5TokenType.Number, double.Parse(inputBuffer, CultureInfo.InvariantCulture), inputBuffer); case State.DecimalFraction: switch (r) { case 'e': case 'E': state = State.DecimalExponent; inputBuffer += (char)this.reader.Read(); goto start; } if (IsDigit(r)) { inputBuffer += (char)this.reader.Read(); goto start; } return Token(Json5TokenType.Number, double.Parse(inputBuffer, CultureInfo.InvariantCulture), inputBuffer); case State.DecimalExponent: switch (r) { case '+': case '-': state = State.DecimalExponentSign; inputBuffer += (char)this.reader.Read(); goto start; case -1: throw UnexpectedEndOfInput(); } if (IsDigit(r)) { state = State.DecimalExponentInteger; inputBuffer += (char)this.reader.Read(); goto start; } throw UnexpectedCharacter((char)r); case State.DecimalExponentSign: if (r == -1) throw UnexpectedEndOfInput(); if (IsDigit(r)) { state = State.DecimalExponentInteger; inputBuffer += (char)this.reader.Read(); goto start; } throw UnexpectedCharacter((char)r); case State.DecimalExponentInteger: if (IsDigit(r)) { inputBuffer += (char)this.reader.Read(); goto start; } return Token(Json5TokenType.Number, double.Parse(inputBuffer, CultureInfo.InvariantCulture), inputBuffer); case State.Hexadecimal: if (r == -1) throw UnexpectedEndOfInput(); if (IsHexDigit(r)) { state = State.HexadecimalInteger; inputBuffer += c = (char)this.reader.Read(); valueBuffer += c; goto start; } throw UnexpectedCharacter((char)r); case State.HexadecimalInteger: if (IsHexDigit(r)) { state = State.HexadecimalInteger; inputBuffer += c = (char)this.reader.Read(); valueBuffer += c; goto start; } // Parse this value with BigInteger because ulong can only parse numbers up to 0xFFFFFFFFFFFFFFFF. // Add '0' to valueBuffer since otherwise it will be parsed as signed value (e.g. ff would be -1) return Token(Json5TokenType.Number, sign * (double)BigInteger.Parse("0" + valueBuffer, NumberStyles.HexNumber), inputBuffer); case State.String: switch (r) { case '\\': state = State.Escape; inputBuffer += (char)this.reader.Read(); goto start; case '"': if (doubleQuote) { inputBuffer += (char)this.reader.Read(); return Token(Json5TokenType.String, valueBuffer, inputBuffer, line, column); } inputBuffer += c = (char)this.reader.Read(); valueBuffer += c; goto start; case '\'': if (!doubleQuote) { inputBuffer += (char)this.reader.Read(); return Token(Json5TokenType.String, valueBuffer, inputBuffer, line, column); } inputBuffer += c = (char)this.reader.Read(); valueBuffer += c; goto start; case '\n': case '\r': //case 0x2028: // These are not supported in strings in ES5, but they are in JSON. //case 0x2029: // For backward compatibility, we allow them but never stringify them unescaped. throw UnexpectedCharacter((char)r); case -1: throw UnexpectedEndOfInput(); } inputBuffer += c = (char)this.reader.Read(); valueBuffer += c; goto start; case State.Escape: switch (r) { case 'b': state = State.String; valueBuffer += '\b'; inputBuffer += (char)this.reader.Read(); goto start; case 'f': state = State.String; valueBuffer += '\f'; inputBuffer += (char)this.reader.Read(); goto start; case 'n': state = State.String; valueBuffer += '\n'; inputBuffer += (char)this.reader.Read(); goto start; case 'r': state = State.String; valueBuffer += '\r'; inputBuffer += (char)this.reader.Read(); goto start; case 't': state = State.String; valueBuffer += '\t'; inputBuffer += (char)this.reader.Read(); goto start; case 'v': state = State.String; valueBuffer += '\v'; inputBuffer += (char)this.reader.Read(); goto start; case '0': // lookahead inputBuffer += (char)this.reader.Read(); if (IsDigit(this.reader.Peek())) throw Error(new NotSupportedException("Octal escape sequences are not supported.")); state = State.String; valueBuffer += '\0'; goto start; case '1': case '2': case '3': case '4': case '5': case '6': case '7': throw Error(new NotSupportedException("Octal escape sequences are not supported.")); case '8': case '9': throw UnexpectedCharacter((char)r); case 'x': inputBuffer += (char)this.reader.Read(); hexBuffer = ""; if ((r = this.reader.Peek()) == -1) throw UnexpectedEndOfInput(); if (!IsHexDigit(r)) throw UnexpectedCharacter((char)r); inputBuffer += c = (char)this.reader.Read(); hexBuffer += c; if ((r = this.reader.Peek()) == -1) throw UnexpectedEndOfInput(); if (!IsHexDigit(r)) throw UnexpectedCharacter((char)r); inputBuffer += c = (char)this.reader.Read(); hexBuffer += c; valueBuffer += (char)int.Parse(hexBuffer, NumberStyles.HexNumber); state = State.String; goto start; case 'u': inputBuffer += (char)this.reader.Read(); hexBuffer = ""; count = 4; while (count-- > 0) { if ((r = this.reader.Peek()) == -1) throw UnexpectedEndOfInput(); if (!IsHexDigit(r)) throw UnexpectedCharacter((char)r); inputBuffer += c = (char)this.reader.Read(); hexBuffer += c; } valueBuffer += (char)int.Parse(hexBuffer, NumberStyles.HexNumber); state = State.String; goto start; case '\n': case '\r': case 0x2028: case 0x2029: state = State.String; inputBuffer += (char)this.reader.Read(); if (r == '\r' && this.reader.Peek() == '\n') inputBuffer += (char)this.reader.Read(); goto start; case -1: throw UnexpectedEndOfInput(); } state = State.String; inputBuffer += c = (char)this.reader.Read(); valueBuffer += c; goto start; } // If this happens, it's a programming error. throw Error(new InvalidOperationException("Invalid lexer state")); } /// <summary> /// Determines whether a character is a decimal digit. /// </summary> /// <param name="c">The character to test.</param> /// <returns><c>true</c> if <paramref name="c"/> is a digit; otherwise, <c>false</c>.</returns> static bool IsDigit(int c) { switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return true; } return false; } /// <summary> /// Determins whether a character is a hexadecimal digit. /// </summary> /// <param name="c">The character to test.</param> /// <returns><c>true</c> if <paramref name="c"/> is a hexadecimal digit; otherwise, <c>false</c>.</returns> static bool IsHexDigit(int c) { switch (c) { case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': return true; } return IsDigit(c); } /// <summary> /// Determines whether a character is a Unicode letter character. /// </summary> /// <param name="c">The character to test.</param> /// <returns><c>true</c> if <paramref name="c"/> is a Unicode letter character; otherwise, <c>false</c>.</returns> static bool IsLetter(char c) { return char.IsLetter(c) || char.GetUnicodeCategory(c) == UnicodeCategory.LetterNumber; } /// <summary> /// Determines whether a character is an ECMAScript 5.1 Unicode identifier character. /// </summary> /// <param name="c">The character to test.</param> /// <returns><c>true</c> if <paramref name="c"/> is an ECMAScript 5.1 Unicode identifier character; otherwise, <c>false</c>.</returns> static bool IsIdentifierChar(char c) { switch (char.GetUnicodeCategory(c)) { case UnicodeCategory.NonSpacingMark: case UnicodeCategory.SpacingCombiningMark: case UnicodeCategory.DecimalDigitNumber: case UnicodeCategory.ConnectorPunctuation: return true; } return IsLetter(c); } Json5Token Token(Json5TokenType type, object value = null, string input = null, int? line = null, int? column = null) { if (value != null) { input = input ?? value.ToString(); column = column ?? this.reader.Column - input.Length; } return new Json5Token { Type = type, Value = value, Input = input, Line = line ?? this.reader.Line, Column = column ?? this.reader.Column }; } /// <summary> /// Returns a <see cref="SyntaxError"/> for an unexpected character. /// </summary> /// <param name="c">The unexpected character.</param> /// <returns>A <see cref="SyntaxError"/> for <paramref name="c"/>.</returns> Json5UnexpectedInputException UnexpectedCharacter(char c) { this.reader.Read(); return new Json5UnexpectedInputException(c.ToString(), this.reader.Line, this.reader.Column); } Json5UnexpectedEndOfInputException UnexpectedEndOfInput() { return new Json5UnexpectedEndOfInputException(this.reader.Line, this.reader.Column); } Json5ParsingException Error(Exception innerException) { this.reader.Read(); return new Json5ParsingException(innerException, this.reader.Line, this.reader.Column); } Json5ParsingException InvalidUnicodeEscape(char u) { this.reader.Read(); return new Json5ParsingException(string.Format("Invalid unicode escape sequence '\\u{0}' in object key.", ((int)u).ToString("x4")), this.reader.Line, this.reader.Column - 6); } /// <summary> /// Represents a state that a <see cref="Json5Lexer"/> is in. /// </summary> enum State { Default, Comment, MultiLineComment, MultiLineCommentAsterisk, SingleLineComment, Identifier, IdentifierStartEscapeSlash, IdentifierEscapeSlash, Sign, Zero, DecimalInteger, DecimalPointLeading, DecimalPoint, DecimalFraction, DecimalExponent, DecimalExponentSign, DecimalExponentInteger, Hexadecimal, HexadecimalInteger, String, Escape, } } }
// CRC32.cs // ------------------------------------------------------------------ // // Copyright (c) 2011 Dino Chiesa. // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // Last Saved: <2011-August-02 18:25:54> // // ------------------------------------------------------------------ // // This module defines the CRC32 class, which can do the CRC32 algorithm, using // arbitrary starting polynomials, and bit reversal. The bit reversal is what // distinguishes this CRC-32 used in BZip2 from the CRC-32 that is used in PKZIP // files, or GZIP files. This class does both. // // ------------------------------------------------------------------ using System; using Interop = System.Runtime.InteropServices; namespace Ionic.Crc { /// <summary> /// Computes a CRC-32. The CRC-32 algorithm is parameterized - you /// can set the polynomial and enable or disable bit /// reversal. This can be used for GZIP, BZip2, or ZIP. /// </summary> /// <remarks> /// This type is used internally by DotNetZip; it is generally not used /// directly by applications wishing to create, read, or manipulate zip /// archive files. /// </remarks> [Interop.GuidAttribute("ebc25cf6-9120-4283-b972-0e5520d0000C")] [Interop.ComVisible(true)] #if !NETCF [Interop.ClassInterface(Interop.ClassInterfaceType.AutoDispatch)] #endif public class CRC32 { /// <summary> /// Indicates the total number of bytes applied to the CRC. /// </summary> public Int64 TotalBytesRead { get { return _TotalBytesRead; } } /// <summary> /// Indicates the current CRC for all blocks slurped in. /// </summary> public Int32 Crc32Result { get { return unchecked((Int32)(~_register)); } } /// <summary> /// Returns the CRC32 for the specified stream. /// </summary> /// <param name="input">The stream over which to calculate the CRC32</param> /// <returns>the CRC32 calculation</returns> public Int32 GetCrc32(System.IO.Stream input) { return GetCrc32AndCopy(input, null); } /// <summary> /// Returns the CRC32 for the specified stream, and writes the input into the /// output stream. /// </summary> /// <param name="input">The stream over which to calculate the CRC32</param> /// <param name="output">The stream into which to deflate the input</param> /// <returns>the CRC32 calculation</returns> public Int32 GetCrc32AndCopy(System.IO.Stream input, System.IO.Stream output) { if (input == null) throw new Exception("The input stream must not be null."); unchecked { byte[] buffer = new byte[BUFFER_SIZE]; int readSize = BUFFER_SIZE; _TotalBytesRead = 0; int count = input.Read(buffer, 0, readSize); if (output != null) output.Write(buffer, 0, count); _TotalBytesRead += count; while (count > 0) { SlurpBlock(buffer, 0, count); count = input.Read(buffer, 0, readSize); if (output != null) output.Write(buffer, 0, count); _TotalBytesRead += count; } return (Int32)(~_register); } } /// <summary> /// Get the CRC32 for the given (word,byte) combo. This is a /// computation defined by PKzip for PKZIP 2.0 (weak) encryption. /// </summary> /// <param name="W">The word to start with.</param> /// <param name="B">The byte to combine it with.</param> /// <returns>The CRC-ized result.</returns> public Int32 ComputeCrc32(Int32 W, byte B) { return _InternalComputeCrc32((UInt32)W, B); } internal Int32 _InternalComputeCrc32(UInt32 W, byte B) { return (Int32)(crc32Table[(W ^ B) & 0xFF] ^ (W >> 8)); } /// <summary> /// Update the value for the running CRC32 using the given block of bytes. /// This is useful when using the CRC32() class in a Stream. /// </summary> /// <param name="block">block of bytes to slurp</param> /// <param name="offset">starting point in the block</param> /// <param name="count">how many bytes within the block to slurp</param> public void SlurpBlock(byte[] block, int offset, int count) { if (block == null) throw new Exception("The data buffer must not be null."); // bzip algorithm for (int i = 0; i < count; i++) { int x = offset + i; byte b = block[x]; if (this.reverseBits) { UInt32 temp = (_register >> 24) ^ b; _register = (_register << 8) ^ crc32Table[temp]; } else { UInt32 temp = (_register & 0x000000FF) ^ b; _register = (_register >> 8) ^ crc32Table[temp]; } } _TotalBytesRead += count; } /// <summary> /// Process one byte in the CRC. /// </summary> /// <param name = "b">the byte to include into the CRC . </param> public void UpdateCRC(byte b) { if (this.reverseBits) { UInt32 temp = (_register >> 24) ^ b; _register = (_register << 8) ^ crc32Table[temp]; } else { UInt32 temp = (_register & 0x000000FF) ^ b; _register = (_register >> 8) ^ crc32Table[temp]; } } /// <summary> /// Process a run of N identical bytes into the CRC. /// </summary> /// <remarks> /// <para> /// This method serves as an optimization for updating the CRC when a /// run of identical bytes is found. Rather than passing in a buffer of /// length n, containing all identical bytes b, this method accepts the /// byte value and the length of the (virtual) buffer - the length of /// the run. /// </para> /// </remarks> /// <param name = "b">the byte to include into the CRC. </param> /// <param name = "n">the number of times that byte should be repeated. </param> public void UpdateCRC(byte b, int n) { while (n-- > 0) { if (this.reverseBits) { uint temp = (_register >> 24) ^ b; _register = (_register << 8) ^ crc32Table[(temp >= 0) ? temp : (temp + 256)]; } else { UInt32 temp = (_register & 0x000000FF) ^ b; _register = (_register >> 8) ^ crc32Table[(temp >= 0) ? temp : (temp + 256)]; } } } private static uint ReverseBits(uint data) { unchecked { uint ret = data; ret = (ret & 0x55555555) << 1 | (ret >> 1) & 0x55555555; ret = (ret & 0x33333333) << 2 | (ret >> 2) & 0x33333333; ret = (ret & 0x0F0F0F0F) << 4 | (ret >> 4) & 0x0F0F0F0F; ret = (ret << 24) | ((ret & 0xFF00) << 8) | ((ret >> 8) & 0xFF00) | (ret >> 24); return ret; } } private static byte ReverseBits(byte data) { unchecked { uint u = (uint)data * 0x00020202; uint m = 0x01044010; uint s = u & m; uint t = (u << 2) & (m << 1); return (byte)((0x01001001 * (s + t)) >> 24); } } private void GenerateLookupTable() { crc32Table = new UInt32[256]; unchecked { UInt32 dwCrc; byte i = 0; do { dwCrc = i; for (byte j = 8; j > 0; j--) { if ((dwCrc & 1) == 1) { dwCrc = (dwCrc >> 1) ^ dwPolynomial; } else { dwCrc >>= 1; } } if (reverseBits) { crc32Table[ReverseBits(i)] = ReverseBits(dwCrc); } else { crc32Table[i] = dwCrc; } i++; } while (i!=0); } #if VERBOSE Console.WriteLine(); Console.WriteLine("private static readonly UInt32[] crc32Table = {"); for (int i = 0; i < crc32Table.Length; i+=4) { Console.Write(" "); for (int j=0; j < 4; j++) { Console.Write(" 0x{0:X8}U,", crc32Table[i+j]); } Console.WriteLine(); } Console.WriteLine("};"); Console.WriteLine(); #endif } private uint gf2_matrix_times(uint[] matrix, uint vec) { uint sum = 0; int i=0; while (vec != 0) { if ((vec & 0x01)== 0x01) sum ^= matrix[i]; vec >>= 1; i++; } return sum; } private void gf2_matrix_square(uint[] square, uint[] mat) { for (int i = 0; i < 32; i++) square[i] = gf2_matrix_times(mat, mat[i]); } /// <summary> /// Combines the given CRC32 value with the current running total. /// </summary> /// <remarks> /// This is useful when using a divide-and-conquer approach to /// calculating a CRC. Multiple threads can each calculate a /// CRC32 on a segment of the data, and then combine the /// individual CRC32 values at the end. /// </remarks> /// <param name="crc">the crc value to be combined with this one</param> /// <param name="length">the length of data the CRC value was calculated on</param> public void Combine(int crc, int length) { uint[] even = new uint[32]; // even-power-of-two zeros operator uint[] odd = new uint[32]; // odd-power-of-two zeros operator if (length == 0) return; uint crc1= ~_register; uint crc2= (uint) crc; // put operator for one zero bit in odd odd[0] = this.dwPolynomial; // the CRC-32 polynomial uint row = 1; for (int i = 1; i < 32; i++) { odd[i] = row; row <<= 1; } // put operator for two zero bits in even gf2_matrix_square(even, odd); // put operator for four zero bits in odd gf2_matrix_square(odd, even); uint len2 = (uint) length; // apply len2 zeros to crc1 (first square will put the operator for one // zero byte, eight zero bits, in even) do { // apply zeros operator for this bit of len2 gf2_matrix_square(even, odd); if ((len2 & 1)== 1) crc1 = gf2_matrix_times(even, crc1); len2 >>= 1; if (len2 == 0) break; // another iteration of the loop with odd and even swapped gf2_matrix_square(odd, even); if ((len2 & 1)==1) crc1 = gf2_matrix_times(odd, crc1); len2 >>= 1; } while (len2 != 0); crc1 ^= crc2; _register= ~crc1; //return (int) crc1; return; } /// <summary> /// Create an instance of the CRC32 class using the default settings: no /// bit reversal, and a polynomial of 0xEDB88320. /// </summary> public CRC32() : this(false) { } /// <summary> /// Create an instance of the CRC32 class, specifying whether to reverse /// data bits or not. /// </summary> /// <param name='reverseBits'> /// specify true if the instance should reverse data bits. /// </param> /// <remarks> /// <para> /// In the CRC-32 used by BZip2, the bits are reversed. Therefore if you /// want a CRC32 with compatibility with BZip2, you should pass true /// here. In the CRC-32 used by GZIP and PKZIP, the bits are not /// reversed; Therefore if you want a CRC32 with compatibility with /// those, you should pass false. /// </para> /// </remarks> public CRC32(bool reverseBits) : this( unchecked((int)0xEDB88320), reverseBits) { } /// <summary> /// Create an instance of the CRC32 class, specifying the polynomial and /// whether to reverse data bits or not. /// </summary> /// <param name='polynomial'> /// The polynomial to use for the CRC, expressed in the reversed (LSB) /// format: the highest ordered bit in the polynomial value is the /// coefficient of the 0th power; the second-highest order bit is the /// coefficient of the 1 power, and so on. Expressed this way, the /// polynomial for the CRC-32C used in IEEE 802.3, is 0xEDB88320. /// </param> /// <param name='reverseBits'> /// specify true if the instance should reverse data bits. /// </param> /// /// <remarks> /// <para> /// In the CRC-32 used by BZip2, the bits are reversed. Therefore if you /// want a CRC32 with compatibility with BZip2, you should pass true /// here for the <c>reverseBits</c> parameter. In the CRC-32 used by /// GZIP and PKZIP, the bits are not reversed; Therefore if you want a /// CRC32 with compatibility with those, you should pass false for the /// <c>reverseBits</c> parameter. /// </para> /// </remarks> public CRC32(int polynomial, bool reverseBits) { this.reverseBits = reverseBits; this.dwPolynomial = (uint) polynomial; this.GenerateLookupTable(); } /// <summary> /// Reset the CRC-32 class - clear the CRC "remainder register." /// </summary> /// <remarks> /// <para> /// Use this when employing a single instance of this class to compute /// multiple, distinct CRCs on multiple, distinct data blocks. /// </para> /// </remarks> public void Reset() { _register = 0xFFFFFFFFU; } // private member vars private UInt32 dwPolynomial; private Int64 _TotalBytesRead; private bool reverseBits; private UInt32[] crc32Table; private const int BUFFER_SIZE = 8192; private UInt32 _register = 0xFFFFFFFFU; } /// <summary> /// A Stream that calculates a CRC32 (a checksum) on all bytes read, /// or on all bytes written. /// </summary> /// /// <remarks> /// <para> /// This class can be used to verify the CRC of a ZipEntry when /// reading from a stream, or to calculate a CRC when writing to a /// stream. The stream should be used to either read, or write, but /// not both. If you intermix reads and writes, the results are not /// defined. /// </para> /// /// <para> /// This class is intended primarily for use internally by the /// DotNetZip library. /// </para> /// </remarks> public class CrcCalculatorStream : System.IO.Stream, System.IDisposable { private static readonly Int64 UnsetLengthLimit = -99; internal System.IO.Stream _innerStream; private CRC32 _Crc32; private Int64 _lengthLimit = -99; private bool _leaveOpen; /// <summary> /// The default constructor. /// </summary> /// <remarks> /// <para> /// Instances returned from this constructor will leave the underlying /// stream open upon Close(). The stream uses the default CRC32 /// algorithm, which implies a polynomial of 0xEDB88320. /// </para> /// </remarks> /// <param name="stream">The underlying stream</param> public CrcCalculatorStream(System.IO.Stream stream) : this(true, CrcCalculatorStream.UnsetLengthLimit, stream, null) { } /// <summary> /// The constructor allows the caller to specify how to handle the /// underlying stream at close. /// </summary> /// <remarks> /// <para> /// The stream uses the default CRC32 algorithm, which implies a /// polynomial of 0xEDB88320. /// </para> /// </remarks> /// <param name="stream">The underlying stream</param> /// <param name="leaveOpen">true to leave the underlying stream /// open upon close of the <c>CrcCalculatorStream</c>; false otherwise.</param> public CrcCalculatorStream(System.IO.Stream stream, bool leaveOpen) : this(leaveOpen, CrcCalculatorStream.UnsetLengthLimit, stream, null) { } /// <summary> /// A constructor allowing the specification of the length of the stream /// to read. /// </summary> /// <remarks> /// <para> /// The stream uses the default CRC32 algorithm, which implies a /// polynomial of 0xEDB88320. /// </para> /// <para> /// Instances returned from this constructor will leave the underlying /// stream open upon Close(). /// </para> /// </remarks> /// <param name="stream">The underlying stream</param> /// <param name="length">The length of the stream to slurp</param> public CrcCalculatorStream(System.IO.Stream stream, Int64 length) : this(true, length, stream, null) { if (length < 0) throw new ArgumentException("length"); } /// <summary> /// A constructor allowing the specification of the length of the stream /// to read, as well as whether to keep the underlying stream open upon /// Close(). /// </summary> /// <remarks> /// <para> /// The stream uses the default CRC32 algorithm, which implies a /// polynomial of 0xEDB88320. /// </para> /// </remarks> /// <param name="stream">The underlying stream</param> /// <param name="length">The length of the stream to slurp</param> /// <param name="leaveOpen">true to leave the underlying stream /// open upon close of the <c>CrcCalculatorStream</c>; false otherwise.</param> public CrcCalculatorStream(System.IO.Stream stream, Int64 length, bool leaveOpen) : this(leaveOpen, length, stream, null) { if (length < 0) throw new ArgumentException("length"); } /// <summary> /// A constructor allowing the specification of the length of the stream /// to read, as well as whether to keep the underlying stream open upon /// Close(), and the CRC32 instance to use. /// </summary> /// <remarks> /// <para> /// The stream uses the specified CRC32 instance, which allows the /// application to specify how the CRC gets calculated. /// </para> /// </remarks> /// <param name="stream">The underlying stream</param> /// <param name="length">The length of the stream to slurp</param> /// <param name="leaveOpen">true to leave the underlying stream /// open upon close of the <c>CrcCalculatorStream</c>; false otherwise.</param> /// <param name="crc32">the CRC32 instance to use to calculate the CRC32</param> public CrcCalculatorStream(System.IO.Stream stream, Int64 length, bool leaveOpen, CRC32 crc32) : this(leaveOpen, length, stream, crc32) { if (length < 0) throw new ArgumentException("length"); } // This ctor is private - no validation is done here. This is to allow the use // of a (specific) negative value for the _lengthLimit, to indicate that there // is no length set. So we validate the length limit in those ctors that use an // explicit param, otherwise we don't validate, because it could be our special // value. private CrcCalculatorStream (bool leaveOpen, Int64 length, System.IO.Stream stream, CRC32 crc32) : base() { _innerStream = stream; _Crc32 = crc32 ?? new CRC32(); _lengthLimit = length; _leaveOpen = leaveOpen; } /// <summary> /// Gets the total number of bytes run through the CRC32 calculator. /// </summary> /// /// <remarks> /// This is either the total number of bytes read, or the total number of /// bytes written, depending on the direction of this stream. /// </remarks> public Int64 TotalBytesSlurped { get { return _Crc32.TotalBytesRead; } } /// <summary> /// Provides the current CRC for all blocks slurped in. /// </summary> /// <remarks> /// <para> /// The running total of the CRC is kept as data is written or read /// through the stream. read this property after all reads or writes to /// get an accurate CRC for the entire stream. /// </para> /// </remarks> public Int32 Crc { get { return _Crc32.Crc32Result; } } /// <summary> /// Indicates whether the underlying stream will be left open when the /// <c>CrcCalculatorStream</c> is Closed. /// </summary> /// <remarks> /// <para> /// Set this at any point before calling <see cref="Close()"/>. /// </para> /// </remarks> public bool LeaveOpen { get { return _leaveOpen; } set { _leaveOpen = value; } } /// <summary> /// Read from the stream /// </summary> /// <param name="buffer">the buffer to read</param> /// <param name="offset">the offset at which to start</param> /// <param name="count">the number of bytes to read</param> /// <returns>the number of bytes actually read</returns> public override int Read(byte[] buffer, int offset, int count) { int bytesToRead = count; // Need to limit the # of bytes returned, if the stream is intended to have // a definite length. This is especially useful when returning a stream for // the uncompressed data directly to the application. The app won't // necessarily read only the UncompressedSize number of bytes. For example // wrapping the stream returned from OpenReader() into a StreadReader() and // calling ReadToEnd() on it, We can "over-read" the zip data and get a // corrupt string. The length limits that, prevents that problem. if (_lengthLimit != CrcCalculatorStream.UnsetLengthLimit) { if (_Crc32.TotalBytesRead >= _lengthLimit) return 0; // EOF Int64 bytesRemaining = _lengthLimit - _Crc32.TotalBytesRead; if (bytesRemaining < count) bytesToRead = (int)bytesRemaining; } int n = _innerStream.Read(buffer, offset, bytesToRead); if (n > 0) _Crc32.SlurpBlock(buffer, offset, n); return n; } /// <summary> /// Write to the stream. /// </summary> /// <param name="buffer">the buffer from which to write</param> /// <param name="offset">the offset at which to start writing</param> /// <param name="count">the number of bytes to write</param> public override void Write(byte[] buffer, int offset, int count) { if (count > 0) _Crc32.SlurpBlock(buffer, offset, count); _innerStream.Write(buffer, offset, count); } /// <summary> /// Indicates whether the stream supports reading. /// </summary> public override bool CanRead { get { return _innerStream.CanRead; } } /// <summary> /// Indicates whether the stream supports seeking. /// </summary> /// <remarks> /// <para> /// Always returns false. /// </para> /// </remarks> public override bool CanSeek { get { return false; } } /// <summary> /// Indicates whether the stream supports writing. /// </summary> public override bool CanWrite { get { return _innerStream.CanWrite; } } /// <summary> /// Flush the stream. /// </summary> public override void Flush() { _innerStream.Flush(); } /// <summary> /// Returns the length of the underlying stream. /// </summary> public override long Length { get { if (_lengthLimit == CrcCalculatorStream.UnsetLengthLimit) return _innerStream.Length; else return _lengthLimit; } } /// <summary> /// The getter for this property returns the total bytes read. /// If you use the setter, it will throw /// <see cref="NotSupportedException"/>. /// </summary> public override long Position { get { return _Crc32.TotalBytesRead; } set { throw new NotSupportedException(); } } /// <summary> /// Seeking is not supported on this stream. This method always throws /// <see cref="NotSupportedException"/> /// </summary> /// <param name="offset">N/A</param> /// <param name="origin">N/A</param> /// <returns>N/A</returns> public override long Seek(long offset, System.IO.SeekOrigin origin) { throw new NotSupportedException(); } /// <summary> /// This method always throws /// <see cref="NotSupportedException"/> /// </summary> /// <param name="value">N/A</param> public override void SetLength(long value) { throw new NotSupportedException(); } void IDisposable.Dispose() { Close(); } /// <summary> /// Closes the stream. /// </summary> public override void Close() { base.Close(); if (!_leaveOpen) _innerStream.Close(); } } }
using System.Collections; using System.Collections.Generic; using System.Diagnostics; namespace Lucene.Net.Index { using Lucene.Net.Support; using System; using Bits = Lucene.Net.Util.Bits; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using BytesRef = Lucene.Net.Util.BytesRef; /// <summary> /// Exposes <seealso cref="TermsEnum"/> API, merged from <seealso cref="TermsEnum"/> API of sub-segments. /// this does a merge sort, by term text, of the sub-readers. /// /// @lucene.experimental /// </summary> public sealed class MultiTermsEnum : TermsEnum { private readonly TermMergeQueue Queue; private readonly TermsEnumWithSlice[] Subs; // all of our subs (one per sub-reader) private readonly TermsEnumWithSlice[] CurrentSubs; // current subs that have at least one term for this field private readonly TermsEnumWithSlice[] Top; private readonly MultiDocsEnum.EnumWithSlice[] SubDocs; private readonly MultiDocsAndPositionsEnum.EnumWithSlice[] SubDocsAndPositions; private BytesRef LastSeek; private bool LastSeekExact; private readonly BytesRef LastSeekScratch = new BytesRef(); private int NumTop; private int NumSubs; private BytesRef Current; private IComparer<BytesRef> TermComp; public class TermsEnumIndex { public static readonly TermsEnumIndex[] EMPTY_ARRAY = new TermsEnumIndex[0]; internal readonly int SubIndex; internal readonly TermsEnum TermsEnum; public TermsEnumIndex(TermsEnum termsEnum, int subIndex) { this.TermsEnum = termsEnum; this.SubIndex = subIndex; } } /// <summary> /// Returns how many sub-reader slices contain the current </summary> /// term. <seealso cref= #getMatchArray </seealso> public int MatchCount { get { return NumTop; } } /// <summary> /// Returns sub-reader slices positioned to the current term. </summary> public TermsEnumWithSlice[] MatchArray { get { return Top; } } /// <summary> /// Sole constructor. </summary> /// <param name="slices"> Which sub-reader slices we should /// merge. </param> public MultiTermsEnum(ReaderSlice[] slices) { Queue = new TermMergeQueue(slices.Length); Top = new TermsEnumWithSlice[slices.Length]; Subs = new TermsEnumWithSlice[slices.Length]; SubDocs = new MultiDocsEnum.EnumWithSlice[slices.Length]; SubDocsAndPositions = new MultiDocsAndPositionsEnum.EnumWithSlice[slices.Length]; for (int i = 0; i < slices.Length; i++) { Subs[i] = new TermsEnumWithSlice(i, slices[i]); SubDocs[i] = new MultiDocsEnum.EnumWithSlice(); SubDocs[i].Slice = slices[i]; SubDocsAndPositions[i] = new MultiDocsAndPositionsEnum.EnumWithSlice(); SubDocsAndPositions[i].Slice = slices[i]; } CurrentSubs = new TermsEnumWithSlice[slices.Length]; } public override BytesRef Term() { return Current; } public override IComparer<BytesRef> Comparator { get { return TermComp; } } /// <summary> /// The terms array must be newly created TermsEnum, ie /// <seealso cref="TermsEnum#next"/> has not yet been called. /// </summary> public TermsEnum Reset(TermsEnumIndex[] termsEnumsIndex) { Debug.Assert(termsEnumsIndex.Length <= Top.Length); NumSubs = 0; NumTop = 0; TermComp = null; Queue.Clear(); for (int i = 0; i < termsEnumsIndex.Length; i++) { TermsEnumIndex termsEnumIndex = termsEnumsIndex[i]; Debug.Assert(termsEnumIndex != null); // init our term comp if (TermComp == null) { Queue.TermComp = TermComp = termsEnumIndex.TermsEnum.Comparator; } else { // We cannot merge sub-readers that have // different TermComps IComparer<BytesRef> subTermComp = termsEnumIndex.TermsEnum.Comparator; if (subTermComp != null && !subTermComp.Equals(TermComp)) { throw new InvalidOperationException("sub-readers have different BytesRef.Comparators: " + subTermComp + " vs " + TermComp + "; cannot merge"); } } BytesRef term = termsEnumIndex.TermsEnum.Next(); if (term != null) { TermsEnumWithSlice entry = Subs[termsEnumIndex.SubIndex]; entry.Reset(termsEnumIndex.TermsEnum, term); Queue.Add(entry); CurrentSubs[NumSubs++] = entry; } else { // field has no terms } } if (Queue.Size() == 0) { return TermsEnum.EMPTY; } else { return this; } } public override bool SeekExact(BytesRef term) { Queue.Clear(); NumTop = 0; bool seekOpt = false; if (LastSeek != null && TermComp.Compare(LastSeek, term) <= 0) { seekOpt = true; } LastSeek = null; LastSeekExact = true; for (int i = 0; i < NumSubs; i++) { bool status; // LUCENE-2130: if we had just seek'd already, prior // to this seek, and the new seek term is after the // previous one, don't try to re-seek this sub if its // current term is already beyond this new seek term. // Doing so is a waste because this sub will simply // seek to the same spot. if (seekOpt) { BytesRef curTerm = CurrentSubs[i].Current; if (curTerm != null) { int cmp = TermComp.Compare(term, curTerm); if (cmp == 0) { status = true; } else if (cmp < 0) { status = false; } else { status = CurrentSubs[i].Terms.SeekExact(term); } } else { status = false; } } else { status = CurrentSubs[i].Terms.SeekExact(term); } if (status) { Top[NumTop++] = CurrentSubs[i]; Current = CurrentSubs[i].Current = CurrentSubs[i].Terms.Term(); Debug.Assert(term.Equals(CurrentSubs[i].Current)); } } // if at least one sub had exact match to the requested // term then we found match return NumTop > 0; } public override SeekStatus SeekCeil(BytesRef term) { Queue.Clear(); NumTop = 0; LastSeekExact = false; bool seekOpt = false; if (LastSeek != null && TermComp.Compare(LastSeek, term) <= 0) { seekOpt = true; } LastSeekScratch.CopyBytes(term); LastSeek = LastSeekScratch; for (int i = 0; i < NumSubs; i++) { SeekStatus status; // LUCENE-2130: if we had just seek'd already, prior // to this seek, and the new seek term is after the // previous one, don't try to re-seek this sub if its // current term is already beyond this new seek term. // Doing so is a waste because this sub will simply // seek to the same spot. if (seekOpt) { BytesRef curTerm = CurrentSubs[i].Current; if (curTerm != null) { int cmp = TermComp.Compare(term, curTerm); if (cmp == 0) { status = SeekStatus.FOUND; } else if (cmp < 0) { status = SeekStatus.NOT_FOUND; } else { status = CurrentSubs[i].Terms.SeekCeil(term); } } else { status = SeekStatus.END; } } else { status = CurrentSubs[i].Terms.SeekCeil(term); } if (status == SeekStatus.FOUND) { Top[NumTop++] = CurrentSubs[i]; Current = CurrentSubs[i].Current = CurrentSubs[i].Terms.Term(); } else { if (status == SeekStatus.NOT_FOUND) { CurrentSubs[i].Current = CurrentSubs[i].Terms.Term(); Debug.Assert(CurrentSubs[i].Current != null); Queue.Add(CurrentSubs[i]); } else { // enum exhausted CurrentSubs[i].Current = null; } } } if (NumTop > 0) { // at least one sub had exact match to the requested term return SeekStatus.FOUND; } else if (Queue.Size() > 0) { // no sub had exact match, but at least one sub found // a term after the requested term -- advance to that // next term: PullTop(); return SeekStatus.NOT_FOUND; } else { return SeekStatus.END; } } public override void SeekExact(long ord) { throw new System.NotSupportedException(); } public override long Ord() { throw new System.NotSupportedException(); } private void PullTop() { // extract all subs from the queue that have the same // top term Debug.Assert(NumTop == 0); while (true) { Top[NumTop++] = Queue.Pop(); if (Queue.Size() == 0 || !(Queue.Top()).Current.BytesEquals(Top[0].Current)) { break; } } Current = Top[0].Current; } private void PushTop() { // call next() on each top, and put back into queue for (int i = 0; i < NumTop; i++) { Top[i].Current = Top[i].Terms.Next(); if (Top[i].Current != null) { Queue.Add(Top[i]); } else { // no more fields in this reader } } NumTop = 0; } public override BytesRef Next() { if (LastSeekExact) { // Must SeekCeil at this point, so those subs that // didn't have the term can find the following term. // NOTE: we could save some CPU by only SeekCeil the // subs that didn't match the last exact seek... but // most impls short-circuit if you SeekCeil to term // they are already on. SeekStatus status = SeekCeil(Current); Debug.Assert(status == SeekStatus.FOUND); LastSeekExact = false; } LastSeek = null; // restore queue PushTop(); // gather equal top fields if (Queue.Size() > 0) { PullTop(); } else { Current = null; } return Current; } public override int DocFreq() { int sum = 0; for (int i = 0; i < NumTop; i++) { sum += Top[i].Terms.DocFreq(); } return sum; } public override long TotalTermFreq() { long sum = 0; for (int i = 0; i < NumTop; i++) { long v = Top[i].Terms.TotalTermFreq(); if (v == -1) { return v; } sum += v; } return sum; } public override DocsEnum Docs(Bits liveDocs, DocsEnum reuse, int flags) { MultiDocsEnum docsEnum; // Can only reuse if incoming enum is also a MultiDocsEnum if (reuse != null && reuse is MultiDocsEnum) { docsEnum = (MultiDocsEnum)reuse; // ... and was previously created w/ this MultiTermsEnum: if (!docsEnum.CanReuse(this)) { docsEnum = new MultiDocsEnum(this, Subs.Length); } } else { docsEnum = new MultiDocsEnum(this, Subs.Length); } MultiBits multiLiveDocs; if (liveDocs is MultiBits) { multiLiveDocs = (MultiBits)liveDocs; } else { multiLiveDocs = null; } int upto = 0; for (int i = 0; i < NumTop; i++) { TermsEnumWithSlice entry = Top[i]; Bits b; if (multiLiveDocs != null) { // optimize for common case: requested skip docs is a // congruent sub-slice of MultiBits: in this case, we // just pull the liveDocs from the sub reader, rather // than making the inefficient // Slice(Multi(sub-readers)): MultiBits.SubResult sub = multiLiveDocs.GetMatchingSub(entry.SubSlice); if (sub.Matches) { b = sub.Result; } else { // custom case: requested skip docs is foreign: // must slice it on every access b = new BitsSlice(liveDocs, entry.SubSlice); } } else if (liveDocs != null) { b = new BitsSlice(liveDocs, entry.SubSlice); } else { // no deletions b = null; } Debug.Assert(entry.Index < docsEnum.SubDocsEnum.Length, entry.Index + " vs " + docsEnum.SubDocsEnum.Length + "; " + Subs.Length); DocsEnum subDocsEnum = entry.Terms.Docs(b, docsEnum.SubDocsEnum[entry.Index], flags); if (subDocsEnum != null) { docsEnum.SubDocsEnum[entry.Index] = subDocsEnum; SubDocs[upto].DocsEnum = subDocsEnum; SubDocs[upto].Slice = entry.SubSlice; upto++; } else { // should this be an error? Debug.Assert(false, "One of our subs cannot provide a docsenum"); } } if (upto == 0) { return null; } else { return docsEnum.Reset(SubDocs, upto); } } public override DocsAndPositionsEnum DocsAndPositions(Bits liveDocs, DocsAndPositionsEnum reuse, int flags) { MultiDocsAndPositionsEnum docsAndPositionsEnum; // Can only reuse if incoming enum is also a MultiDocsAndPositionsEnum if (reuse != null && reuse is MultiDocsAndPositionsEnum) { docsAndPositionsEnum = (MultiDocsAndPositionsEnum)reuse; // ... and was previously created w/ this MultiTermsEnum: if (!docsAndPositionsEnum.CanReuse(this)) { docsAndPositionsEnum = new MultiDocsAndPositionsEnum(this, Subs.Length); } } else { docsAndPositionsEnum = new MultiDocsAndPositionsEnum(this, Subs.Length); } MultiBits multiLiveDocs; if (liveDocs is MultiBits) { multiLiveDocs = (MultiBits)liveDocs; } else { multiLiveDocs = null; } int upto = 0; for (int i = 0; i < NumTop; i++) { TermsEnumWithSlice entry = Top[i]; Bits b; if (multiLiveDocs != null) { // Optimize for common case: requested skip docs is a // congruent sub-slice of MultiBits: in this case, we // just pull the liveDocs from the sub reader, rather // than making the inefficient // Slice(Multi(sub-readers)): MultiBits.SubResult sub = multiLiveDocs.GetMatchingSub(Top[i].SubSlice); if (sub.Matches) { b = sub.Result; } else { // custom case: requested skip docs is foreign: // must slice it on every access (very // inefficient) b = new BitsSlice(liveDocs, Top[i].SubSlice); } } else if (liveDocs != null) { b = new BitsSlice(liveDocs, Top[i].SubSlice); } else { // no deletions b = null; } Debug.Assert(entry.Index < docsAndPositionsEnum.SubDocsAndPositionsEnum.Length, entry.Index + " vs " + docsAndPositionsEnum.SubDocsAndPositionsEnum.Length + "; " + Subs.Length); DocsAndPositionsEnum subPostings = entry.Terms.DocsAndPositions(b, docsAndPositionsEnum.SubDocsAndPositionsEnum[entry.Index], flags); if (subPostings != null) { docsAndPositionsEnum.SubDocsAndPositionsEnum[entry.Index] = subPostings; SubDocsAndPositions[upto].DocsAndPositionsEnum = subPostings; SubDocsAndPositions[upto].Slice = entry.SubSlice; upto++; } else { if (entry.Terms.Docs(b, null, DocsEnum.FLAG_NONE) != null) { // At least one of our subs does not store // offsets or positions -- we can't correctly // produce a MultiDocsAndPositions enum return null; } } } if (upto == 0) { return null; } else { return docsAndPositionsEnum.Reset(SubDocsAndPositions, upto); } } public sealed class TermsEnumWithSlice { internal readonly ReaderSlice SubSlice; internal TermsEnum Terms; public BytesRef Current; internal readonly int Index; public TermsEnumWithSlice(int index, ReaderSlice subSlice) { this.SubSlice = subSlice; this.Index = index; Debug.Assert(subSlice.Length >= 0, "length=" + subSlice.Length); } public void Reset(TermsEnum terms, BytesRef term) { this.Terms = terms; Current = term; } public override string ToString() { return SubSlice.ToString() + ":" + Terms; } } private sealed class TermMergeQueue : Util.PriorityQueue<TermsEnumWithSlice> { internal IComparer<BytesRef> TermComp; internal TermMergeQueue(int size) : base(size) { } public override bool LessThan(TermsEnumWithSlice termsA, TermsEnumWithSlice termsB) { int cmp = TermComp.Compare(termsA.Current, termsB.Current); if (cmp != 0) { return cmp < 0; } else { return termsA.SubSlice.Start < termsB.SubSlice.Start; } } } public override string ToString() { return "MultiTermsEnum(" + Arrays.ToString(Subs) + ")"; } } }
// ------------------------------------------------------------------------------ // Copyright (c) 2014 Microsoft Corporation // // 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. // ------------------------------------------------------------------------------ namespace Microsoft.Live.Operations { using System; using System.IO; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using BT = Windows.Networking.BackgroundTransfer; using Windows.Storage; using Windows.Storage.Streams; /// <summary> /// This class implements the upload operation on Windows 8 using the background uploader. /// </summary> internal class TailoredUploadOperation : ApiOperation { #region Instance member variables private const uint MaxUploadResponseLength = 10240; private BT.UploadOperation uploadOp; /// <summary> /// CancellationTokenSource used when calling the BT.UploadOperation. /// </summary> private CancellationTokenSource uploadOpCts; private bool isAttach; #endregion #region Cosntructors /// <summary> /// This class implements the upload operation on Windows 8 using the background uploader. /// </summary> /// <remarks>This constructor is used when uploading a file from the file system.</remarks> public TailoredUploadOperation( LiveConnectClient client, Uri url, string fileName, IStorageFile inputFile, OverwriteOption option, IProgress<LiveOperationProgress> progress, SynchronizationContextWrapper syncContext) : this(client, url, fileName, option, progress, syncContext) { Debug.Assert(inputFile != null, "inputFile is null."); this.InputFile = inputFile; } /// <summary> /// This class implements the upload operation on Windows 8 using the background uploader. /// </summary> /// <remarks>This constructor is used when uploading a stream created by the application.</remarks> public TailoredUploadOperation( LiveConnectClient client, Uri url, string fileName, IInputStream inputStream, OverwriteOption option, IProgress<LiveOperationProgress> progress, SynchronizationContextWrapper syncContext) : this(client, url, fileName, option, progress, syncContext) { Debug.Assert(inputStream != null, "inputStream is null."); this.InputStream = inputStream; } /// <summary> /// This class implements the upload operation on Windows 8 using the background uploader. /// </summary> /// <remarks>This constructor is used when uploading a stream created by the application.</remarks> internal TailoredUploadOperation( LiveConnectClient client, Uri url, string fileName, OverwriteOption option, IProgress<LiveOperationProgress> progress, SynchronizationContextWrapper syncContext) : base(client, url, ApiMethod.Upload, null, syncContext) { this.FileName = fileName; this.Progress = progress; this.OverwriteOption = option; } /// <summary> /// Creates a new TailoredDownloadOperation instance. /// </summary> /// <remarks>This constructor should only be used when attaching to an pending download.</remarks> internal TailoredUploadOperation() : base(null, null, ApiMethod.Upload, null, null) { } #endregion #region Properties public string FileName { get; private set; } public OverwriteOption OverwriteOption { get; private set; } public IStorageFile InputFile { get; private set; } public IInputStream InputStream { get; private set; } public IProgress<LiveOperationProgress> Progress { get; private set; } #endregion #region Public methods public async void Attach(BT.UploadOperation uploadOp) { Debug.Assert(uploadOp != null); this.uploadOp = uploadOp; this.isAttach = true; this.uploadOpCts = new CancellationTokenSource(); var progressHandler = new Progress<BT.UploadOperation>(this.OnUploadProgress); try { // Since we don't provide API for apps to attach to pending upload operations, we have no // way to invoke the app event handler to provide any feedback. We would just ignore the result here. this.uploadOp = await this.uploadOp.AttachAsync().AsTask(this.uploadOpCts.Token, progressHandler); } catch { // Ignore errors as well. } } public override void Cancel() { if (this.Status == OperationStatus.Cancelled || this.Status == OperationStatus.Completed) { return; } this.Status = OperationStatus.Cancelled; if (this.uploadOp != null) { this.uploadOpCts.Cancel(); } else { base.OnCancel(); } } #endregion #region Protected methods protected override void OnExecute() { var getUploadLinkOp = new GetUploadLinkOperation( this.LiveClient, this.Url, this.FileName, this.OverwriteOption, null); getUploadLinkOp.OperationCompletedCallback = this.OnGetUploadLinkCompleted; getUploadLinkOp.Execute(); } #endregion #region Private methods private async void OnGetUploadLinkCompleted(LiveOperationResult result) { if (this.Status == OperationStatus.Cancelled) { base.OnCancel(); return; } if (result.Error != null || result.IsCancelled) { this.OnOperationCompleted(result); return; } var uploadUrl = new Uri(result.RawResult, UriKind.Absolute); // NOTE: the GetUploadLinkOperation will return a uri with the overwite, suppress_response_codes, // and suppress_redirect query parameters set. Debug.Assert(uploadUrl.Query != null); Debug.Assert(uploadUrl.Query.Contains(QueryParameters.Overwrite)); Debug.Assert(uploadUrl.Query.Contains(QueryParameters.SuppressRedirects)); Debug.Assert(uploadUrl.Query.Contains(QueryParameters.SuppressResponseCodes)); var uploader = new BT.BackgroundUploader(); uploader.Group = LiveConnectClient.LiveSDKUploadGroup; if (this.LiveClient.Session != null) { uploader.SetRequestHeader( ApiOperation.AuthorizationHeader, AuthConstants.BearerTokenType + " " + this.LiveClient.Session.AccessToken); } uploader.SetRequestHeader(ApiOperation.LibraryHeader, Platform.GetLibraryHeaderValue()); uploader.Method = HttpMethods.Put; this.uploadOpCts = new CancellationTokenSource(); Exception webError = null; LiveOperationResult opResult = null; try { if (this.InputStream != null) { this.uploadOp = await uploader.CreateUploadFromStreamAsync(uploadUrl, this.InputStream); } else { this.uploadOp = uploader.CreateUpload(uploadUrl, this.InputFile); } var progressHandler = new Progress<BT.UploadOperation>(this.OnUploadProgress); this.uploadOp = await this.uploadOp.StartAsync().AsTask(this.uploadOpCts.Token, progressHandler); } catch (TaskCanceledException exception) { opResult = new LiveOperationResult(exception, true); } catch (Exception exp) { // This might be an server error. We will read the response to determine the error message. webError = exp; } if (opResult == null) { try { IInputStream responseStream = this.uploadOp.GetResultStreamAt(0); if (responseStream == null) { var error = new LiveConnectException( ApiOperation.ApiClientErrorCode, ResourceHelper.GetString("ConnectionError")); opResult = new LiveOperationResult(error, false); } else { var reader = new DataReader(responseStream); uint length = await reader.LoadAsync(MaxUploadResponseLength); opResult = ApiOperation.CreateOperationResultFrom(reader.ReadString(length), ApiMethod.Upload); if (webError != null && opResult.Error != null && !(opResult.Error is LiveConnectException)) { // If the error did not come from the api service, // we'll just return the error thrown by the uploader. opResult = new LiveOperationResult(webError, false); } } } catch (COMException exp) { opResult = new LiveOperationResult(exp, false); } catch (FileNotFoundException exp) { opResult = new LiveOperationResult(exp, false); } } this.OnOperationCompleted(opResult); } /// <summary> /// Called when a progress event is raised from the BT.UploadOperation and this /// will call this TailoredUploadOperation's progress handler. /// </summary> private void OnUploadProgress(BT.UploadOperation uploadOp) { Debug.Assert(uploadOp != null); if (uploadOp.Progress.Status == BT.BackgroundTransferStatus.Error || uploadOp.Progress.Status == BT.BackgroundTransferStatus.Canceled || this.isAttach || this.Progress == null) { return; } this.Progress.Report( new LiveOperationProgress( (long)uploadOp.Progress.BytesSent, (long)uploadOp.Progress.TotalBytesToSend)); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Xunit; using Microsoft.Xunit.Performance; namespace System.Linq.Tests { public class Perf_Linq { #region Helper Methods /// <summary> /// Provides TestInfo data to xunit performance tests /// </summary> public static IEnumerable<object[]> IterationSizeWrapperData() { int[] iterations = { 1000 }; int[] sizes = { 100 }; foreach (int iteration in iterations) foreach (int size in sizes) { yield return new object[] { size, iteration, Perf_LinqTestBase.WrapperType.NoWrap }; yield return new object[] { size, iteration, Perf_LinqTestBase.WrapperType.IEnumerable }; yield return new object[] { size, iteration, Perf_LinqTestBase.WrapperType.IReadOnlyCollection }; yield return new object[] { size, iteration, Perf_LinqTestBase.WrapperType.ICollection }; } } /// <summary> /// Provides TestInfo data to xunit performance tests /// </summary> public static IEnumerable<object[]> IterationSizeWrapperDataNoWrapper() { int[] iterations = { 1000 }; int[] sizes = { 100 }; foreach (int iteration in iterations) foreach (int size in sizes) yield return new object[] { size, iteration }; } private static int[] QuickSortWorstCase(int n) { int OddPos(int k) { int s = k; while (s * 2 < n) s *= 2; return (n - 1) % s + 1; } int[] a = new int[n]; for (int x = 1; x <= n; x++) { if (x % 2 == 0) { a[x / 2 - 1] = x; } else if (x == n) { a[n / 2] = x; } else { a[n - OddPos(x)] = x; } } return a; } private class BaseClass { public int Value; } private class ChildClass : BaseClass { public int ChildValue; } #endregion #region Perf Tests [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void Select(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { Perf_LinqTestBase.Measure<int>(size, iteration, wrapType, col => col.Select(o => o + 1)); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void SelectSelect(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { Perf_LinqTestBase.Measure<int>(size, iteration, wrapType, col => col.Select(o => o + 1).Select(o => o - 1)); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void Where(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { Perf_LinqTestBase.Measure<int>(size, iteration, wrapType, col => col.Where(o => o >= 0)); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void WhereWhere(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { Perf_LinqTestBase.Measure<int>(size, iteration, wrapType, col => col.Where(o => o >= 0).Where(o => o >= -1)); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void WhereSelect(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { Perf_LinqTestBase.Measure<int>(size, iteration, wrapType, col => col.Where(o => o >= 0).Select(o => o + 1)); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void Cast_ToBaseClass(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { Func<IEnumerable<ChildClass>, IEnumerable<BaseClass>> linqApply = col => col.Cast<BaseClass>(); ChildClass val = new ChildClass() { Value = 1, ChildValue = 2 }; Perf_LinqTestBase.Measure<ChildClass, BaseClass>(10, 5, val, wrapType, linqApply); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void Cast_SameType(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { Func<IEnumerable<int>, IEnumerable<int>> linqApply = col => col.Cast<int>(); int val = 1; Perf_LinqTestBase.Measure<int, int>(10, 5, val, wrapType, linqApply); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void OrderBy(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { Perf_LinqTestBase.Measure<int>(size, iteration, wrapType, col => col.OrderBy(o => -o)); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void OrderByDescending(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { Perf_LinqTestBase.Measure<int>(size, iteration, wrapType, col => col.OrderByDescending(o => -o)); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void OrderByThenBy(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { Perf_LinqTestBase.Measure<int>(size, iteration, wrapType, col => col.OrderBy(o => -o).ThenBy(o => o)); } [Benchmark] [MemberData(nameof(IterationSizeWrapperDataNoWrapper))] public void Range(int size, int iteration) { Perf_LinqTestBase.Measure<int>(1, iteration, Perf_LinqTestBase.WrapperType.NoWrap, col => Enumerable.Range(0, size)); } [Benchmark] [MemberData(nameof(IterationSizeWrapperDataNoWrapper))] public void Repeat(int size, int iteration) { Perf_LinqTestBase.Measure<int>(1, iteration, Perf_LinqTestBase.WrapperType.NoWrap, col => Enumerable.Repeat(0, size)); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void Reverse(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { Perf_LinqTestBase.Measure<int>(size, iteration, wrapType, col => col.Reverse()); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void Skip(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { Perf_LinqTestBase.Measure<int>(size, iteration, wrapType, col => col.Skip(1)); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void Take(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { Perf_LinqTestBase.Measure<int>(size, iteration, wrapType, col => col.Take(size - 1)); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void SkipTake(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { Perf_LinqTestBase.Measure<int>(size, iteration, wrapType, col => col.Skip(1).Take(size - 2)); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void ToArray(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { int[] array = Enumerable.Range(0, size).ToArray(); Perf_LinqTestBase.MeasureMaterializationToArray<int>(Perf_LinqTestBase.Wrap(array, wrapType), iteration); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void ToList(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { int[] array = Enumerable.Range(0, size).ToArray(); Perf_LinqTestBase.MeasureMaterializationToList<int>(Perf_LinqTestBase.Wrap(array, wrapType), iteration); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void ToDictionary(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { int[] array = Enumerable.Range(0, size).ToArray(); Perf_LinqTestBase.MeasureMaterializationToDictionary<int>(Perf_LinqTestBase.Wrap(array, wrapType), iteration); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void Contains_ElementNotFound(int size, int iterationCount, Perf_LinqTestBase.WrapperType wrapType) { IEnumerable<int> source = Perf_LinqTestBase.Wrap(Enumerable.Range(0, size).ToArray(), wrapType); foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < iterationCount; i++) { source.Contains(size + 1); } } } } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void Contains_FirstElementMatches(int size, int iterationCount, Perf_LinqTestBase.WrapperType wrapType) { IEnumerable<int> source = Perf_LinqTestBase.Wrap(Enumerable.Range(0, size).ToArray(), wrapType); foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < iterationCount; i++) { source.Contains(0); } } } } [Benchmark] public void OrderBy_TakeOne() { Perf_LinqTestBase.MeasureIteration(QuickSortWorstCase(10000).OrderBy(i => i).Take(1), 10); } #endregion } }
#region MIT license // // MIT license // // Copyright (c) 2007-2008 Jiri Moudry, Pascal Craponne // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #endregion using System; using System.Data.Common; using System.Linq; using System.Collections.Generic; using System.Text; using System.Data.Linq.Mapping; using System.Reflection; using System.Data; #if MONO_STRICT using System.Data.Linq; #else using DbLinq.Data.Linq; #endif using DbLinq.Data.Linq.SqlClient; using DbLinq.Util; using DbLinq.Vendor; namespace DbLinq.Firebird { [Vendor(typeof(FirebirdProvider))] #if !MONO_STRICT public #endif class FirebirdVendor : Vendor.Implementation.Vendor { public override string VendorName { get { return "FirebirdSql"; } } protected readonly FirebirdSqlProvider sqlProvider = new FirebirdSqlProvider(); public override ISqlProvider SqlProvider { get { return sqlProvider; } } /// <summary> /// call mysql stored proc or stored function, /// optionally return DataSet, and collect return params. /// </summary> public override System.Data.Linq.IExecuteResult ExecuteMethodCall(DataContext context, MethodInfo method , params object[] inputValues) { if (method == null) throw new ArgumentNullException("L56 Null 'method' parameter"); //check to make sure there is exactly one [FunctionEx]? that's below. //FunctionAttribute functionAttrib = GetFunctionAttribute(method); var functionAttrib = context.Mapping.GetFunction(method); ParameterInfo[] paramInfos = method.GetParameters(); //int numRequiredParams = paramInfos.Count(p => p.IsIn || p.IsRetval); //if (numRequiredParams != inputValues.Length) // throw new ArgumentException("L161 Argument count mismatch"); string sp_name = functionAttrib.MappedName; // picrap: is there any way to abstract some part of this? using (IDbCommand command = context.Connection.CreateCommand()) { command.CommandText = sp_name; //FbSqlCommand command = new FbSqlCommand("select * from hello0()"); int currInputIndex = 0; List<string> paramNames = new List<string>(); for (int i = 0; i < paramInfos.Length; i++) { ParameterInfo paramInfo = paramInfos[i]; //TODO: check to make sure there is exactly one [Parameter]? ParameterAttribute paramAttrib = paramInfo.GetCustomAttributes(false).OfType<ParameterAttribute>().Single(); string paramName = "@" + paramAttrib.Name; //eg. '@param1' paramNames.Add(paramName); System.Data.ParameterDirection direction = GetDirection(paramInfo, paramAttrib); //FbDbType dbType = FbSqlTypeConversions.ParseType(paramAttrib.DbType); IDbDataParameter cmdParam = command.CreateParameter(); cmdParam.ParameterName = paramName; //cmdParam.Direction = System.Data.ParameterDirection.Input; if (direction == System.Data.ParameterDirection.Input || direction == System.Data.ParameterDirection.InputOutput) { object inputValue = inputValues[currInputIndex++]; cmdParam.Value = inputValue; } else { cmdParam.Value = null; } cmdParam.Direction = direction; command.Parameters.Add(cmdParam); } if (!functionAttrib.IsComposable) // IsCompsable is false when we have a procedure { //procedures: under the hood, this seems to prepend 'CALL ' command.CommandType = System.Data.CommandType.StoredProcedure; } else { //functions: 'SELECT * FROM myFunction()' or 'SELECT * FROM hello(?s)' command.CommandText = "SELECT * FROM " + command.CommandText + "(" + string.Join(",", paramNames.ToArray()) + ")"; } if (method.ReturnType == typeof(DataSet)) { //unknown shape of resultset: System.Data.DataSet dataSet = new DataSet(); //IDataAdapter adapter = new FbDataAdapter((FbCommand)command); IDbDataAdapter adapter = CreateDataAdapter(context); adapter.SelectCommand = command; adapter.Fill(dataSet); List<object> outParamValues = CopyOutParams(paramInfos, command.Parameters); return new ProcedureResult(dataSet, outParamValues.ToArray()); } else { object obj = command.ExecuteScalar(); List<object> outParamValues = CopyOutParams(paramInfos, command.Parameters); return new ProcedureResult(obj, outParamValues.ToArray()); } } } static System.Data.ParameterDirection GetDirection(ParameterInfo paramInfo, ParameterAttribute paramAttrib) { //strange hack to determine what's a ref, out parameter: //http://lists.ximian.com/pipermain/mono-list/2003-March/012751.html bool hasAmpersand = paramInfo.ParameterType.FullName.Contains('&'); if (paramInfo.IsOut) return System.Data.ParameterDirection.Output; if (hasAmpersand) return System.Data.ParameterDirection.InputOutput; return System.Data.ParameterDirection.Input; } /// <summary> /// Collect all Out or InOut param values, casting them to the correct .net type. /// </summary> private List<object> CopyOutParams(ParameterInfo[] paramInfos, IDataParameterCollection paramSet) { List<object> outParamValues = new List<object>(); //Type type_t = typeof(T); int i = -1; foreach (IDbDataParameter param in paramSet) { i++; if (param.Direction == System.Data.ParameterDirection.Input) { outParamValues.Add("unused"); continue; } object val = param.Value; Type desired_type = paramInfos[i].ParameterType; if (desired_type.Name.EndsWith("&")) { //for ref and out parameters, we need to tweak ref types, e.g. // "System.Int32&, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" string fullName1 = desired_type.AssemblyQualifiedName; string fullName2 = fullName1.Replace("&", ""); desired_type = Type.GetType(fullName2); } try { //fi.SetValue(t, val); //fails with 'System.Decimal cannot be converted to Int32' //DbLinq.util.FieldUtils.SetObjectIdField(t, fi, val); //object val2 = FieldUtils.CastValue(val, desired_type); object val2 = TypeConvert.To(val, desired_type); outParamValues.Add(val2); } catch (Exception) { //fails with 'System.Decimal cannot be converted to Int32' //Logger.Write(Level.Error, "CopyOutParams ERROR L245: failed on CastValue(): " + ex.Message); } } return outParamValues; } } }
using System; /// <summary> /// Char.Equals(Object) /// Note: This method is new in the .NET Framework version 2.0. /// Returns a value indicating whether this instance is equal to the specified Char object. /// </summary> public class CharEquals { public static int Main() { CharEquals testObj = new CharEquals(); TestLibrary.TestFramework.BeginTestCase("for method: Char.Equals(Object)"); if(testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; return retVal; } #region Positive tests public bool PosTest1() { bool retVal = true; const string c_TEST_ID = "P001"; const string c_TEST_DESC = @"PosTest1: char.MaxValue vs '\uFFFF'"; string errorDesc; const char c_MAX_CHAR = '\uFFFF'; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { char actualChar = char.MaxValue; object obj = c_MAX_CHAR; bool result = actualChar.Equals(obj); if (!result) { errorDesc = "Char.MaxValue is not " + c_MAX_CHAR + " as expected: Actual(" + actualChar + ")"; TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; const string c_TEST_ID = "P002"; const string c_TEST_DESC = @"PosTest2: char.MinValue vs '\u0000'"; string errorDesc; const char c_MIN_CHAR = '\u0000'; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { char actualChar = char.MinValue; object obj = c_MIN_CHAR; bool result = actualChar.Equals(obj); if (!result) { errorDesc = "char.MinValue is not " + c_MIN_CHAR + " as expected: Actual(" + actualChar + ")"; TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; const string c_TEST_ID = "P003"; const string c_TEST_DESC = "PosTest3: char.MaxValue vs char.MinValue"; string errorDesc; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { bool expectedValue = false; object obj = char.MinValue; bool actualValue = char.MaxValue.Equals(obj); if (actualValue != expectedValue) { errorDesc = @"char.MaxValue('\uFFFF') does not equal char.MinValue('\u0000')"; TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; const string c_TEST_ID = "P004"; const string c_TEST_DESC = "PosTest4: equality of two random charaters"; string errorDesc; char chA, chB; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { chA = TestLibrary.Generator.GetChar(-55); chB = TestLibrary.Generator.GetChar(-55); object obj = chB; bool expectedValue = (int)chA == (int)chB; bool actualValue = chA.Equals(obj); if (actualValue != expectedValue) { errorDesc = string.Format("The equality of character \'\\u{0:x}\' against character \'\\u{1:x}\' is not {2} as expected: Actual({3})", (int)chA, (int)chB, expectedValue, actualValue); TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; const string c_TEST_ID = "P004"; const string c_TEST_DESC = "PosTest4: char vs 32-bit integer value"; string errorDesc; char chA; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { chA = TestLibrary.Generator.GetChar(-55); object obj = (int)chA; bool expectedValue = false; bool actualValue = chA.Equals(obj); if (actualValue != expectedValue) { errorDesc = string.Format("The equality of character \'\\u{0:x}\' against 32-bit integer {1:x} is not {2} as expected: Actual({3})", (int)chA, (int)obj, expectedValue, actualValue); TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } #endregion }
using System; using System.Collections.Generic; namespace Pixie.Options { /// <summary> /// Describes a flag option: a Boolean option whose value is set /// by mentioning one of the option's forms. Flag options take no /// arguments. /// </summary> public sealed class FlagOption : Option { /// <summary> /// Creates a flag option from a positive form. /// The flag's default value is <c>false</c>. /// </summary> /// <param name="positiveForm"> /// A positive form for the flag option. /// </param> public FlagOption( OptionForm positiveForm) : this( new OptionForm[] { positiveForm }, new OptionForm[] { }, false) { } /// <summary> /// Creates a flag option from a positive form, /// a negative form and a default value. /// </summary> /// <param name="positiveForm"> /// A positive form for the flag option. /// </param> /// <param name="negativeForm"> /// A negative form for the flag option. /// </param> /// <param name="defaultValue"> /// A default value for the flag option. /// </param> public FlagOption( OptionForm positiveForm, OptionForm negativeForm, bool defaultValue) : this( new OptionForm[] { positiveForm }, new OptionForm[] { negativeForm }, defaultValue) { } /// <summary> /// Creates a flag option from a list of positive forms, /// a list of negative forms and a default value. /// </summary> /// <param name="positiveForms"> /// A list of positive forms for the flag option. /// </param> /// <param name="negativeForms"> /// A list of negative forms for the flag option. /// </param> /// <param name="defaultValue"> /// A default value for the flag option. /// </param> public FlagOption( IReadOnlyList<OptionForm> positiveForms, IReadOnlyList<OptionForm> negativeForms, bool defaultValue) : this( positiveForms, negativeForms, defaultValue, "") { } private FlagOption( IReadOnlyList<OptionForm> positiveForms, IReadOnlyList<OptionForm> negativeForms, bool defaultValue, MarkupNode description) { this.PositiveForms = positiveForms; this.NegativeForms = negativeForms; this.positiveFormSet = new HashSet<OptionForm>(positiveForms); this.defaultVal = defaultValue; this.allForms = new List<OptionForm>(positiveForms); this.allForms.AddRange(negativeForms); this.category = OptionDocs.DefaultCategory; this.description = description; } private FlagOption(FlagOption other) { this.PositiveForms = other.PositiveForms; this.NegativeForms = other.NegativeForms; this.positiveFormSet = other.positiveFormSet; this.defaultVal = other.defaultVal; this.allForms = other.allForms; this.category = other.category; this.description = other.description; } /// <summary> /// Gets a list of positive forms for this flag option. /// </summary> /// <returns>A list of positive forms for this flag option.</returns> public IReadOnlyList<OptionForm> PositiveForms { get; private set; } /// <summary> /// Gets a list of negative forms for this flag option. /// </summary> /// <returns>A list of negative forms for this flag option.</returns> public IReadOnlyList<OptionForm> NegativeForms { get; private set; } private HashSet<OptionForm> positiveFormSet; private List<OptionForm> allForms; private bool defaultVal; private string category; private MarkupNode description; /// <inheritdoc/> public override IReadOnlyList<OptionForm> Forms => allForms; /// <inheritdoc/> public override object DefaultValue => defaultVal; /// <inheritdoc/> public override OptionDocs Documentation => new OptionDocs( category, description, new Dictionary<OptionForm, IReadOnlyList<OptionParameter>>()); /// <summary> /// Creates a copy of this option that is classified under a /// particular category. /// </summary> /// <param name="category">The new option's category.</param> /// <returns>An option.</returns> public FlagOption WithCategory(string category) { var result = new FlagOption(this); result.category = category; return result; } /// <summary> /// Creates a copy of this option that has a particular description. /// </summary> /// <param name="description">The new option's description.</param> /// <returns>An option.</returns> public FlagOption WithDescription(MarkupNode description) { var result = new FlagOption(this); result.description = description; return result; } /// <inheritdoc/> public override OptionParser CreateParser(OptionForm form) { if (positiveFormSet.Contains(form)) { return new FlagOptionParser(true); } else { return new FlagOptionParser(false); } } /// <inheritdoc/> public override ParsedOption MergeValues(ParsedOption first, ParsedOption second) { // Listen to the last flag provided by the user. return second; } /// <summary> /// Creates a simple flag option that is turned off /// by default and is turned on when one or more of /// its forms is encountered. /// </summary> /// <param name="forms">The option forms to accept.</param> /// <returns>A flag option.</returns> public static FlagOption CreateFlagOption( IReadOnlyList<OptionForm> forms) { return new FlagOption(forms, new OptionForm[] { }, false); } /// <summary> /// Creates a simple flag option that is turned off /// by default and is turned on when one or more of /// its forms is encountered. /// </summary> /// <param name="forms">The option forms to accept.</param> /// <returns>A flag option.</returns> public static FlagOption CreateFlagOption( params OptionForm[] forms) { return CreateFlagOption((IReadOnlyList<OptionForm>)forms); } } internal sealed class FlagOptionParser : OptionParser { public FlagOptionParser(bool value) { this.value = value; } private bool value; public override object GetValue(ILog log) { return value; } public override bool Parse(string argument) { // Flags don't take any arguments. return false; } } }
using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace Core { public class TagBase { public class LookasideSlot { public LookasideSlot Next; // Next buffer in the list of free buffers } public class Lookaside_ { public ushort Size; // Size of each buffer in bytes public bool Enabled; // False to disable new lookaside allocations public bool Malloced; // True if pStart obtained from sqlite3_malloc() public int Outs; // Number of buffers currently checked out public int MaxOuts; // Highwater mark for nOut public int[] Stats = new int[3]; // 0: hits. 1: size misses. 2: full misses public LookasideSlot Free; // List of available buffers public byte[] Start; // First byte of available memory space public LookasideSlot End; // First byte past end of available space } public MutexEx Mutex; // Connection mutex public bool MallocFailed; // True if we have seen a malloc failure public RC ErrCode; // Most recent error code (RC_*) public int ErrMask; // & result codes with this before returning public Lookaside_ Lookaside; // Lookaside malloc configuration } public partial class SysEx { #region Log & Trace #if DEBUG internal static bool IOTrace = true; internal static void LOG(RC rc, string format, params object[] args) { Console.WriteLine("l:" + string.Format(format, args)); } internal static void IOTRACE(string format, params object[] args) { if (IOTrace) Console.WriteLine("i:" + string.Format(format, args)); } #else internal static void LOG(RC rc, string x, params object[] args) { } internal static void IOTRACE(string format, params object[] args) { } #endif //internal static RC LOG2(RC rc, string func, string path) //{ // var sf = new StackTrace(new StackFrame(true)).GetFrame(0); // var errorID = (uint)Marshal.GetLastWin32Error(); // var message = Marshal.GetLastWin32Error().ToString(); // Debug.Assert(rc != RC.OK); // if (path == null) // path = string.Empty; // int i; // for (i = 0; i < message.Length && message[i] != '\r' && message[i] != '\n'; i++) ; // message = message.Substring(0, i); // //sqlite3_log("os_win.c:%d: (%d) %s(%s) - %s", sf.GetFileLineNumber(), errorID, func, sf.GetFileName(), message); // return rc; //} #endregion internal const string CORE_VERSION = "--VERS--"; internal const int CORE_VERSION_NUMBER = 3007016; internal const string CORE_SOURCE_ID = "--SOURCE-ID--"; #region WSD #endregion #region Initialize/Shutdown/Config public class GlobalStatics { public bool Memstat; // True to enable memory status public bool CoreMutex; // True to enable core mutexing public bool FullMutex; // True to enable full mutexing public bool OpenUri; // True to interpret filenames as URIs //MainLLbool UseCis; // Use covering indices for full-scans public int MaxStrlen; // Maximum string length public int LookasideSize; // Default lookaside buffer size public int Lookasides; // Default lookaside buffer count //public sqlite3_mem_methods m; // Low-level memory allocation interface //public sqlite3_mutex_methods mutex; // Low-level mutex interface //Main::sqlite3_pcache_methods pcache; // Low-level page-cache interface //public array_t<byte[]> Heap; // Heap storage space //public int MaxReq, MaxReq; // Min and max heap requests sizes public byte[][] Scratch, Scratch2; // Scratch memory public int ScratchSize; // Size of each scratch buffer public int Scratchs; // Number of scratch buffers //Main::MemPage Page; // Page cache memory //Main::int PageSize; // Size of each page in pPage[] //Main::int Pages; // Number of pages in pPage[] //Main::int MaxParserStack; // maximum depth of the parser stack public bool SharedCacheEnabled; // true if shared-cache mode enabled // The above might be initialized to non-zero. The following need to always initially be zero, however. public bool IsInit; // True after initialization has finished public bool InProgress; // True while initialization in progress public bool IsMutexInit; // True after mutexes are initialized public bool IsMallocInit; // True after malloc is initialized //Main::bool IsPCacheInit; // True after malloc is initialized public MutexEx InitMutex; // Mutex used by sqlite3_initialize() public int InitMutexRefs; // Number of users of pInitMutex public Action<object, int, string> Log; // Function for logging public object LogArg; // First argument to xLog() public bool LocaltimeFault; // True to fail localtime() calls #if ENABLE_SQLLOG public Action<object, TagBase, string, int> Sqllog; public object SqllogArg; #endif public GlobalStatics( bool memstat, bool coreMutex, bool fullMutex, bool openUri, int maxStrlen, int lookasideSize, int lookasides, //sqlite3_mem_methods m, //sqlite3_mutex_methods mutex, //array_t<byte[]> heap, //int minReq, int maxReq, byte[][] scratch, int scratchSize, int scratchs, bool sharedCacheEnabled, bool isInit, bool inProgress, bool isMutexInit, bool isMallocInit, MutexEx initMutex, int initMutexRefs, Action<object, int, string> log, object logArg, bool localtimeFault #if ENABLE_SQLLOG , Action<object, TagBase, string, int> Sqllog, object SqllogArg #endif ) { Memstat = memstat; CoreMutex = coreMutex; OpenUri = openUri; FullMutex = fullMutex; MaxStrlen = maxStrlen; LookasideSize = lookasideSize; Lookasides = lookasides; //m = m; //mutex = mutex; //Heap = heap; //MaxReq = minReq; MinReq = maxReq; Scratch = scratch; ScratchSize = scratchSize; Scratchs = scratchs; SharedCacheEnabled = sharedCacheEnabled; IsInit = isInit; InProgress = inProgress; IsMutexInit = isMutexInit; IsMallocInit = isMallocInit; InitMutex = initMutex; InitMutexRefs = initMutexRefs; Log = log; LogArg = logArg; LocaltimeFault = localtimeFault; #if ENABLE_SQLLOG Sqllog = sqllog; SqllogArg = sqllogArg; #endif } } public enum CONFIG { SINGLETHREAD = 1, // nil MULTITHREAD = 2, // nil SERIALIZED = 3, // nil MALLOC = 4, // sqlite3_mem_methods* GETMALLOC = 5, // sqlite3_mem_methods* SCRATCH = 6, // void*, int sz, int N HEAP = 8, // void*, int nByte, int min MEMSTATUS = 9, // boolean MUTEX = 10, // sqlite3_mutex_methods* GETMUTEX = 11, // sqlite3_mutex_methods* LOOKASIDE = 13, // int int LOG = 16, // xFunc, void* URI = 17, // int SQLLOG = 21, // xSqllog, void* } const bool CORE_DEFAULT_MEMSTATUS = true; const bool CORE_USE_URI = false; // The following singleton contains the global configuration for the SQLite library. public static readonly GlobalStatics _GlobalStatics = new GlobalStatics( CORE_DEFAULT_MEMSTATUS, // Memstat true, // CoreMutex #if THREADSAFE true, // FullMutex #else false, // FullMutex #endif CORE_USE_URI, // OpenUri // Main::UseCis 0x7ffffffe, // MaxStrlen 128, // LookasideSize 500, // Lookasides //{0,0,0,0,0,0,0,0}, // m //{0,0,0,0,0,0,0,0,0}, // mutex // pcache2 //array_t(void *)nullptr, 0)// Heap //0, 0, // MinHeap, MaxHeap null, // Scratch 0, // ScratchSize 0, // Scratchs // Main::Page // Main::PageSize // Main::Pages // Main::MaxParserStack false, // SharedCacheEnabled // All the rest should always be initialized to zero false, // IsInit false, // InProgress false, // IsMutexInit false, // IsMallocInit // Main::IsPCacheInit default(MutexEx), // InitMutex 0, // InitMutexRefs null, // Log null, // LogArg false // LocaltimeFault #if ENABLE_SQLLOG , null, // Sqllog null // SqllogArg #endif ); public static RC PreInitialize(out MutexEx masterMutex) { masterMutex = default(MutexEx); // If SQLite is already completely initialized, then this call to sqlite3_initialize() should be a no-op. But the initialization // must be complete. So isInit must not be set until the very end of this routine. if (_GlobalStatics.IsInit) return RC.OK; // The following is just a sanity check to make sure SQLite has been compiled correctly. It is important to run this code, but // we don't want to run it too often and soak up CPU cycles for no reason. So we run it once during initialization. #if !NDEBUG && !OMIT_FLOATING_POINT // This section of code's only "output" is via assert() statements. //ulong x = (((ulong)1)<<63)-1; //double y; //Debug.Assert(sizeof(ulong) == 8); //Debug.Assert(sizeof(ulong) == sizeof(double)); //_memcpy<void>(&y, &x, 8); //Debug.Assert(double.IsNaN(y)); #endif RC rc; #if ENABLE_SQLLOG { Init_Sqllog(); } #endif // Make sure the mutex subsystem is initialized. If unable to initialize the mutex subsystem, return early with the error. // If the system is so sick that we are unable to allocate a mutex, there is not much SQLite is going to be able to do. // The mutex subsystem must take care of serializing its own initialization. rc = RC.OK; //MutexEx::Init(); if (rc != 0) return rc; // Initialize the malloc() system and the recursive pInitMutex mutex. This operation is protected by the STATIC_MASTER mutex. Note that // MutexAlloc() is called for a static mutex prior to initializing the malloc subsystem - this implies that the allocation of a static // mutex must not require support from the malloc subsystem. masterMutex = MutexEx.Alloc(MutexEx.MUTEX.STATIC_MASTER); // The main static mutex MutexEx.Enter(masterMutex); _GlobalStatics.IsMutexInit = true; //if (!SysEx_GlobalStatics.IsMallocInit) // rc = sqlite3MallocInit(); if (rc == RC.OK) { _GlobalStatics.IsMallocInit = true; if (_GlobalStatics.InitMutex.Tag == null) { _GlobalStatics.InitMutex = MutexEx.Alloc(MutexEx.MUTEX.RECURSIVE); if (_GlobalStatics.CoreMutex && _GlobalStatics.InitMutex.Tag == null) rc = RC.NOMEM; } } if (rc == RC.OK) _GlobalStatics.InitMutexRefs++; MutexEx.Leave(masterMutex); // If rc is not SQLITE_OK at this point, then either the malloc subsystem could not be initialized or the system failed to allocate // the pInitMutex mutex. Return an error in either case. if (rc != RC.OK) return rc; // Do the rest of the initialization under the recursive mutex so that we will be able to handle recursive calls into // sqlite3_initialize(). The recursive calls normally come through sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other // recursive calls might also be possible. // // IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls to the xInit method, so the xInit method need not be threadsafe. // // The following mutex is what serializes access to the appdef pcache xInit methods. The sqlite3_pcache_methods.xInit() all is embedded in the // call to sqlite3PcacheInitialize(). MutexEx.Enter(_GlobalStatics.InitMutex); if (!_GlobalStatics.IsInit && !_GlobalStatics.InProgress) { _GlobalStatics.InProgress = true; rc = VSystem.Initialize(); } if (rc != RC.OK) MutexEx.Leave(_GlobalStatics.InitMutex); return rc; } public static void PostInitialize(MutexEx masterMutex) { MutexEx.Leave(_GlobalStatics.InitMutex); // Go back under the static mutex and clean up the recursive mutex to prevent a resource leak. MutexEx.Enter(masterMutex); _GlobalStatics.InitMutexRefs--; if (_GlobalStatics.InitMutexRefs <= 0) { Debug.Assert(_GlobalStatics.InitMutexRefs == 0); MutexEx.Free(_GlobalStatics.InitMutex); _GlobalStatics.InitMutex.Tag = null; } MutexEx.Leave(masterMutex); } public static RC Shutdown() { if (_GlobalStatics.IsInit) { VSystem.Shutdown(); //sqlite3_reset_auto_extension(); _GlobalStatics.IsInit = false; } //if (SysEx_GlobalStatics.IsMallocInit) //{ // sqlite3MallocEnd(); // SysEx_GlobalStatics.IsMallocInit = false; //} if (_GlobalStatics.IsMutexInit) { //MutexEx::End(); _GlobalStatics.IsMutexInit = false; } return RC.OK; } public static RC Config(CONFIG op, params object[] args) { // sqlite3_config() shall return SQLITE_MISUSE if it is invoked while the SQLite library is in use. if (_GlobalStatics.IsInit) return SysEx.MISUSE_BKPT(); RC rc = RC.OK; switch (op) { #if THREADSAFE // Mutex configuration options are only available in a threadsafe compile. case CONFIG.SINGLETHREAD: { // Disable all mutexing _GlobalStatics.CoreMutex = false; _GlobalStatics.FullMutex = false; break; } case CONFIG.MULTITHREAD: { // Disable mutexing of database connections, Enable mutexing of core data structures _GlobalStatics.CoreMutex = true; _GlobalStatics.FullMutex = false; break; } case CONFIG.SERIALIZED: { // Enable all mutexing _GlobalStatics.CoreMutex = true; _GlobalStatics.FullMutex = true; break; } case CONFIG.MUTEX: { // Specify an alternative mutex implementation //_GlobalStatics.Mutex = (sqlite3_mutex_methods)args[0]; break; } case CONFIG.GETMUTEX: { // Retrieve the current mutex implementation //args[0] = _GlobalStatics.Mutex; break; } #endif case CONFIG.MALLOC: { // Specify an alternative malloc implementation //_GlobalStatics.m = *va_arg(args, sqlite3_mem_methods*); break; } case CONFIG.GETMALLOC: { // Retrieve the current malloc() implementation //if (_GlobalStatics.m.xMalloc==0) sqlite3MemSetDefault(); //args[0]= _GlobalStatics.m; break; } case CONFIG.MEMSTATUS: { // Enable or disable the malloc status collection _GlobalStatics.Memstat = (bool)args[0]; break; } case CONFIG.SCRATCH: { // Designate a buffer for scratch memory space _GlobalStatics.Scratch = (byte[][])args[0]; _GlobalStatics.ScratchSize = (int)args[1]; _GlobalStatics.Scratchs = (int)args[2]; break; } #if ENABLE_MEMSYS3 || ENABLE_MEMSYS5 case CONFIG_HEAP: { // Designate a buffer for heap memory space _GlobalStatics.Heap.data = va_arg(args, void*); _GlobalStatics.Heap.length = va_arg(args, int); _GlobalStatics.MinReq = va_arg(ap, int); if (_GlobalStatics.MinReq < 1) _GlobalStatics.MinReq = 1; else if (SysEx_GlobalStatics.MinReq > (1<<12)) // cap min request size at 2^12 _GlobalStatics.MinReq = (1<<12); if (!_GlobalStatics.Heap.data) // If the heap pointer is NULL, then restore the malloc implementation back to NULL pointers too. This will cause the malloc to go back to its default implementation when sqlite3_initialize() is run. memset(&_GlobalStatics.m, 0, sizeof(_GlobalStatics.m)); else // The heap pointer is not NULL, then install one of the mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor ENABLE_MEMSYS5 is defined, return an error. #if ENABLE_MEMSYS3 _GlobalStatics.m = sqlite3MemGetMemsys3(); #endif #if ENABLE_MEMSYS5 _GlobalStatics.m = sqlite3MemGetMemsys5(); #endif break; } #endif case CONFIG.LOOKASIDE: { _GlobalStatics.LookasideSize = (int)args[0]; _GlobalStatics.Lookasides = (int)args[1]; break; } case CONFIG.LOG: { // Record a pointer to the logger function and its first argument. The default is NULL. Logging is disabled if the function pointer is NULL. // MSVC is picky about pulling func ptrs from va lists. // http://support.microsoft.com/kb/47961 _GlobalStatics.Log = (Action<object, int, string>)args[0]; _GlobalStatics.LogArg = (object)args[1]; break; } case CONFIG.URI: { _GlobalStatics.OpenUri = (bool)args[0]; break; } #if ENABLE_SQLLOG case CONFIG.SQLLOG: { _GlobalStatics.Sqllog = (Action<object, TagBase, int, string>)args[0];; _GlobalStatics.SqllogArg = (object)args[1]; break; } #endif default: { rc = RC.ERROR; break; } } return rc; } #endregion #region Func #endregion #region BKPT #if DEBUG internal static RC CORRUPT_BKPT() { var sf = new StackTrace(new StackFrame(true)).GetFrame(0); LOG(RC.CANTOPEN, "database corruption at line {0} of [{1}]", sf.GetFileLineNumber(), sf.GetFileName()); return RC.CORRUPT; } internal static RC MISUSE_BKPT() { var sf = new StackTrace(new StackFrame(true)).GetFrame(0); LOG(RC.CANTOPEN, "misuse at line {0} of [{1}]", sf.GetFileLineNumber(), sf.GetFileName()); return RC.MISUSE; } internal static RC CANTOPEN_BKPT() { var sf = new StackTrace(new StackFrame(true)).GetFrame(0); LOG(RC.CANTOPEN, "cannot open file at line {0} of [{1}]", sf.GetFileLineNumber(), sf.GetFileName()); return RC.CANTOPEN; } #else internal static RC CORRUPT_BKPT() { return RC.CORRUPT; } internal static RC MISUSE_BKPT() { return RC.MISUSE; } internal static RC CANTOPEN_BKPT() { return RC.CANTOPEN; } #endif #endregion public static RC SetupLookaside(TagBase tag, byte[] buf, int size, int count) { if (tag.Lookaside.Outs != 0) return RC.BUSY; // Free any existing lookaside buffer for this handle before allocating a new one so we don't have to have space for both at the same time. if (tag.Lookaside.Malloced) C._free(ref tag.Lookaside.Start); // The size of a lookaside slot after ROUNDDOWN8 needs to be larger than a pointer to be useful. size = C._ROUNDDOWN8(size); // IMP: R-33038-09382 if (size <= (int)4) size = 0; if (count < 0) count = 0; byte[] start; if (size == 0 || count == 0) { size = 0; start = null; } else if (buf == null) { C._benignalloc_begin(); start = new byte[size * count]; // IMP: R-61949-35727 C._benignalloc_end(); } else start = buf; tag.Lookaside.Start = start; tag.Lookaside.Free = null; tag.Lookaside.Size = (ushort)size; if (start != null) { Debug.Assert(size > 4); TagBase.LookasideSlot p = (TagBase.LookasideSlot)null; //: start; for (int i = count - 1; i >= 0; i--) { p.Next = tag.Lookaside.Free; tag.Lookaside.Free = p; p = (TagBase.LookasideSlot)null; //: &((uint8 *)p)[size]; } tag.Lookaside.End = p; tag.Lookaside.Enabled = true; tag.Lookaside.Malloced = (buf == null); } else { tag.Lookaside.End = null; tag.Lookaside.Enabled = false; tag.Lookaside.Malloced = false; } return RC.OK; } } }
using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.IdentityModel.Protocols.OpenIdConnect; using MusicStoreB2C.Components; using MusicStoreB2C.Models; namespace MusicStoreB2C { public class StartupMusicStore { private readonly Platform _platform; public StartupMusicStore(IHostingEnvironment hostingEnvironment) { // Below code demonstrates usage of multiple configuration sources. For instance a setting say 'setting1' // is found in both the registered sources, then the later source will win. By this way a Local config // can be overridden by a different setting while deployed remotely. var builder = new ConfigurationBuilder() .SetBasePath(hostingEnvironment.ContentRootPath) .AddJsonFile("config.json") //All environment variables in the process's context flow in as configuration values. .AddEnvironmentVariables(); if (hostingEnvironment.IsDevelopment()) { // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709 builder.AddUserSecrets<OrigStartup>(); } Configuration = builder.Build(); _platform = new Platform(); } public IConfiguration Configuration { get; private set; } public void ConfigureServices(IServiceCollection services) { IConfigurationSection blah = Configuration.GetSection("AppSettings"); services.Configure<AppSettings>(blah); // Add EF services to the services container if (_platform.UseInMemoryStore) { services.AddDbContext<MusicStoreContext>(options => options.UseInMemoryDatabase()); } else { services.AddDbContext<MusicStoreContext>(options => options.UseSqlServer(Configuration[StoreConfig.ConnectionStringKey.Replace("__", ":")])); } // Add Identity services to the services container services.AddIdentity<ApplicationUser, IdentityRole>(options => { options.Cookies.ApplicationCookie.AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.Cookies.ApplicationCookie.AccessDeniedPath = "/Home/AccessDenied"; }) .AddEntityFrameworkStores<MusicStoreContext>() .AddDefaultTokenProviders(); services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => { builder.WithOrigins("http://example.com"); }); }); services.AddLogging(); // Add MVC services to the services container services.AddMvc(); // Add memory cache services services.AddMemoryCache(); services.AddDistributedMemoryCache(); // Add session related services. services.AddSession(); // Add the system clock service services.AddSingleton<ISystemClock, SystemClock>(); services.AddAuthentication( SharedOptions => SharedOptions.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme); // Configure Auth services.AddAuthorization(options => { options.AddPolicy( "ManageStore", authBuilder => { authBuilder.RequireClaim("ManageStore", "Allowed"); }); }); } //This method is invoked when ASPNETCORE_ENVIRONMENT is 'Development' or is not defined //The allowed values are Development,Staging and Production public void ConfigureDevelopment(IApplicationBuilder app, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(minLevel: LogLevel.Trace); // StatusCode pages to gracefully handle status codes 400-599. app.UseStatusCodePagesWithRedirects("~/Home/StatusCodePage"); // Display custom error page in production when error occurs // During development use the ErrorPage middleware to display error information in the browser app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); Configure(app); } //This method is invoked when ASPNETCORE_ENVIRONMENT is 'Staging' //The allowed values are Development,Staging and Production public void ConfigureStaging(IApplicationBuilder app, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(minLevel: LogLevel.Warning); // StatusCode pages to gracefully handle status codes 400-599. app.UseStatusCodePagesWithRedirects("~/Home/StatusCodePage"); app.UseExceptionHandler("/Home/Error"); Configure(app); } //This method is invoked when ASPNETCORE_ENVIRONMENT is 'Production' //The allowed values are Development,Staging and Production public void ConfigureProduction(IApplicationBuilder app, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(minLevel: LogLevel.Warning); // StatusCode pages to gracefully handle status codes 400-599. app.UseStatusCodePagesWithRedirects("~/Home/StatusCodePage"); app.UseExceptionHandler("/Home/Error"); Configure(app); } public void Configure(IApplicationBuilder app) { // Configure Session. app.UseSession(); // Add static files to the request pipeline app.UseStaticFiles(); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme, AutomaticAuthenticate = false, AutomaticChallenge = true }); // Add cookie-based authentication to the request pipeline app.UseIdentity(); app.UseFacebookAuthentication(new FacebookOptions { AppId = "550624398330273", AppSecret = "10e56a291d6b618da61b1e0dae3a8954" }); app.UseGoogleAuthentication(new GoogleOptions { ClientId = "995291875932-0rt7417v5baevqrno24kv332b7d6d30a.apps.googleusercontent.com", ClientSecret = "J_AT57H5KH_ItmMdu0r6PfXm" }); app.UseTwitterAuthentication(new TwitterOptions { ConsumerKey = "lDSPIu480ocnXYZ9DumGCDw37", ConsumerSecret = "fpo0oWRNc3vsZKlZSq1PyOSoeXlJd7NnG4Rfc94xbFXsdcc3nH" }); // The MicrosoftAccount service has restrictions that prevent the use of // http://localhost:5001/ for test applications. // As such, here is how to change this sample to uses http://ktesting.com:5001/ instead. // Edit the Project.json file and replace http://localhost:5001/ with http://ktesting.com:5001/. // From an admin command console first enter: // notepad C:\Windows\System32\drivers\etc\hosts // and add this to the file, save, and exit (and reboot?): // 127.0.0.1 ktesting.com // Then you can choose to run the app as admin (see below) or add the following ACL as admin: // netsh http add urlacl url=http://ktesting:5001/ user=[domain\user] // The sample app can then be run via: // dnx . web app.UseMicrosoftAccountAuthentication(new MicrosoftAccountOptions { DisplayName = "MicrosoftAccount - Requires project changes", ClientId = "000000004012C08A", ClientSecret = "GaMQ2hCnqAC6EcDLnXsAeBVIJOLmeutL" }); // Create an Azure Active directory application and copy paste the following app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions { // Authority = "https://login.windows.net/[tenantName].onmicrosoft.com", Authority = string.Format("https://login.microsoftonline.com/{0}/v2.0/", Configuration["AzureAD:Tenant"]), //ClientId = "[ClientId]", ClientId = Configuration["AzureAD:ClientId"], ClientSecret = Configuration["AzureAD:ClientSecret"], // ResponseType = OpenIdConnectResponseType.CodeIdToken, ResponseType = OpenIdConnectResponseType.IdToken, }); // Add MVC to the request pipeline app.UseMvc(routes => { routes.MapRoute( name: "areaRoute", template: "{area:exists}/{controller}/{action}", defaults: new { action = "Index" }); routes.MapRoute( name: "default", template: "{controller}/{action}/{id?}", defaults: new { controller = "Home", action = "Index" }); routes.MapRoute( name: "api", template: "{controller}/{id?}"); }); //Populates the MusicStore sample data SampleData.InitializeMusicStoreDatabaseAsync(app.ApplicationServices).Wait(); } } }
namespace PeregrineDb.Tests.Testing { using System; using System.Collections.Generic; using FluentAssertions; using PeregrineDb; using PeregrineDb.Dialects; using PeregrineDb.Testing; using PeregrineDb.Tests.ExampleEntities; using PeregrineDb.Tests.Utils; using Xunit; public abstract class DataWiperTests { public static IEnumerable<object[]> TestDialects => new[] { new[] { Dialect.SqlServer2012 }, new[] { Dialect.PostgreSql } }; public class DeleteAllData : DataWiperTests { [Theory] [MemberData(nameof(TestDialects))] public void Deletes_data_from_simple_table(IDialect dialect) { using (var database = BlankDatabaseFactory.MakeDatabase(dialect)) { // Arrange database.Insert(new Dog { Name = "Some Name 1", Age = 10 }); database.Insert(new Dog { Name = "Some Name 2", Age = 10 }); database.Insert(new Dog { Name = "Some Name 3", Age = 10 }); database.Insert(new Dog { Name = "Some Name 4", Age = 11 }); // Act DataWiper.ClearAllData(database); // Assert database.Count<Dog>().Should().Be(0); } } [Theory] [MemberData(nameof(TestDialects))] public void Ignores_specified_tables(IDialect dialect) { using (var database = BlankDatabaseFactory.MakeDatabase(dialect)) { // Arrange database.Insert(new Dog { Name = "Some Name 1", Age = 10 }); string tableName; switch (dialect) { case SqlServer2012Dialect _: tableName = "dbo.Dogs"; break; case PostgreSqlDialect _: tableName = "public.dog"; break; default: throw new NotSupportedException("Unknown dialect: " + dialect.GetType().Name); } // Act DataWiper.ClearAllData(database, new HashSet<string> { tableName }); // Assert database.Count<Dog>().Should().Be(1); } } [Theory] [MemberData(nameof(TestDialects))] public void Deletes_data_from_foreign_keyed_tables(IDialect dialect) { using (var database = BlankDatabaseFactory.MakeDatabase(dialect)) { // Arrange var dogId = database.Insert<int>(new Dog { Name = "Some Name 1", Age = 10 }); database.Insert(new SimpleForeignKey { Name = "Some Name 1", DogId = dogId }); // Act DataWiper.ClearAllData(database); // Assert database.Count<Dog>().Should().Be(0); database.Count<SimpleForeignKey>().Should().Be(0); } } [Theory] [MemberData(nameof(TestDialects))] public void Errors_when_an_ignored_table_references_an_unignored_one(IDialect dialect) { using (var database = BlankDatabaseFactory.MakeDatabase(dialect)) { // Arrange var dogId = database.Insert<int>(new Dog { Name = "Some Name 1", Age = 10 }); database.Insert(new SimpleForeignKey { Name = "Some Name 1", DogId = dogId }); string tableName; switch (dialect) { case SqlServer2012Dialect _: tableName = "dbo.SimpleForeignKeys"; break; case PostgreSqlDialect _: tableName = "public.simple_foreign_key"; break; default: throw new NotSupportedException("Unknown dialect: " + dialect.GetType().Name); } // Act Action act = () => DataWiper.ClearAllData(database, new HashSet<string> { tableName }); // Assert act.Should().Throw<Exception>(); // Cleanup database.DeleteAll<SimpleForeignKey>(); } } [Theory] [MemberData(nameof(TestDialects))] public void Deletes_data_from_self_referenced_foreign_keyed_tables(IDialect dialect) { using (var database = BlankDatabaseFactory.MakeDatabase(dialect)) { // Arrange var id = database.Insert<int>(new SelfReferenceForeignKey()); database.Insert(new SelfReferenceForeignKey { ForeignId = id }); // Act DataWiper.ClearAllData(database); // Assert database.Count<SelfReferenceForeignKey>().Should().Be(0); } } [Theory] [MemberData(nameof(TestDialects))] public void Deletes_data_from_cyclic_foreign_keyed_tables(IDialect dialect) { using (var database = BlankDatabaseFactory.MakeDatabase(dialect)) { // Arrange var a = new CyclicForeignKeyA(); a.Id = database.Insert<int>(a); var b = new CyclicForeignKeyB { ForeignId = a.Id }; b.Id = database.Insert<int>(b); var c = new CyclicForeignKeyC { ForeignId = b.Id }; c.Id = database.Insert<int>(c); a.ForeignId = c.Id; database.Update(a); // Act DataWiper.ClearAllData(database); // Assert database.Count<CyclicForeignKeyA>().Should().Be(0); database.Count<CyclicForeignKeyB>().Should().Be(0); database.Count<CyclicForeignKeyC>().Should().Be(0); } } [Theory] [MemberData(nameof(TestDialects))] public void Deletes_data_from_tables_in_other_schemas(IDialect dialect) { using (var database = BlankDatabaseFactory.MakeDatabase(dialect)) { // Arrange var otherId = database.Insert<int>(new SchemaOther { Name = "Other" }); database.Insert(new SchemaSimpleForeignKeys { SchemaOtherId = otherId }); // Act DataWiper.ClearAllData(database); // Assert database.Count<SchemaOther>().Should().Be(0); database.Count<SchemaSimpleForeignKeys>().Should().Be(0); } } [Theory] [MemberData(nameof(TestDialects))] public void Ignores_tables_in_other_schemas(IDialect dialect) { using (var database = BlankDatabaseFactory.MakeDatabase(dialect)) { // Arrange database.Insert(new SchemaOther { Name = "Other" }); string name; switch (dialect) { case SqlServer2012Dialect _: name = "Other.SchemaOther"; break; case PostgreSqlDialect _: name = "other.schemaother"; break; default: throw new NotSupportedException("Unknown dialect: " + dialect.GetType().Name); } // Act DataWiper.ClearAllData(database, new HashSet<string> { name }); // Assert database.Count<SchemaOther>().Should().Be(1); } } [Theory] [MemberData(nameof(TestDialects))] public void Can_delete_tables_which_reference_another_twice(IDialect dialect) { using (var database = BlankDatabaseFactory.MakeDatabase(dialect)) { // Arrange var id = database.Insert<int>(new WipeMultipleForeignKeyTarget { Name = "Other" }); database.Insert(new WipeMultipleForeignKeySource { NameId = id, OptionalNameId = id }); // Act DataWiper.ClearAllData(database); // Assert database.Count<WipeMultipleForeignKeyTarget>().Should().Be(0); } } } } }
// TransactionSubmission.cs // // Copyright (c) 2013 Brent Knowles (http://www.brentknowles.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. // // Review documentation at http://www.yourothermind.com for updated implementation notes, license updates // or other general information/ // // Author information available at http://www.brentknowles.com or http://www.amazon.com/Brent-Knowles/e/B0035WW7OW // Full source code: https://github.com/BrentKnowles/YourOtherMind //### using System; using CoreUtilities; using System.ComponentModel.Composition; namespace Transactions { //[Export(typeof(TransactionBase))] // will be moved to an AddIn public class TransactionSubmission : TransactionBase { public const int T_SUBMISSION = 1001; public const int T_SUBMISSION_DESTINATION= 1005; /* Mapping Musing - Submissions * * date = date sent * * data1 - Guid of Layout * data2 - Guid of Market * data3 - Priority * data4 - WILL NOT BE USED * Expenses - Money1 * Earned - Money2 * DateReplied - Date2 * Notes - Notes * * Rights - Data5 * DraftVersionUsed - Data6 * * ReplyType - Data7 * ReplyFeedback - Data8 * * * SubmissionType - Data9 */ // a lookup function to translate a GUId to a project name // optional. public delegate string getprojectbyguiddelegate(string guid); public getprojectbyguiddelegate GetProjectFromGUID = null; // using this so I can simply have destinations inherit TransactionSubmission protected virtual void SetType() { RowData[TransactionsTable.TYPE.Index] = TransactionSubmission.T_SUBMISSION.ToString (); } public TransactionSubmission (DateTime dateSubmitted, string ProjectGUID, string MarketGUID, int Priority, float Money1, float Money2, DateTime DataReplied, string Notes, string Rights, string Version, string ReplyType, string ReplyFeedback, string SubmissionType, string MarketName) : base() { SetType (); RowData[TransactionsTable.DATE.Index] = dateSubmitted; RowData[TransactionsTable.DATA1_LAYOUTGUID.Index] = ProjectGUID; RowData[TransactionsTable.DATA2.Index] = MarketGUID; RowData[TransactionsTable.DATA3.Index] = Priority; RowData[TransactionsTable.MONEY1.Index] = Money1; // March 2013 - am assuming this must be expenses RowData[TransactionsTable.MONEY2.Index] = Money2; RowData[TransactionsTable.DATE2.Index] = DataReplied; RowData[TransactionsTable.NOTES.Index] = Notes; RowData[TransactionsTable.DATA5.Index] = Rights; RowData[TransactionsTable.DATA6.Index] = Version; RowData[TransactionsTable.DATA7.Index] = ReplyType; RowData[TransactionsTable.DATA8.Index] = ReplyFeedback; RowData[TransactionsTable.DATA9.Index] = SubmissionType; RowData[TransactionsTable.DATA10.Index] = MarketName; } public void SetID (string iD) { RowData[TransactionsTable.ID.Index ] = iD; } public TransactionSubmission() { } public TransactionSubmission(object[] items): base(items) { // all children need this form of the constructor } /* Mapping Musing - Submissions + * + * date = date sent + * + * data1 - Guid of Layout + * data2 - Guid of Market + * data3 - Priority + * data4 - WILL NOT BE USED + * Expenses - Money1 + * Earned - Money2 + * DateReplied - Date2 + * Notes - Notes + * * Rights - Data5 + * DraftVersionUsed - Data6 + * + * ReplyType - Data7 + * ReplyFeedback - Data8 + * + * + * SubmissionType - Data9 + */ public string ProjectGUID { get {return RowData[TransactionsTable.DATA1_LAYOUTGUID.Index].ToString ();} } public DateTime SubmissionDate { get { return DateTime.Parse (RowData [TransactionsTable.DATE.Index].ToString ());} set { RowData [TransactionsTable.DATE.Index] = value;} } public DateTime ReplyDate { get {return DateTime.Parse (RowData[TransactionsTable.DATE2.Index].ToString());} } public string Draft { get { return RowData [TransactionsTable.DATA6.Index].ToString();} } public string Rights { get {return RowData[TransactionsTable.DATA5.Index].ToString ();} } public string Notes { get {return RowData[TransactionsTable.NOTES.Index].ToString ();} } public string Priority { get {return RowData[TransactionsTable.DATA3.Index].ToString ();} } public string Replyfeedback { get { return RowData [TransactionsTable.DATA8.Index].ToString ();} } public decimal Earned { get { decimal fEarned = 0; try { fEarned = Decimal.Parse (RowData [TransactionsTable.MONEY2.Index].ToString ()); } catch (Exception) { fEarned = 0; } return fEarned; ; } set{ ;} } public decimal Expenses { get { decimal fPostage = 0; try { fPostage = Decimal.Parse(RowData[TransactionsTable.MONEY1.Index].ToString ()); } catch (Exception) { fPostage = 0; } return fPostage; ;} } public string MarketName { get {return RowData[TransactionsTable.DATA10.Index].ToString ();} } public string MarketGuid { get {return RowData[TransactionsTable.DATA2.Index].ToString ();} } public string ReplyType { get {return RowData[TransactionsTable.DATA7.Index].ToString ();} } public string SubmissionType { get {return RowData[TransactionsTable.DATA9.Index].ToString ();} } public override string Display { get { // string dataToAdd = String.Format("Date = {0};GuidOfLayout={1};GuidOfMarket={2};Priority {3}; Expenses{4};Earned{5};datereplied {6}; notes{7};"+ // "rights {8}; version {9}; reply type{10};reply feedback {11};sub type {12}", // // DateAsFriendlyString(), RowData[TransactionsTable.DATA1_LAYOUTGUID.Index], // RowData[TransactionsTable.DATA2.Index], RowData[TransactionsTable.DATA3.Index], // RowData[TransactionsTable.MONEY1.Index], RowData[TransactionsTable.MONEY2.Index], // RowData[TransactionsTable.DATE2.Index], RowData[TransactionsTable.NOTES.Index], // RowData[TransactionsTable.DATA5.Index], RowData[TransactionsTable.DATA6.Index], // RowData[TransactionsTable.DATA7.Index], RowData[TransactionsTable.DATA8.Index], // RowData[TransactionsTable.DATA9.Index]); // string debug = String.Format ("DEBUGGUID :[{0}]", RowData[TransactionsTable.DATA2.Index].ToString()); string dataToAdd =Loc.Instance.GetStringFmt ("Submitted to {0} on {1} [{2}] ", RowData[TransactionsTable.DATA10.Index], GetFriendlyDateForMostRecentDate (), RowData[TransactionsTable.DATA7.Index] ); return Loc.Instance.GetStringFmt("Submission {0}", dataToAdd); } } // For when a market is viewing a project public override string DisplayVariant { get { string ProjectName = Loc.Instance.GetString ("Unknown Project"); if (GetProjectFromGUID != null) { try { // if we have provided a lookup function then use it ProjectName = GetProjectFromGUID(ProjectGUID); } catch (Exception) { ProjectName = "error"; } } string date = GetFriendlyDateForMostRecentDate (); string dataToAdd =Loc.Instance.GetStringFmt ("{0} was submitted here on {1} [{2}]", ProjectName, date, RowData[TransactionsTable.DATA7.Index]); int DaysBetween = this.DaysInBetween(); return Loc.Instance.GetStringFmt("Submission {0} ({1} days out)", dataToAdd, DaysBetween); } } } }
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copyright (c) 2015 Jonathan Skeet. 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. #endregion namespace MoreLinq.Test { using System; using NUnit.Framework; using static FullJoinTest.Side; [TestFixture] public class FullJoinTest { public enum Side { Left, Right, Both } [Test] public void FullJoinWithHomogeneousSequencesIsLazy() { var xs = new BreakingSequence<int>(); var ys = new BreakingSequence<int>(); Assert.DoesNotThrow(() => xs.FullJoin(ys, e => e, BreakingFunc.Of<int, object>(), BreakingFunc.Of<int, object>(), BreakingFunc.Of<int, int, object>())); } [Test] public void FullJoinWithHomogeneousSequencesWithComparerIsLazy() { var xs = new BreakingSequence<int>(); var ys = new BreakingSequence<int>(); Assert.DoesNotThrow(() => xs.FullJoin(ys, e => e, BreakingFunc.Of<int, object>(), BreakingFunc.Of<int, object>(), BreakingFunc.Of<int, int, object>(), comparer: null)); } [Test] public void FullJoinIsLazy() { var xs = new BreakingSequence<int>(); var ys = new BreakingSequence<object>(); Assert.DoesNotThrow(() => xs.FullJoin(ys, x => x, y => y.GetHashCode(), BreakingFunc.Of<int, object>(), BreakingFunc.Of<object, object>(), BreakingFunc.Of<int, object, object>())); } [Test] public void FullJoinWithComparerIsLazy() { var xs = new BreakingSequence<int>(); var ys = new BreakingSequence<object>(); Assert.DoesNotThrow(() => xs.FullJoin(ys, x => x, y => y.GetHashCode(), BreakingFunc.Of<int, object>(), BreakingFunc.Of<object, object>(), BreakingFunc.Of<int, object, object>(), comparer: null)); } [Test] public void FullJoinResults() { var foo = (1, "foo"); var bar1 = (2, "bar"); var bar2 = (2, "Bar"); var bar3 = (2, "BAR"); var baz = (3, "baz"); var qux = (4, "qux"); var quux = (5, "quux"); var quuz = (6, "quuz"); var xs = new[] { foo, bar1, qux }; var ys = new[] { quux, bar2, baz, bar3, quuz }; var missing = default((int, string)); var result = xs.FullJoin(ys, x => x.Item1, y => y.Item1, x => (Left, x, missing), y => (Right, missing, y), (x, y) => (Both, x, y)); result.AssertSequenceEqual( (Left , foo , missing), (Both , bar1 , bar2 ), (Both , bar1 , bar3 ), (Left , qux , missing), (Right, missing, quux ), (Right, missing, baz ), (Right, missing, quuz )); } [Test] public void FullJoinWithComparerResults() { var foo = ("one" , "foo"); var bar1 = ("two" , "bar"); var bar2 = ("Two" , "bar"); var bar3 = ("TWO" , "bar"); var baz = ("three", "baz"); var qux = ("four" , "qux"); var quux = ("five" , "quux"); var quuz = ("six" , "quuz"); var xs = new[] { foo, bar1, qux }; var ys = new[] { quux, bar2, baz, bar3, quuz }; var missing = default((string, string)); var result = xs.FullJoin(ys, x => x.Item1, y => y.Item1, x => (Left, x, missing), y => (Right, missing, y), (x, y) => (Both, x, y), StringComparer.OrdinalIgnoreCase); result.AssertSequenceEqual( (Left , foo , missing), (Both , bar1 , bar2 ), (Both , bar1 , bar3 ), (Left , qux , missing), (Right, missing, quux ), (Right, missing, baz ), (Right, missing, quuz )); } [Test] public void FullJoinEmptyLeft() { var foo = (1, "foo"); var bar = (2, "bar"); var baz = (3, "baz"); var xs = new (int, string)[0]; var ys = new[] { foo, bar, baz }; var missing = default((int, string)); var result = xs.FullJoin(ys, x => x.Item1, y => y.Item1, x => (Left, x, missing), y => (Right, missing, y), (x, y) => (Both, x, y)); result.AssertSequenceEqual( (Right, missing, foo), (Right, missing, bar), (Right, missing, baz)); } [Test] public void FullJoinEmptyRight() { var foo = (1, "foo"); var bar = (2, "bar"); var baz = (3, "baz"); var xs = new[] { foo, bar, baz }; var ys = new (int, string)[0]; var missing = default((int, string)); var result = xs.FullJoin(ys, x => x.Item1, y => y.Item1, x => (Left, x, missing), y => (Right, missing, y), (x, y) => (Both, x, y)); result.AssertSequenceEqual( (Left, foo, missing), (Left, bar, missing), (Left, baz, missing)); } } }
// ============================================================ // RRDSharp: Managed implementation of RRDTool for .NET/Mono // ============================================================ // // Project Info: http://sourceforge.net/projects/rrdsharp/ // Project Lead: Julio David Quintana ([email protected]) // // Distributed under terms of the LGPL: // // This library is free software; you can redistribute it and/or modify it under the terms // of the GNU Lesser General internal 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 internal License for more details. // // You should have received a copy of the GNU Lesser General internal License along with this // library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, // Boston, MA 02111-1307, USA. using System; using System.Collections; using stRrd.Core; namespace stRrd.Graph { internal class RpnCalculator { internal const byte TKN_CONSTANT = 0; internal const byte TKN_DATASOURCE = 1; internal const byte TKN_PLUS = 2; internal const byte TKN_MINUS = 3; internal const byte TKN_MULTIPLY = 4; internal const byte TKN_DIVIDE = 5; internal const byte TKN_MOD = 6; internal const byte TKN_SIN = 7; internal const byte TKN_COS = 8; internal const byte TKN_LOG = 9; internal const byte TKN_EXP = 10; internal const byte TKN_FLOOR = 11; internal const byte TKN_CEIL = 12; internal const byte TKN_ROUND = 13; internal const byte TKN_POW = 14; internal const byte TKN_ABS = 15; internal const byte TKN_SQRT = 16; internal const byte TKN_RANDOM = 17; internal const byte TKN_LT = 18; internal const byte TKN_LE = 19; internal const byte TKN_GT = 20; internal const byte TKN_GE = 21; internal const byte TKN_EQ = 22; internal const byte TKN_IF = 23; internal const byte TKN_MIN = 24; internal const byte TKN_MAX = 25; internal const byte TKN_LIMIT = 26; internal const byte TKN_DUP = 27; internal const byte TKN_EXC = 28; internal const byte TKN_POP = 29; internal const byte TKN_UN = 30; internal const byte TKN_UNKN = 31; internal const byte TKN_NOW = 32; internal const byte TKN_TIME = 33; internal const byte TKN_PI = 34; internal const byte TKN_E = 35; internal const byte TKN_AND = 36; internal const byte TKN_OR = 37; internal const byte TKN_XOR = 38; internal const byte TKN_SAMPLES = 39; internal const byte TKN_STEP = 40; private double step; private Source[] sources; private ArrayList stack = new ArrayList(); internal RpnCalculator( Source[] sources, double step ) { this.sources = sources; this.step = step; } internal double Evaluate( Cdef cdef, int row, long timestamp ) { stack.Clear(); byte[] tokens = cdef.Tokens; int[] dsIndices = cdef.DsIndices; double[] constants = cdef.Constants; Random autoRand = new Random(); double x1, x2, x3; for ( int i = 0; i < tokens.Length; i++ ) { switch ( tokens[i] ) { case TKN_CONSTANT: Push( constants[i] ); break; case TKN_DATASOURCE: Push( sources[ dsIndices[i] ].Get(row) ); break; case TKN_PLUS: Push(Pop() + Pop()); break; case TKN_MINUS: x2 = Pop(); x1 = Pop(); Push(x1 - x2); break; case TKN_MULTIPLY: Push(Pop() * Pop()); break; case TKN_DIVIDE: x2 = Pop(); x1 = Pop(); Push(x1 / x2); break; case TKN_MOD: x2 = Pop(); x1 = Pop(); Push(x1 % x2); break; case TKN_SIN: Push(Math.Sin(Pop())); break; case TKN_COS: Push(Math.Cos(Pop())); break; case TKN_LOG: Push(Math.Log(Pop())); break; case TKN_EXP: Push(Math.Exp(Pop())); break; case TKN_FLOOR: Push(Math.Floor(Pop())); break; case TKN_CEIL: Push(Math.Ceiling(Pop())); break; case TKN_ROUND: Push(Math.Round(Pop(), MidpointRounding.AwayFromZero)); break; case TKN_POW: x2 = Pop(); x1 = Pop(); Push(Math.Pow(x1, x2)); break; case TKN_ABS: Push(Math.Abs(Pop())); break; case TKN_SQRT: Push(Math.Sqrt(Pop())); break; case TKN_RANDOM: Push(autoRand.Next()); break; case TKN_LT: x2 = Pop(); x1 = Pop(); Push(x1 < x2? 1: 0); break; case TKN_LE: x2 = Pop(); x1 = Pop(); Push(x1 <= x2? 1: 0); break; case TKN_GT: x2 = Pop(); x1 = Pop(); Push(x1 > x2? 1: 0); break; case TKN_GE: x2 = Pop(); x1 = Pop(); Push(x1 >= x2? 1: 0); break; case TKN_EQ: x2 = Pop(); x1 = Pop(); Push(x1 == x2? 1: 0); break; case TKN_IF: x3 = Pop(); x2 = Pop(); x1 = Pop(); Push(x1 != 0 ? x2: x3); break; case TKN_MIN: Push(Math.Min(Pop(), Pop())); break; case TKN_MAX: Push(Math.Max(Pop(), Pop())); break; case TKN_LIMIT: double high = Pop(), low = Pop(), val = Pop(); Push(val < low || val > high? Double.NaN: val); break; case TKN_DUP: double x = Pop(); Push(x); Push(x); break; case TKN_EXC: x2 = Pop(); x1 = Pop(); Push(x2); Push(x1); break; case TKN_POP: Pop(); break; case TKN_UN: Push(Double.IsNaN(Pop())? 1: 0); break; case TKN_UNKN: Push(Double.NaN); break; case TKN_NOW: Push(Util.Time); break; case TKN_TIME: Push(timestamp); break; case TKN_PI: Push(Math.PI); break; case TKN_E: Push(Math.E); break; case TKN_AND: x2 = Pop(); x1 = Pop(); Push((x1 != 0 && x2 != 0)? 1: 0); break; case TKN_OR: x2 = Pop(); x1 = Pop(); Push((x1 != 0 || x2 != 0)? 1: 0); break; case TKN_XOR: x2 = Pop(); x1 = Pop(); Push(((x1 != 0 && x2 == 0) || (x1 == 0 && x2 != 0))? 1: 0); break; case TKN_SAMPLES: Push (cdef.SampleCount); break; case TKN_STEP: Push( step ); break; } } if (stack.Count != 1) throw new RrdException("RPN error, invalid stack length"); return Pop(); } private void Push( double val ) { stack.Add( val ); } private double Pop() { int last = stack.Count - 1; if ( last < 0 ) throw new RrdException("POP failed, stack empty"); double lastValue = (double) stack[last]; stack.Remove(lastValue); return lastValue; } } }
using System; using System.Diagnostics; using Xunit; using LessIO; namespace LessMsi.Tests { public class TestBase { [DebuggerHidden] protected void ExtractAndCompareToMaster(string msiFileName) { var actualFileEntries = ExtractFilesFromMsi(msiFileName, null); var expectedEntries = GetExpectedEntriesForMsi(msiFileName); AssertAreEqual(expectedEntries, actualFileEntries); } [DebuggerHidden] protected static void AssertAreEqual(FileEntryGraph expected, FileEntryGraph actual) { string msg; if (!FileEntryGraph.CompareEntries(expected, actual, out msg)) { throw new Exception("FileEntryGraph entries are not the equal"); } } protected FileEntryGraph ExtractFilesFromMsi(string msiFileName, string[] fileNamesToExtractOrNull) { return ExtractFilesFromMsi(msiFileName, fileNamesToExtractOrNull, ""); } protected FileEntryGraph ExtractFilesFromMsi(string msiFileName, string[] fileNamesToExtractOrNull, string outputDir) { return ExtractFilesFromMsi(msiFileName, fileNamesToExtractOrNull, new Path(outputDir), true); } /// <summary> /// Extracts some or all of the files from the specified MSI and returns a <see cref="FileEntryGraph"/> representing the files that were extracted. /// </summary> /// <param name="msiFileName">The msi file to extract or null to extract all files.</param> /// <param name="fileNamesToExtractOrNull">The files to extract from the MSI or null to extract all files.</param> /// <param name="outputDir">A relative directory to extract output to or an empty string to use the default output directory.</param> /// <param name="skipReturningFileEntryGraph">True to return the <see cref="FileEntryGraph"/>. Otherwise null will be returned.</param> protected FileEntryGraph ExtractFilesFromMsi(string msiFileName, string[] fileNamesToExtractOrNull, Path outputDir, bool returnFileEntryGraph) { outputDir = GetTestOutputDir(outputDir, msiFileName); if (FileSystem.Exists(outputDir)) { FileSystem.RemoveDirectory(outputDir, true); } Debug.Assert(!FileSystem.Exists(outputDir), "Directory still exists!"); FileSystem.CreateDirectory(outputDir); //ExtractViaCommandLine(outputDir, msiFileName); ExtractInProcess(msiFileName, outputDir.PathString, fileNamesToExtractOrNull); if (returnFileEntryGraph) { // build actual file entries extracted var actualEntries = FileEntryGraph.GetActualEntries(outputDir.PathString, msiFileName); // dump to actual dir (for debugging and updating tests) actualEntries.Save(GetActualOutputFile(msiFileName)); return actualEntries; } else { return null; } } /// <summary> /// Returns a suitable output directory for test data while running the test. /// If <paramref name="outputDir"/> is specified it is used and <paramref name="testNameOrMsiFileName"/> is ignored. /// Alternatively, <paramref name="testNameOrMsiFileName"/> is used to generate a test dir. /// </summary> /// <param name="outputDir">The output dir to use or <see cref="Path.Empty"/>.</param> /// <param name="testNameOrMsiFileName"> /// A test name (often the name of a msi file under test) to use to generate a test dir when <paramref name="testNameOrMsiFileName"/> is not specified. /// </param> /// <returns></returns> protected Path GetTestOutputDir(Path outputDir, string testNameOrMsiFileName) { Path baseOutputDir = Path.Combine(AppPath, "MsiOutputTemp"); if (outputDir.IsEmpty || !outputDir.IsPathRooted) outputDir = Path.Combine(baseOutputDir, "_" + testNameOrMsiFileName); else outputDir = Path.Combine(baseOutputDir, outputDir); return outputDir; } private void ExtractInProcess(string msiFileName, string outputDir, string[] fileNamesToExtractOrNull) { //LessMsi.Program.DoExtraction(GetMsiTestFile(msiFileName).FullName, outputDir); if (fileNamesToExtractOrNull == null) { //extract everything: LessMsi.Msi.Wixtracts.ExtractFiles(GetMsiTestFile(msiFileName), outputDir, null, null); } else { LessMsi.Msi.Wixtracts.ExtractFiles(GetMsiTestFile(msiFileName), outputDir, fileNamesToExtractOrNull); } } /// <summary> /// This is an "old" way and it is difficul to debug (since it runs test out of proc), but it works. /// </summary> private void ExtractViaCommandLine(string msiFileName, string outputDir, string[] filenamesToExtractOrNull) { string args = string.Format(" /x \"{0}\" \"{1}\"", GetMsiTestFile(msiFileName), outputDir); if (filenamesToExtractOrNull != null && filenamesToExtractOrNull.Length > 0) throw new NotImplementedException(); string consoleOutput; RunCommandLine(args, out consoleOutput); } protected int RunCommandLine(string commandlineArgs) { string temp; return RunCommandLine(commandlineArgs, out temp); } /// <summary> /// Runs lessmsi.exe via commandline. /// </summary> /// <param name="commandlineArgs">The arguments passed to lessmsi.exe</param> /// <param name="consoleOutput">The console output.</param> /// <returns>The exe return code.</returns> protected int RunCommandLine(string commandlineArgs, out string consoleOutput) { // exec & wait var startInfo = new ProcessStartInfo(LessIO.Path.Combine(AppPath, "lessmsi.exe").PathString, commandlineArgs); startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; startInfo.UseShellExecute = false; var p = Process.Start(startInfo); bool exited = p.WaitForExit(1000*30); if (!exited) { p.Kill(); throw new Exception("Process did not exit for commandlineArgs:" + commandlineArgs); } consoleOutput = p.StandardOutput.ReadToEnd(); if (p.ExitCode == 0) Debug.WriteLine(consoleOutput); else { var errorOutput = p.StandardError.ReadToEnd(); throw new ExitCodeException(p.ExitCode, errorOutput, consoleOutput); } return p.ExitCode; } /// <summary> /// Same as <see cref="RunCommandLine"/>, is useful for debugging. /// </summary> /// <param name="commandLineArgs"></param> protected int RunCommandLineInProccess(string commandLineArgs) { //NOTE: Obviously oversimplified splitting of args. var args = commandLineArgs.Split(' '); for (var i = 0; i < args.Length; i++ ) { args[i] = args[i].Trim('\"'); } return LessMsi.Cli.Program.Main(args); } internal sealed class ExitCodeException : Exception { public ExitCodeException(int exitCode, string errorOutput, string consoleOutput) : base("lessmsi.exe returned an error code (" + exitCode + "). Error output was:\r\n" + errorOutput + "\r\nConsole output was:\r\n" + consoleOutput) { this.ExitCode = exitCode; } public int ExitCode { get; set; } } /// <summary> /// Loads the expected entries for the specified MSI file from the standard location. /// </summary> /// <param name="forMsi">The msi filename (no path) to load entries for.</param> /// <returns>The <see cref="FileEntryGraph"/> representing the files that are expected to be extracted from the MSI.</returns> protected FileEntryGraph GetExpectedEntriesForMsi(string forMsi) { return FileEntryGraph.Load(GetExpectedOutputFile(forMsi), forMsi); } private Path GetMsiTestFile(string msiFileName) { return Path.Combine(AppPath, "TestFiles", "MsiInput", msiFileName); } private Path GetExpectedOutputFile(string msiFileName) { return Path.Combine(AppPath, "TestFiles", "ExpectedOutput", msiFileName + ".expected.csv"); } protected Path GetActualOutputFile(string msiFileName) { // strip any subdirectories here since some input msi files have subdirectories. msiFileName = Path.GetFileName(msiFileName); var fi = Path.Combine(AppPath, msiFileName + ".actual.csv"); return fi; } protected Path AppPath { get { var codeBase = new Uri(this.GetType().Assembly.CodeBase); var local = new Path(codeBase.LocalPath); return local.Parent; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ShortKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AtRoot_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterClass_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterGlobalStatement_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterGlobalVariableDeclaration_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInUsingAlias() { VerifyAbsence( @"using Foo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterStackAlloc() { VerifyKeyword( @"class C { int* foo = stackalloc $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InFixedStatement() { VerifyKeyword( @"fixed ($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InDelegateReturnType() { VerifyKeyword( @"public delegate $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InCastType() { VerifyKeyword(AddInsideMethod( @"var str = (($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InCastType2() { VerifyKeyword(AddInsideMethod( @"var str = (($$)items) as string;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterOuterConst() { VerifyKeyword( @"class C { const $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterInnerConst() { VerifyKeyword(AddInsideMethod( @"const $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InEmptyStatement() { VerifyKeyword(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void EnumBaseTypes() { VerifyKeyword( @"enum E : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InGenericType1() { VerifyKeyword(AddInsideMethod( @"IList<$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InGenericType2() { VerifyKeyword(AddInsideMethod( @"IList<int,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InGenericType3() { VerifyKeyword(AddInsideMethod( @"IList<int[],$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InGenericType4() { VerifyKeyword(AddInsideMethod( @"IList<IFoo<int?,byte*>,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInBaseList() { VerifyAbsence( @"class C : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InGenericType_InBaseList() { VerifyKeyword( @"class C : IList<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterIs() { VerifyKeyword(AddInsideMethod( @"var v = foo is $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterAs() { VerifyKeyword(AddInsideMethod( @"var v = foo as $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterMethod() { VerifyKeyword( @"class C { void Foo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterField() { VerifyKeyword( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterProperty() { VerifyKeyword( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedAttribute() { VerifyKeyword( @"class C { [foo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InsideStruct() { VerifyKeyword( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InsideInterface() { VerifyKeyword( @"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InsideClass() { VerifyKeyword( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterPartial() { VerifyAbsence(@"partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterNestedPartial() { VerifyAbsence( @"class C { partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedAbstract() { VerifyKeyword( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedInternal() { VerifyKeyword( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedStaticPublic() { VerifyKeyword( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedPublicStatic() { VerifyKeyword( @"class C { public static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterVirtualPublic() { VerifyKeyword( @"class C { virtual public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedPublic() { VerifyKeyword( @"class C { public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedPrivate() { VerifyKeyword( @"class C { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedProtected() { VerifyKeyword( @"class C { protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedSealed() { VerifyKeyword( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedStatic() { VerifyKeyword( @"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InLocalVariableDeclaration() { VerifyKeyword(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InForVariableDeclaration() { VerifyKeyword(AddInsideMethod( @"for ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InForeachVariableDeclaration() { VerifyKeyword(AddInsideMethod( @"foreach ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InUsingVariableDeclaration() { VerifyKeyword(AddInsideMethod( @"using ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InFromVariableDeclaration() { VerifyKeyword(AddInsideMethod( @"var q = from $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InJoinVariableDeclaration() { VerifyKeyword(AddInsideMethod( @"var q = from a in b join $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterMethodOpenParen() { VerifyKeyword( @"class C { void Foo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterMethodComma() { VerifyKeyword( @"class C { void Foo(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterMethodAttribute() { VerifyKeyword( @"class C { void Foo(int i, [Foo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterConstructorOpenParen() { VerifyKeyword( @"class C { public C($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterConstructorComma() { VerifyKeyword( @"class C { public C(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterConstructorAttribute() { VerifyKeyword( @"class C { public C(int i, [Foo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterDelegateOpenParen() { VerifyKeyword( @"delegate void D($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterDelegateComma() { VerifyKeyword( @"delegate void D(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterDelegateAttribute() { VerifyKeyword( @"delegate void D(int i, [Foo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterThis() { VerifyKeyword( @"static class C { public static void Foo(this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterRef() { VerifyKeyword( @"class C { void Foo(ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterOut() { VerifyKeyword( @"class C { void Foo(out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterLambdaRef() { VerifyKeyword( @"class C { void Foo() { System.Func<int, int> f = (ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterLambdaOut() { VerifyKeyword( @"class C { void Foo() { System.Func<int, int> f = (out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterParams() { VerifyKeyword( @"class C { void Foo(params $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InImplicitOperator() { VerifyKeyword( @"class C { public static implicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InExplicitOperator() { VerifyKeyword( @"class C { public static explicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterIndexerBracket() { VerifyKeyword( @"class C { int this[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterIndexerBracketComma() { VerifyKeyword( @"class C { int this[int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNewInExpression() { VerifyKeyword(AddInsideMethod( @"new $$")); } [WorkItem(538804)] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InTypeOf() { VerifyKeyword(AddInsideMethod( @"typeof($$")); } [WorkItem(538804)] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InDefault() { VerifyKeyword(AddInsideMethod( @"default($$")); } [WorkItem(538804)] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InSizeOf() { VerifyKeyword(AddInsideMethod( @"sizeof($$")); } [WorkItem(544219)] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInObjectInitializerMemberContext() { VerifyAbsence(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [WorkItem(546938)] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InCrefContext() { VerifyKeyword(@" class Program { /// <see cref=""$$""> static void Main(string[] args) { } }"); } [WorkItem(546955)] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InCrefContextNotAfterDot() { VerifyAbsence(@" /// <see cref=""System.$$"" /> class C { } "); } [WorkItem(18374)] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterAsyncAsType() { VerifyAbsence(@"class c { async async $$ }"); } [WorkItem(1468, "https://github.com/dotnet/roslyn/issues/1468")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInCrefTypeParameter() { VerifyAbsence(@" using System; /// <see cref=""List{$$}"" /> class C { } "); } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cloudsearch-2013-01-01.normal.json service model. */ using System; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.CloudSearch.Model; using Amazon.CloudSearch.Model.Internal.MarshallTransformations; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.CloudSearch { /// <summary> /// Implementation for accessing CloudSearch /// /// Amazon CloudSearch Configuration Service /// <para> /// You use the Amazon CloudSearch configuration service to create, configure, and manage /// search domains. Configuration service requests are submitted using the AWS Query protocol. /// AWS Query requests are HTTP or HTTPS requests submitted via HTTP GET or POST with /// a query parameter named Action. /// </para> /// /// <para> /// The endpoint for configuration service requests is region-specific: cloudsearch.<i>region</i>.amazonaws.com. /// For example, cloudsearch.us-east-1.amazonaws.com. For a current list of supported /// regions and endpoints, see <a href="http://docs.aws.amazon.com/general/latest/gr/rande.html#cloudsearch_region" /// target="_blank">Regions and Endpoints</a>. /// </para> /// </summary> public partial class AmazonCloudSearchClient : AmazonServiceClient, IAmazonCloudSearch { #region Constructors /// <summary> /// Constructs AmazonCloudSearchClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> public AmazonCloudSearchClient(AWSCredentials credentials) : this(credentials, new AmazonCloudSearchConfig()) { } /// <summary> /// Constructs AmazonCloudSearchClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="region">The region to connect.</param> public AmazonCloudSearchClient(AWSCredentials credentials, RegionEndpoint region) : this(credentials, new AmazonCloudSearchConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonCloudSearchClient with AWS Credentials and an /// AmazonCloudSearchClient Configuration object. /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="clientConfig">The AmazonCloudSearchClient Configuration Object</param> public AmazonCloudSearchClient(AWSCredentials credentials, AmazonCloudSearchConfig clientConfig) : base(credentials, clientConfig) { } /// <summary> /// Constructs AmazonCloudSearchClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> public AmazonCloudSearchClient(string awsAccessKeyId, string awsSecretAccessKey) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonCloudSearchConfig()) { } /// <summary> /// Constructs AmazonCloudSearchClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="region">The region to connect.</param> public AmazonCloudSearchClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonCloudSearchConfig() {RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonCloudSearchClient with AWS Access Key ID, AWS Secret Key and an /// AmazonCloudSearchClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="clientConfig">The AmazonCloudSearchClient Configuration Object</param> public AmazonCloudSearchClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonCloudSearchConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, clientConfig) { } /// <summary> /// Constructs AmazonCloudSearchClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> public AmazonCloudSearchClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonCloudSearchConfig()) { } /// <summary> /// Constructs AmazonCloudSearchClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="region">The region to connect.</param> public AmazonCloudSearchClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonCloudSearchConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonCloudSearchClient with AWS Access Key ID, AWS Secret Key and an /// AmazonCloudSearchClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="clientConfig">The AmazonCloudSearchClient Configuration Object</param> public AmazonCloudSearchClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonCloudSearchConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig) { } #endregion #region Overrides /// <summary> /// Creates the signer for the service. /// </summary> protected override AbstractAWSSigner CreateSigner() { return new AWS4Signer(); } #endregion #region Dispose /// <summary> /// Disposes the service client. /// </summary> protected override void Dispose(bool disposing) { base.Dispose(disposing); } #endregion #region BuildSuggesters internal BuildSuggestersResponse BuildSuggesters(BuildSuggestersRequest request) { var marshaller = new BuildSuggestersRequestMarshaller(); var unmarshaller = BuildSuggestersResponseUnmarshaller.Instance; return Invoke<BuildSuggestersRequest,BuildSuggestersResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the BuildSuggesters operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the BuildSuggesters operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<BuildSuggestersResponse> BuildSuggestersAsync(BuildSuggestersRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new BuildSuggestersRequestMarshaller(); var unmarshaller = BuildSuggestersResponseUnmarshaller.Instance; return InvokeAsync<BuildSuggestersRequest,BuildSuggestersResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateDomain internal CreateDomainResponse CreateDomain(CreateDomainRequest request) { var marshaller = new CreateDomainRequestMarshaller(); var unmarshaller = CreateDomainResponseUnmarshaller.Instance; return Invoke<CreateDomainRequest,CreateDomainResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateDomain operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateDomain operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<CreateDomainResponse> CreateDomainAsync(CreateDomainRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateDomainRequestMarshaller(); var unmarshaller = CreateDomainResponseUnmarshaller.Instance; return InvokeAsync<CreateDomainRequest,CreateDomainResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DefineAnalysisScheme internal DefineAnalysisSchemeResponse DefineAnalysisScheme(DefineAnalysisSchemeRequest request) { var marshaller = new DefineAnalysisSchemeRequestMarshaller(); var unmarshaller = DefineAnalysisSchemeResponseUnmarshaller.Instance; return Invoke<DefineAnalysisSchemeRequest,DefineAnalysisSchemeResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DefineAnalysisScheme operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DefineAnalysisScheme operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DefineAnalysisSchemeResponse> DefineAnalysisSchemeAsync(DefineAnalysisSchemeRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DefineAnalysisSchemeRequestMarshaller(); var unmarshaller = DefineAnalysisSchemeResponseUnmarshaller.Instance; return InvokeAsync<DefineAnalysisSchemeRequest,DefineAnalysisSchemeResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DefineExpression internal DefineExpressionResponse DefineExpression(DefineExpressionRequest request) { var marshaller = new DefineExpressionRequestMarshaller(); var unmarshaller = DefineExpressionResponseUnmarshaller.Instance; return Invoke<DefineExpressionRequest,DefineExpressionResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DefineExpression operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DefineExpression operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DefineExpressionResponse> DefineExpressionAsync(DefineExpressionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DefineExpressionRequestMarshaller(); var unmarshaller = DefineExpressionResponseUnmarshaller.Instance; return InvokeAsync<DefineExpressionRequest,DefineExpressionResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DefineIndexField internal DefineIndexFieldResponse DefineIndexField(DefineIndexFieldRequest request) { var marshaller = new DefineIndexFieldRequestMarshaller(); var unmarshaller = DefineIndexFieldResponseUnmarshaller.Instance; return Invoke<DefineIndexFieldRequest,DefineIndexFieldResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DefineIndexField operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DefineIndexField operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DefineIndexFieldResponse> DefineIndexFieldAsync(DefineIndexFieldRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DefineIndexFieldRequestMarshaller(); var unmarshaller = DefineIndexFieldResponseUnmarshaller.Instance; return InvokeAsync<DefineIndexFieldRequest,DefineIndexFieldResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DefineSuggester internal DefineSuggesterResponse DefineSuggester(DefineSuggesterRequest request) { var marshaller = new DefineSuggesterRequestMarshaller(); var unmarshaller = DefineSuggesterResponseUnmarshaller.Instance; return Invoke<DefineSuggesterRequest,DefineSuggesterResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DefineSuggester operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DefineSuggester operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DefineSuggesterResponse> DefineSuggesterAsync(DefineSuggesterRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DefineSuggesterRequestMarshaller(); var unmarshaller = DefineSuggesterResponseUnmarshaller.Instance; return InvokeAsync<DefineSuggesterRequest,DefineSuggesterResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteAnalysisScheme internal DeleteAnalysisSchemeResponse DeleteAnalysisScheme(DeleteAnalysisSchemeRequest request) { var marshaller = new DeleteAnalysisSchemeRequestMarshaller(); var unmarshaller = DeleteAnalysisSchemeResponseUnmarshaller.Instance; return Invoke<DeleteAnalysisSchemeRequest,DeleteAnalysisSchemeResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteAnalysisScheme operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteAnalysisScheme operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DeleteAnalysisSchemeResponse> DeleteAnalysisSchemeAsync(DeleteAnalysisSchemeRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteAnalysisSchemeRequestMarshaller(); var unmarshaller = DeleteAnalysisSchemeResponseUnmarshaller.Instance; return InvokeAsync<DeleteAnalysisSchemeRequest,DeleteAnalysisSchemeResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteDomain internal DeleteDomainResponse DeleteDomain(DeleteDomainRequest request) { var marshaller = new DeleteDomainRequestMarshaller(); var unmarshaller = DeleteDomainResponseUnmarshaller.Instance; return Invoke<DeleteDomainRequest,DeleteDomainResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteDomain operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteDomain operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DeleteDomainResponse> DeleteDomainAsync(DeleteDomainRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteDomainRequestMarshaller(); var unmarshaller = DeleteDomainResponseUnmarshaller.Instance; return InvokeAsync<DeleteDomainRequest,DeleteDomainResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteExpression internal DeleteExpressionResponse DeleteExpression(DeleteExpressionRequest request) { var marshaller = new DeleteExpressionRequestMarshaller(); var unmarshaller = DeleteExpressionResponseUnmarshaller.Instance; return Invoke<DeleteExpressionRequest,DeleteExpressionResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteExpression operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteExpression operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DeleteExpressionResponse> DeleteExpressionAsync(DeleteExpressionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteExpressionRequestMarshaller(); var unmarshaller = DeleteExpressionResponseUnmarshaller.Instance; return InvokeAsync<DeleteExpressionRequest,DeleteExpressionResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteIndexField internal DeleteIndexFieldResponse DeleteIndexField(DeleteIndexFieldRequest request) { var marshaller = new DeleteIndexFieldRequestMarshaller(); var unmarshaller = DeleteIndexFieldResponseUnmarshaller.Instance; return Invoke<DeleteIndexFieldRequest,DeleteIndexFieldResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteIndexField operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteIndexField operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DeleteIndexFieldResponse> DeleteIndexFieldAsync(DeleteIndexFieldRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteIndexFieldRequestMarshaller(); var unmarshaller = DeleteIndexFieldResponseUnmarshaller.Instance; return InvokeAsync<DeleteIndexFieldRequest,DeleteIndexFieldResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteSuggester internal DeleteSuggesterResponse DeleteSuggester(DeleteSuggesterRequest request) { var marshaller = new DeleteSuggesterRequestMarshaller(); var unmarshaller = DeleteSuggesterResponseUnmarshaller.Instance; return Invoke<DeleteSuggesterRequest,DeleteSuggesterResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteSuggester operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteSuggester operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DeleteSuggesterResponse> DeleteSuggesterAsync(DeleteSuggesterRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteSuggesterRequestMarshaller(); var unmarshaller = DeleteSuggesterResponseUnmarshaller.Instance; return InvokeAsync<DeleteSuggesterRequest,DeleteSuggesterResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeAnalysisSchemes internal DescribeAnalysisSchemesResponse DescribeAnalysisSchemes(DescribeAnalysisSchemesRequest request) { var marshaller = new DescribeAnalysisSchemesRequestMarshaller(); var unmarshaller = DescribeAnalysisSchemesResponseUnmarshaller.Instance; return Invoke<DescribeAnalysisSchemesRequest,DescribeAnalysisSchemesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeAnalysisSchemes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeAnalysisSchemes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeAnalysisSchemesResponse> DescribeAnalysisSchemesAsync(DescribeAnalysisSchemesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeAnalysisSchemesRequestMarshaller(); var unmarshaller = DescribeAnalysisSchemesResponseUnmarshaller.Instance; return InvokeAsync<DescribeAnalysisSchemesRequest,DescribeAnalysisSchemesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeAvailabilityOptions internal DescribeAvailabilityOptionsResponse DescribeAvailabilityOptions(DescribeAvailabilityOptionsRequest request) { var marshaller = new DescribeAvailabilityOptionsRequestMarshaller(); var unmarshaller = DescribeAvailabilityOptionsResponseUnmarshaller.Instance; return Invoke<DescribeAvailabilityOptionsRequest,DescribeAvailabilityOptionsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeAvailabilityOptions operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeAvailabilityOptions operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeAvailabilityOptionsResponse> DescribeAvailabilityOptionsAsync(DescribeAvailabilityOptionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeAvailabilityOptionsRequestMarshaller(); var unmarshaller = DescribeAvailabilityOptionsResponseUnmarshaller.Instance; return InvokeAsync<DescribeAvailabilityOptionsRequest,DescribeAvailabilityOptionsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeDomains internal DescribeDomainsResponse DescribeDomains() { return DescribeDomains(new DescribeDomainsRequest()); } internal DescribeDomainsResponse DescribeDomains(DescribeDomainsRequest request) { var marshaller = new DescribeDomainsRequestMarshaller(); var unmarshaller = DescribeDomainsResponseUnmarshaller.Instance; return Invoke<DescribeDomainsRequest,DescribeDomainsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Gets information about the search domains owned by this account. Can be limited to /// specific domains. Shows all domains by default. To get the number of searchable documents /// in a domain, use the console or submit a <code>matchall</code> request to your domain's /// search endpoint: <code>q=matchall&amp;amp;q.parser=structured&amp;amp;size=0</code>. /// For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/getting-domain-info.html" /// target="_blank">Getting Information about a Search Domain</a> in the <i>Amazon CloudSearch /// Developer Guide</i>. /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeDomains service method, as returned by CloudSearch.</returns> /// <exception cref="Amazon.CloudSearch.Model.BaseException"> /// An error occurred while processing the request. /// </exception> /// <exception cref="Amazon.CloudSearch.Model.InternalException"> /// An internal error occurred while processing the request. If this problem persists, /// report an issue from the <a href="http://status.aws.amazon.com/" target="_blank">Service /// Health Dashboard</a>. /// </exception> public Task<DescribeDomainsResponse> DescribeDomainsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { return DescribeDomainsAsync(new DescribeDomainsRequest(), cancellationToken); } /// <summary> /// Initiates the asynchronous execution of the DescribeDomains operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeDomains operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeDomainsResponse> DescribeDomainsAsync(DescribeDomainsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeDomainsRequestMarshaller(); var unmarshaller = DescribeDomainsResponseUnmarshaller.Instance; return InvokeAsync<DescribeDomainsRequest,DescribeDomainsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeExpressions internal DescribeExpressionsResponse DescribeExpressions(DescribeExpressionsRequest request) { var marshaller = new DescribeExpressionsRequestMarshaller(); var unmarshaller = DescribeExpressionsResponseUnmarshaller.Instance; return Invoke<DescribeExpressionsRequest,DescribeExpressionsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeExpressions operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeExpressions operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeExpressionsResponse> DescribeExpressionsAsync(DescribeExpressionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeExpressionsRequestMarshaller(); var unmarshaller = DescribeExpressionsResponseUnmarshaller.Instance; return InvokeAsync<DescribeExpressionsRequest,DescribeExpressionsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeIndexFields internal DescribeIndexFieldsResponse DescribeIndexFields(DescribeIndexFieldsRequest request) { var marshaller = new DescribeIndexFieldsRequestMarshaller(); var unmarshaller = DescribeIndexFieldsResponseUnmarshaller.Instance; return Invoke<DescribeIndexFieldsRequest,DescribeIndexFieldsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeIndexFields operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeIndexFields operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeIndexFieldsResponse> DescribeIndexFieldsAsync(DescribeIndexFieldsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeIndexFieldsRequestMarshaller(); var unmarshaller = DescribeIndexFieldsResponseUnmarshaller.Instance; return InvokeAsync<DescribeIndexFieldsRequest,DescribeIndexFieldsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeScalingParameters internal DescribeScalingParametersResponse DescribeScalingParameters(DescribeScalingParametersRequest request) { var marshaller = new DescribeScalingParametersRequestMarshaller(); var unmarshaller = DescribeScalingParametersResponseUnmarshaller.Instance; return Invoke<DescribeScalingParametersRequest,DescribeScalingParametersResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeScalingParameters operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeScalingParameters operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeScalingParametersResponse> DescribeScalingParametersAsync(DescribeScalingParametersRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeScalingParametersRequestMarshaller(); var unmarshaller = DescribeScalingParametersResponseUnmarshaller.Instance; return InvokeAsync<DescribeScalingParametersRequest,DescribeScalingParametersResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeServiceAccessPolicies internal DescribeServiceAccessPoliciesResponse DescribeServiceAccessPolicies(DescribeServiceAccessPoliciesRequest request) { var marshaller = new DescribeServiceAccessPoliciesRequestMarshaller(); var unmarshaller = DescribeServiceAccessPoliciesResponseUnmarshaller.Instance; return Invoke<DescribeServiceAccessPoliciesRequest,DescribeServiceAccessPoliciesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeServiceAccessPolicies operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeServiceAccessPolicies operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeServiceAccessPoliciesResponse> DescribeServiceAccessPoliciesAsync(DescribeServiceAccessPoliciesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeServiceAccessPoliciesRequestMarshaller(); var unmarshaller = DescribeServiceAccessPoliciesResponseUnmarshaller.Instance; return InvokeAsync<DescribeServiceAccessPoliciesRequest,DescribeServiceAccessPoliciesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeSuggesters internal DescribeSuggestersResponse DescribeSuggesters(DescribeSuggestersRequest request) { var marshaller = new DescribeSuggestersRequestMarshaller(); var unmarshaller = DescribeSuggestersResponseUnmarshaller.Instance; return Invoke<DescribeSuggestersRequest,DescribeSuggestersResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeSuggesters operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeSuggesters operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeSuggestersResponse> DescribeSuggestersAsync(DescribeSuggestersRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeSuggestersRequestMarshaller(); var unmarshaller = DescribeSuggestersResponseUnmarshaller.Instance; return InvokeAsync<DescribeSuggestersRequest,DescribeSuggestersResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region IndexDocuments internal IndexDocumentsResponse IndexDocuments(IndexDocumentsRequest request) { var marshaller = new IndexDocumentsRequestMarshaller(); var unmarshaller = IndexDocumentsResponseUnmarshaller.Instance; return Invoke<IndexDocumentsRequest,IndexDocumentsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the IndexDocuments operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the IndexDocuments operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<IndexDocumentsResponse> IndexDocumentsAsync(IndexDocumentsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new IndexDocumentsRequestMarshaller(); var unmarshaller = IndexDocumentsResponseUnmarshaller.Instance; return InvokeAsync<IndexDocumentsRequest,IndexDocumentsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListDomainNames internal ListDomainNamesResponse ListDomainNames() { return ListDomainNames(new ListDomainNamesRequest()); } internal ListDomainNamesResponse ListDomainNames(ListDomainNamesRequest request) { var marshaller = new ListDomainNamesRequestMarshaller(); var unmarshaller = ListDomainNamesResponseUnmarshaller.Instance; return Invoke<ListDomainNamesRequest,ListDomainNamesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Lists all search domains owned by an account. /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListDomainNames service method, as returned by CloudSearch.</returns> /// <exception cref="Amazon.CloudSearch.Model.BaseException"> /// An error occurred while processing the request. /// </exception> public Task<ListDomainNamesResponse> ListDomainNamesAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { return ListDomainNamesAsync(new ListDomainNamesRequest(), cancellationToken); } /// <summary> /// Initiates the asynchronous execution of the ListDomainNames operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListDomainNames operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ListDomainNamesResponse> ListDomainNamesAsync(ListDomainNamesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListDomainNamesRequestMarshaller(); var unmarshaller = ListDomainNamesResponseUnmarshaller.Instance; return InvokeAsync<ListDomainNamesRequest,ListDomainNamesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region UpdateAvailabilityOptions internal UpdateAvailabilityOptionsResponse UpdateAvailabilityOptions(UpdateAvailabilityOptionsRequest request) { var marshaller = new UpdateAvailabilityOptionsRequestMarshaller(); var unmarshaller = UpdateAvailabilityOptionsResponseUnmarshaller.Instance; return Invoke<UpdateAvailabilityOptionsRequest,UpdateAvailabilityOptionsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the UpdateAvailabilityOptions operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateAvailabilityOptions operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<UpdateAvailabilityOptionsResponse> UpdateAvailabilityOptionsAsync(UpdateAvailabilityOptionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new UpdateAvailabilityOptionsRequestMarshaller(); var unmarshaller = UpdateAvailabilityOptionsResponseUnmarshaller.Instance; return InvokeAsync<UpdateAvailabilityOptionsRequest,UpdateAvailabilityOptionsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region UpdateScalingParameters internal UpdateScalingParametersResponse UpdateScalingParameters(UpdateScalingParametersRequest request) { var marshaller = new UpdateScalingParametersRequestMarshaller(); var unmarshaller = UpdateScalingParametersResponseUnmarshaller.Instance; return Invoke<UpdateScalingParametersRequest,UpdateScalingParametersResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the UpdateScalingParameters operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateScalingParameters operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<UpdateScalingParametersResponse> UpdateScalingParametersAsync(UpdateScalingParametersRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new UpdateScalingParametersRequestMarshaller(); var unmarshaller = UpdateScalingParametersResponseUnmarshaller.Instance; return InvokeAsync<UpdateScalingParametersRequest,UpdateScalingParametersResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region UpdateServiceAccessPolicies internal UpdateServiceAccessPoliciesResponse UpdateServiceAccessPolicies(UpdateServiceAccessPoliciesRequest request) { var marshaller = new UpdateServiceAccessPoliciesRequestMarshaller(); var unmarshaller = UpdateServiceAccessPoliciesResponseUnmarshaller.Instance; return Invoke<UpdateServiceAccessPoliciesRequest,UpdateServiceAccessPoliciesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the UpdateServiceAccessPolicies operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateServiceAccessPolicies operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<UpdateServiceAccessPoliciesResponse> UpdateServiceAccessPoliciesAsync(UpdateServiceAccessPoliciesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new UpdateServiceAccessPoliciesRequestMarshaller(); var unmarshaller = UpdateServiceAccessPoliciesResponseUnmarshaller.Instance; return InvokeAsync<UpdateServiceAccessPoliciesRequest,UpdateServiceAccessPoliciesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion } }
namespace LL.MDE.Components.Qvt.Transformation.EA2FMEA { using System; using System.Collections.Generic; using System.Linq; using LL.MDE.Components.Qvt.Common; using LL.MDE.DataModels.EnAr; using LL.MDE.DataModels.XML; public class RelationRootProperty2StructureElement { private readonly IMetaModelInterface editor; private readonly TransformationEA2FMEA transformation; private Dictionary<CheckOnlyDomains, EnforceDomains> traceabilityMap = new Dictionary<CheckOnlyDomains, EnforceDomains>(); public RelationRootProperty2StructureElement(IMetaModelInterface editor , TransformationEA2FMEA transformation ) { this.editor = editor;this.transformation = transformation; } public EnforceDomains FindPreviousResult(LL.MDE.DataModels.EnAr.Package abstractionLevelP,LL.MDE.DataModels.XML.Tag parentSeDecomposition,LL.MDE.DataModels.XML.Tag stucture) { CheckOnlyDomains input = new CheckOnlyDomains(abstractionLevelP,parentSeDecomposition,stucture); return traceabilityMap.ContainsKey(input) ? traceabilityMap[input] : null; } internal static ISet<CheckResultRootProperty2StructureElement> Check( LL.MDE.DataModels.EnAr.Package abstractionLevelP,LL.MDE.DataModels.XML.Tag parentSeDecomposition,LL.MDE.DataModels.XML.Tag stucture ) { ISet<CheckResultRootProperty2StructureElement> result = new HashSet<CheckResultRootProperty2StructureElement>();ISet<MatchDomainAbstractionLevelP> matchDomainAbstractionLevelPs = CheckDomainAbstractionLevelP(abstractionLevelP);ISet<MatchDomainParentSeDecomposition> matchDomainParentSeDecompositions = CheckDomainParentSeDecomposition(parentSeDecomposition);ISet<MatchDomainStucture> matchDomainStuctures = CheckDomainStucture(stucture);foreach (MatchDomainAbstractionLevelP matchDomainAbstractionLevelP in matchDomainAbstractionLevelPs ) {foreach (MatchDomainParentSeDecomposition matchDomainParentSeDecomposition in matchDomainParentSeDecompositions ) {foreach (MatchDomainStucture matchDomainStucture in matchDomainStuctures ) {LL.MDE.DataModels.EnAr.Package bpP = matchDomainAbstractionLevelP.bpP; LL.MDE.DataModels.EnAr.Element bpPE = matchDomainAbstractionLevelP.bpPE; LL.MDE.DataModels.EnAr.Element childEl = matchDomainAbstractionLevelP.childEl; string id = matchDomainAbstractionLevelP.id; string elName = matchDomainAbstractionLevelP.elName; long reid = matchDomainAbstractionLevelP.reid; LL.MDE.DataModels.EnAr.Element classifierEl = matchDomainAbstractionLevelP.classifierEl; string classifierName = matchDomainAbstractionLevelP.classifierName; CheckResultRootProperty2StructureElement checkonlysMatch = new CheckResultRootProperty2StructureElement () {matchDomainAbstractionLevelP = matchDomainAbstractionLevelP,matchDomainParentSeDecomposition = matchDomainParentSeDecomposition,matchDomainStucture = matchDomainStucture,}; result.Add(checkonlysMatch); } // End foreach } // End foreach } // End foreach return result; } internal static ISet<MatchDomainAbstractionLevelP> CheckDomainAbstractionLevelP(LL.MDE.DataModels.EnAr.Package abstractionLevelP) { ISet<MatchDomainAbstractionLevelP> result = new HashSet<MatchDomainAbstractionLevelP>(); foreach (LL.MDE.DataModels.EnAr.Package bpP in abstractionLevelP.Packages.OfType<LL.MDE.DataModels.EnAr.Package>()) { LL.MDE.DataModels.EnAr.Element bpPE = bpP.Element; if (bpP.ParentPackage() == abstractionLevelP) { foreach (LL.MDE.DataModels.EnAr.Element childEl in bpP.Elements.OfType<LL.MDE.DataModels.EnAr.Element>()) { if (bpPE.Stereotype == "block properties" && bpPE.ElementPackage() == bpP) { string id = childEl.ElementGUID; string elName = childEl.Name; long reid = childEl.ElementID; LL.MDE.DataModels.EnAr.Element classifierEl = childEl.Classifier(); if (childEl.Type == "Object" && childEl.ElementPackage() == bpP) { string classifierName = classifierEl.Name; MatchDomainAbstractionLevelP match = new MatchDomainAbstractionLevelP() { abstractionLevelP = abstractionLevelP, bpP = bpP, bpPE = bpPE, childEl = childEl, id = id, elName = elName, reid = reid, classifierEl = classifierEl, classifierName = classifierName, }; result.Add(match); }}} }} return result; } internal static ISet<MatchDomainParentSeDecomposition> CheckDomainParentSeDecomposition(LL.MDE.DataModels.XML.Tag parentSeDecomposition) { ISet<MatchDomainParentSeDecomposition> result = new HashSet<MatchDomainParentSeDecomposition>(); MatchDomainParentSeDecomposition match = new MatchDomainParentSeDecomposition() { parentSeDecomposition = parentSeDecomposition, }; result.Add(match); return result; } internal static ISet<MatchDomainStucture> CheckDomainStucture(LL.MDE.DataModels.XML.Tag stucture) { ISet<MatchDomainStucture> result = new HashSet<MatchDomainStucture>(); MatchDomainStucture match = new MatchDomainStucture() { stucture = stucture, }; result.Add(match); return result; } internal void CheckAndEnforce(LL.MDE.DataModels.EnAr.Package abstractionLevelP,LL.MDE.DataModels.XML.Tag parentSeDecomposition,LL.MDE.DataModels.XML.Tag stucture,LL.MDE.DataModels.XML.Tag structureElements ) { CheckOnlyDomains input = new CheckOnlyDomains(abstractionLevelP,parentSeDecomposition,stucture); EnforceDomains output = new EnforceDomains(structureElements); if (traceabilityMap.ContainsKey(input) && !traceabilityMap[input].Equals(output)) { throw new Exception("This relation has already been used with different enforced parameters!"); } if (!traceabilityMap.ContainsKey(input)) { ISet<CheckResultRootProperty2StructureElement> result = Check (abstractionLevelP,parentSeDecomposition,stucture); Enforce(result, structureElements); traceabilityMap[input] = output; } } internal void Enforce(ISet<CheckResultRootProperty2StructureElement> result, LL.MDE.DataModels.XML.Tag structureElements ) { foreach (CheckResultRootProperty2StructureElement match in result) { // Extracting variables binded in source domains LL.MDE.DataModels.EnAr.Package abstractionLevelP = match.matchDomainAbstractionLevelP.abstractionLevelP; LL.MDE.DataModels.EnAr.Package bpP = match.matchDomainAbstractionLevelP.bpP; LL.MDE.DataModels.EnAr.Element bpPE = match.matchDomainAbstractionLevelP.bpPE; LL.MDE.DataModels.EnAr.Element childEl = match.matchDomainAbstractionLevelP.childEl; string id = match.matchDomainAbstractionLevelP.id; string elName = match.matchDomainAbstractionLevelP.elName; long reid = match.matchDomainAbstractionLevelP.reid; LL.MDE.DataModels.EnAr.Element classifierEl = match.matchDomainAbstractionLevelP.classifierEl; string classifierName = match.matchDomainAbstractionLevelP.classifierName; LL.MDE.DataModels.XML.Tag parentSeDecomposition = match.matchDomainParentSeDecomposition.parentSeDecomposition; LL.MDE.DataModels.XML.Tag stucture = match.matchDomainStucture.stucture; // Assigning variables binded in the where clause string name=elName + ':' + classifierName; // Enforcing each enforced domain MatchDomainStructureElements targetMatchDomainStructureElements = EnforceStructureElements(id,name, structureElements ); // Retrieving variables binded in the enforced domains LL.MDE.DataModels.XML.Tag fmStructureelement = targetMatchDomainStructureElements.fmStructureelement; LL.MDE.DataModels.XML.Tag fmSeDecomposition = targetMatchDomainStructureElements.fmSeDecomposition; LL.MDE.DataModels.XML.Attribute structureId = targetMatchDomainStructureElements.structureId; LL.MDE.DataModels.XML.Tag longName1 = targetMatchDomainStructureElements.longName1; LL.MDE.DataModels.XML.Tag l41 = targetMatchDomainStructureElements.l41; LL.MDE.DataModels.XML.Attribute lAttr1 = targetMatchDomainStructureElements.lAttr1; // Calling other relations as defined in the where clause new RelationCreateDecompositionLink(editor,transformation).CheckAndEnforce(structureId,parentSeDecomposition);new RelationBlockProperty2StructureElement(editor,transformation).CheckAndEnforce(childEl,fmSeDecomposition,structureElements);} } internal MatchDomainStructureElements EnforceStructureElements(string id,string name, LL.MDE.DataModels.XML.Tag structureElements) { MatchDomainStructureElements match = new MatchDomainStructureElements(); // Contructing structureElements LL.MDE.DataModels.XML.Tag fmStructureelement = null; fmStructureelement = (LL.MDE.DataModels.XML.Tag) editor.CreateNewObjectInField(structureElements, "childTags"); // Contructing fmStructureelement editor.AddOrSetInField(fmStructureelement, "tagname", "FM-STRUCTURE-ELEMENT" ); LL.MDE.DataModels.XML.Tag fmSeDecomposition = null; fmSeDecomposition = (LL.MDE.DataModels.XML.Tag) editor.CreateNewObjectInField(fmStructureelement, "childTags"); LL.MDE.DataModels.XML.Attribute structureId = null; structureId = (LL.MDE.DataModels.XML.Attribute) editor.CreateNewObjectInField(fmStructureelement, "attributes"); LL.MDE.DataModels.XML.Tag longName1 = null; longName1 = (LL.MDE.DataModels.XML.Tag) editor.CreateNewObjectInField(fmStructureelement, "childTags"); // Contructing fmSeDecomposition editor.AddOrSetInField(fmSeDecomposition, "tagname", "FM-SE-DECOMPOSITION" ); // Contructing structureId editor.AddOrSetInField(structureId, "name", "ID" ); editor.AddOrSetInField(structureId, "value", id ); // Contructing longName1 editor.AddOrSetInField(longName1, "tagname", "LONG-NAME" ); LL.MDE.DataModels.XML.Tag l41 = null; l41 = (LL.MDE.DataModels.XML.Tag) editor.CreateNewObjectInField(longName1, "childTags"); // Contructing l41 editor.AddOrSetInField(l41, "tagname", "L-4" ); editor.AddOrSetInField(l41, "value", name ); LL.MDE.DataModels.XML.Attribute lAttr1 = null; lAttr1 = (LL.MDE.DataModels.XML.Attribute) editor.CreateNewObjectInField(l41, "attributes"); // Contructing lAttr1 editor.AddOrSetInField(lAttr1, "name", "L" ); editor.AddOrSetInField(lAttr1, "value", "r" ); // Return newly binded variables match.structureElements = structureElements; match.fmStructureelement = fmStructureelement; match.fmSeDecomposition = fmSeDecomposition; match.structureId = structureId; match.longName1 = longName1; match.l41 = l41; match.lAttr1 = lAttr1; return match; } public class CheckOnlyDomains : Tuple<Package,Tag,Tag> { public CheckOnlyDomains(Package abstractionLevelP,Tag parentSeDecomposition,Tag stucture) : base(abstractionLevelP,parentSeDecomposition,stucture) { } public Package abstractionLevelP { get { return Item1; } } public Tag parentSeDecomposition { get { return Item2; } } public Tag stucture { get { return Item3; } } } public class EnforceDomains : Tuple<Tag> { public EnforceDomains(Tag structureElements) : base(structureElements) { } public Tag structureElements { get { return Item1; } } } internal class CheckResultRootProperty2StructureElement { public MatchDomainAbstractionLevelP matchDomainAbstractionLevelP; public MatchDomainParentSeDecomposition matchDomainParentSeDecomposition; public MatchDomainStucture matchDomainStucture; } internal class MatchDomainAbstractionLevelP { public LL.MDE.DataModels.EnAr.Package abstractionLevelP; public LL.MDE.DataModels.EnAr.Package bpP; public LL.MDE.DataModels.EnAr.Element bpPE; public LL.MDE.DataModels.EnAr.Element childEl; public LL.MDE.DataModels.EnAr.Element classifierEl; public string classifierName; public string elName; public string id; public long reid; } internal class MatchDomainParentSeDecomposition { public LL.MDE.DataModels.XML.Tag parentSeDecomposition; } internal class MatchDomainStructureElements { public LL.MDE.DataModels.XML.Tag fmSeDecomposition; public LL.MDE.DataModels.XML.Tag fmStructureelement; public LL.MDE.DataModels.XML.Tag l41; public LL.MDE.DataModels.XML.Attribute lAttr1; public LL.MDE.DataModels.XML.Tag longName1; public LL.MDE.DataModels.XML.Tag structureElements; public LL.MDE.DataModels.XML.Attribute structureId; } internal class MatchDomainStucture { public LL.MDE.DataModels.XML.Tag stucture; } } }
// // ControlOverlay.cs // // Author: // Stephane Delcroix <[email protected]> // Larry Ewing <[email protected]> // // Copyright (C) 2007-2009 Novell, Inc. // Copyright (C) 2008-2009 Stephane Delcroix // Copyright (C) 2007 Larry Ewing // // 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 Cairo; using System; using FSpot.Gui; using FSpot.Utils; using Gtk; namespace FSpot { public class ControlOverlay : Window { Widget host; Window host_toplevel; bool composited; VisibilityType visibility; int round = 12; DelayedOperation hide; DelayedOperation fade; DelayedOperation dismiss; double x_align = 0.5; double y_align = 1.0; public enum VisibilityType { None, Partial, Full } public double XAlign { get { return x_align; } set { x_align = value; Relocate (); } } public double YAlign { get { return y_align; } set { y_align = value; Relocate (); } } public bool AutoHide { get; set; } = true; public VisibilityType Visibility { get { return visibility; } set { if (dismiss.IsPending && value != VisibilityType.None) return; switch (value) { case VisibilityType.None: FadeToTarget (0.0); break; case VisibilityType.Partial: FadeToTarget (0.4); break; case VisibilityType.Full: FadeToTarget (0.8); break; } visibility = value; } } public ControlOverlay (Widget host) : base (WindowType.Popup) { this.host = host; Decorated = false; DestroyWithParent = true; Name = "FullscreenContainer"; AllowGrow = true; //AllowShrink = true; KeepAbove = true; host_toplevel = (Window)host.Toplevel; TransientFor = host_toplevel; host_toplevel.ConfigureEvent += HandleHostConfigure; host_toplevel.SizeAllocated += HandleHostSizeAllocated; AddEvents ((int)(Gdk.EventMask.PointerMotionMask)); hide = new DelayedOperation (2000, HideControls); fade = new DelayedOperation (40, FadeToTarget); dismiss = new DelayedOperation (2000, delegate { /* do nothing */ return false; }); } protected override void OnDestroyed () { hide.Stop (); fade.Stop (); base.OnDestroyed (); } public bool HideControls () { int x, y; Gdk.ModifierType type; if (!AutoHide) return false; if (IsRealized) { GdkWindow.GetPointer (out x, out y, out type); if (Allocation.Contains (x, y)) { hide.Start (); return true; } } hide.Stop (); Visibility = VisibilityType.None; return false; } protected virtual void ShapeSurface (Context cr, Cairo.Color color) { cr.Operator = Operator.Source; Cairo.Pattern p = new Cairo.SolidPattern (new Cairo.Color (0, 0, 0, 0)); cr.SetSource (p); p.Dispose (); cr.Paint (); cr.Operator = Operator.Over; Cairo.Pattern r = new SolidPattern (color); cr.SetSource (r); r.Dispose (); cr.MoveTo (round, 0); if (x_align == 1.0) cr.LineTo (Allocation.Width, 0); else cr.Arc (Allocation.Width - round, round, round, -Math.PI * 0.5, 0); if (x_align == 1.0 || y_align == 1.0) cr.LineTo (Allocation.Width, Allocation.Height); else cr.Arc (Allocation.Width - round, Allocation.Height - round, round, 0, Math.PI * 0.5); if (y_align == 1.0) cr.LineTo (0, Allocation.Height); else cr.Arc (round, Allocation.Height - round, round, Math.PI * 0.5, Math.PI); cr.Arc (round, round, round, Math.PI, Math.PI * 1.5); cr.ClosePath (); cr.Fill (); } double target; double opacity = 0; bool FadeToTarget () { //Log.Debug ("op {0}\ttarget{1}", opacity, target); Visible = (opacity > 0.05); if (Math.Abs (target - opacity) < .05) return false; if (target > opacity) opacity += .04; else opacity -= .04; if (Visible) CompositeUtils.SetWinOpacity (this, opacity); else Hide (); return true; } bool FadeToTarget (double toTarget) { //Log.Debug ("FadeToTarget {0}", target); Realize (); target = toTarget; fade.Start (); if (toTarget > 0.0) hide.Restart (); return false; } void ShapeWindow () { if (composited) return; Gdk.Pixmap bitmap = new Gdk.Pixmap (GdkWindow, Allocation.Width, Allocation.Height, 1); Context cr = Gdk.CairoHelper.Create (bitmap); ShapeCombineMask (bitmap, 0, 0); ShapeSurface (cr, new Color (1, 1, 1)); ShapeCombineMask (bitmap, 0, 0); ((IDisposable)cr).Dispose (); bitmap.Dispose (); } protected override bool OnExposeEvent (Gdk.EventExpose args) { Gdk.Color c = Style.Background (State); Context cr = Gdk.CairoHelper.Create (GdkWindow); ShapeSurface (cr, new Cairo.Color (c.Red / (double)ushort.MaxValue, c.Blue / (double)ushort.MaxValue, c.Green / (double)ushort.MaxValue, 0.8)); ((IDisposable)cr).Dispose (); return base.OnExposeEvent (args); } protected override bool OnMotionNotifyEvent (Gdk.EventMotion args) { Visibility = VisibilityType.Full; base.OnMotionNotifyEvent (args); return false; } protected override void OnSizeAllocated (Gdk.Rectangle rec) { base.OnSizeAllocated (rec); Relocate (); ShapeWindow (); QueueDraw (); } void HandleHostSizeAllocated (object o, SizeAllocatedArgs args) { Relocate (); } void HandleHostConfigure (object o, ConfigureEventArgs args) { Relocate (); } void Relocate () { int x, y; if (!IsRealized || !host_toplevel.IsRealized) return; host.GdkWindow.GetOrigin (out x, out y); int xOrigin = x; int yOrigin = y; x += (int)(host.Allocation.Width * x_align); y += (int)(host.Allocation.Height * y_align); x -= (int)(Allocation.Width * 0.5); y -= (int)(Allocation.Height * 0.5); x = Math.Max (0, Math.Min (x, xOrigin + host.Allocation.Width - Allocation.Width)); y = Math.Max (0, Math.Min (y, yOrigin + host.Allocation.Height - Allocation.Height)); Move (x, y); } protected override void OnRealized () { composited = CompositeUtils.IsComposited (Screen) && CompositeUtils.SetRgbaColormap (this); AppPaintable = composited; base.OnRealized (); ShapeWindow (); Relocate (); } public void Dismiss () { Visibility = VisibilityType.None; dismiss.Start (); } protected override void OnMapped () { base.OnMapped (); Relocate (); } } }
using Lucene.Net.Attributes; using Lucene.Net.Support; using System; using System.Collections; using System.Diagnostics; namespace Lucene.Net.Util { using Lucene.Net.Randomized.Generators; using NUnit.Framework; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using DocIdSet = Lucene.Net.Search.DocIdSet; using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator; /// <summary> /// Base test class for <seealso cref="DocIdSet"/>s. </summary> public abstract class BaseDocIdSetTestCase<T> : LuceneTestCase where T : Lucene.Net.Search.DocIdSet { /// <summary> /// Create a copy of the given <seealso cref="BitSet"/> which has <code>length</code> bits. </summary> public abstract T CopyOf(BitArray bs, int length); /// <summary> /// Create a random set which has <code>numBitsSet</code> of its <code>numBits</code> bits set. </summary> protected internal static BitArray RandomSet(int numBits, int numBitsSet) { Debug.Assert(numBitsSet <= numBits); BitArray set = new BitArray(numBits); Random random = Random(); if (numBitsSet == numBits) { set.SafeSet(0, numBits != 0); //convert int to boolean } else { for (int i = 0; i < numBitsSet; ++i) { while (true) { int o = random.Next(numBits); if (!set.SafeGet(o)) { set.SafeSet(o, true); break; } } } } return set; } /// <summary> /// Same as <seealso cref="#randomSet(int, int)"/> but given a load factor. </summary> protected internal static BitArray RandomSet(int numBits, float percentSet) { return RandomSet(numBits, (int)(percentSet * numBits)); } /// <summary> /// Test length=0. /// </summary> [Test] public void TestNoBit() { BitArray bs = new BitArray(1); T copy = CopyOf(bs, 0); AssertEquals(0, bs, copy); } /// <summary> /// Test length=1. /// </summary> [Test] public void Test1Bit() { BitArray bs = new BitArray(1); if (Random().NextBoolean()) { bs.SafeSet(0, true); } T copy = CopyOf(bs, 1); AssertEquals(1, bs, copy); } /// <summary> /// Test length=2. /// </summary> [Test] public void Test2Bits() { BitArray bs = new BitArray(2); if (Random().NextBoolean()) { bs.SafeSet(0, true); } if (Random().NextBoolean()) { bs.SafeSet(1, true); } T copy = CopyOf(bs, 2); AssertEquals(2, bs, copy); } /// <summary> /// Compare the content of the set against a <seealso cref="BitSet"/>. /// </summary> [Test, Timeout(150000)] [LongRunningTest] public void TestAgainstBitSet() { int numBits = TestUtil.NextInt(Random(), 100, 1 << 20); // test various random sets with various load factors foreach (float percentSet in new float[] { 0f, 0.0001f, (float)Random().NextDouble() / 2, 0.9f, 1f }) { BitArray set = RandomSet(numBits, percentSet); T copy = CopyOf(set, numBits); AssertEquals(numBits, set, copy); } // test one doc BitArray set_ = new BitArray(numBits); set_.SafeSet(0, true); // 0 first T copy_ = CopyOf(set_, numBits); AssertEquals(numBits, set_, copy_); set_.SafeSet(0, false); set_.SafeSet(Random().Next(numBits), true); copy_ = CopyOf(set_, numBits); // then random index AssertEquals(numBits, set_, copy_); // test regular increments for (int inc = 2; inc < 1000; inc += TestUtil.NextInt(Random(), 1, 100)) { set_ = new BitArray(numBits); for (int d = Random().Next(10); d < numBits; d += inc) { set_.SafeSet(d, true); } copy_ = CopyOf(set_, numBits); AssertEquals(numBits, set_, copy_); } } /// <summary> /// Assert that the content of the <seealso cref="DocIdSet"/> is the same as the content of the <seealso cref="BitSet"/>. /// </summary> public virtual void AssertEquals(int numBits, BitArray ds1, T ds2) { // nextDoc DocIdSetIterator it2 = ds2.GetIterator(); if (it2 == null) { Assert.AreEqual(-1, ds1.NextSetBit(0)); } else { Assert.AreEqual(-1, it2.DocID()); for (int doc = ds1.NextSetBit(0); doc != -1; doc = ds1.NextSetBit(doc + 1)) { Assert.AreEqual(doc, it2.NextDoc()); Assert.AreEqual(doc, it2.DocID()); } Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, it2.NextDoc()); Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, it2.DocID()); } // nextDoc / advance it2 = ds2.GetIterator(); if (it2 == null) { Assert.AreEqual(-1, ds1.NextSetBit(0)); } else { for (int doc = -1; doc != DocIdSetIterator.NO_MORE_DOCS; ) { if (Random().NextBoolean()) { doc = ds1.NextSetBit(doc + 1); if (doc == -1) { doc = DocIdSetIterator.NO_MORE_DOCS; } Assert.AreEqual(doc, it2.NextDoc()); Assert.AreEqual(doc, it2.DocID()); } else { int target = doc + 1 + Random().Next(Random().NextBoolean() ? 64 : Math.Max(numBits / 8, 1)); doc = ds1.NextSetBit(target); if (doc == -1) { doc = DocIdSetIterator.NO_MORE_DOCS; } Assert.AreEqual(doc, it2.Advance(target)); Assert.AreEqual(doc, it2.DocID()); } } } // bits() Bits bits = ds2.GetBits(); if (bits != null) { // test consistency between bits and iterator it2 = ds2.GetIterator(); for (int previousDoc = -1, doc = it2.NextDoc(); ; previousDoc = doc, doc = it2.NextDoc()) { int max = doc == DocIdSetIterator.NO_MORE_DOCS ? bits.Length() : doc; for (int i = previousDoc + 1; i < max; ++i) { Assert.AreEqual(false, bits.Get(i)); } if (doc == DocIdSetIterator.NO_MORE_DOCS) { break; } Assert.AreEqual(true, bits.Get(doc)); } } } } }
namespace SideBySide; public class ConnectionPool : IClassFixture<DatabaseFixture> { [Theory] [InlineData(false, 11, 0L)] [InlineData(true, 12, 1L)] #if BASELINE // baseline default behaviour is to not reset the connection, which trades correctness for speed // see bug report at http://bugs.mysql.com/bug.php?id=77421 [InlineData(null, 13, 0L)] #else [InlineData(null, 13, 1L)] #endif public void ResetConnection(object connectionReset, int poolSize, long expected) { var csb = AppConfig.CreateConnectionStringBuilder(); csb.Pooling = true; csb.MaximumPoolSize = (uint) poolSize; // use a different pool size to create a unique connection string to force a unique pool to be created if (connectionReset is bool connectionResetValue) csb.ConnectionReset = connectionResetValue; using (var connection = new MySqlConnection(csb.ConnectionString)) { connection.Open(); using var command = connection.CreateCommand(); command.CommandText = "select @@autocommit;"; Assert.Equal(1L, command.ExecuteScalar()); } using (var connection = new MySqlConnection(csb.ConnectionString)) { connection.Open(); using var command = connection.CreateCommand(); command.CommandText = "SET autocommit=0;"; command.ExecuteNonQuery(); } using (var connection = new MySqlConnection(csb.ConnectionString)) { connection.Open(); using var command = connection.CreateCommand(); command.CommandText = "select @@autocommit;"; Assert.Equal(expected, command.ExecuteScalar()); } } [Fact] public async Task ExhaustConnectionPool() { var csb = AppConfig.CreateConnectionStringBuilder(); csb.Pooling = true; csb.MinimumPoolSize = 0; csb.MaximumPoolSize = 3; csb.ConnectionTimeout = 60; var connections = new List<MySqlConnection>(); for (int i = 0; i < csb.MaximumPoolSize; i++) { var connection = new MySqlConnection(csb.ConnectionString); await connection.OpenAsync().ConfigureAwait(false); connections.Add(connection); } var closeTask = Task.Run(() => { Thread.Sleep(5000); connections[0].Dispose(); connections.RemoveAt(0); }); using (var extraConnection = new MySqlConnection(csb.ConnectionString)) { var stopwatch = Stopwatch.StartNew(); await extraConnection.OpenAsync().ConfigureAwait(false); stopwatch.Stop(); Assert.InRange(stopwatch.ElapsedMilliseconds, 4500, 7500); } closeTask.Wait(); foreach (var connection in connections) connection.Dispose(); } [Fact] public async Task ExhaustConnectionPoolWithTimeout() { var csb = AppConfig.CreateConnectionStringBuilder(); csb.Pooling = true; csb.MinimumPoolSize = 0; csb.MaximumPoolSize = 3; csb.ConnectionTimeout = 5; var connections = new List<MySqlConnection>(); for (int i = 0; i < csb.MaximumPoolSize; i++) { var connection = new MySqlConnection(csb.ConnectionString); await connection.OpenAsync().ConfigureAwait(false); connections.Add(connection); } using (var extraConnection = new MySqlConnection(csb.ConnectionString)) { var stopwatch = Stopwatch.StartNew(); Assert.Throws<MySqlException>(() => extraConnection.Open()); stopwatch.Stop(); Assert.InRange(stopwatch.ElapsedMilliseconds, 4500, 6000); } foreach (var connection in connections) connection.Dispose(); } [Fact] public void LeakConnections() { var csb = AppConfig.CreateConnectionStringBuilder(); csb.Pooling = true; csb.MinimumPoolSize = 0; csb.MaximumPoolSize = 6; csb.ConnectionTimeout = 3u; for (int i = 0; i < csb.MaximumPoolSize + 2; i++) { var connection = new MySqlConnection(csb.ConnectionString); connection.Open(); // have to GC for leaked connections to be removed from the pool GC.Collect(); Thread.Sleep(400); } } [Fact] public async Task WaitTimeout() { var csb = AppConfig.CreateConnectionStringBuilder(); csb.Pooling = true; csb.MinimumPoolSize = 0; csb.MaximumPoolSize = 1; int serverThread; using (var connection = new MySqlConnection(csb.ConnectionString)) { await connection.OpenAsync(); using (var cmd = connection.CreateCommand()) { cmd.CommandText = "SET @@session.wait_timeout=3"; await cmd.ExecuteNonQueryAsync(); } serverThread = connection.ServerThread; } await Task.Delay(TimeSpan.FromSeconds(5)); using (var connection = new MySqlConnection(csb.ConnectionString)) { #if !BASELINE try #endif { await connection.OpenAsync(); Assert.NotEqual(serverThread, connection.ServerThread); } #if !BASELINE catch (MySqlProtocolException) when (csb.UseCompression) { // workaround for https://bugs.mysql.com/bug.php?id=103412 } #endif } } [Fact] public async Task CharacterSet() { var csb = AppConfig.CreateConnectionStringBuilder(); csb.Pooling = true; csb.MinimumPoolSize = 0; csb.MaximumPoolSize = 21; // use a uniqe pool size to create a unique connection string to force a unique pool to be created #if BASELINE csb.CharacterSet = "utf8mb4"; #endif // verify that connection charset is the same when retrieving a connection from the pool await CheckCharacterSetAsync(csb.ConnectionString).ConfigureAwait(false); await CheckCharacterSetAsync(csb.ConnectionString).ConfigureAwait(false); await CheckCharacterSetAsync(csb.ConnectionString).ConfigureAwait(false); } private async Task CheckCharacterSetAsync(string connectionString) { using var connection = new MySqlConnection(connectionString); await connection.OpenAsync().ConfigureAwait(false); using var cmd = connection.CreateCommand(); cmd.CommandText = @"select @@character_set_client, @@character_set_connection"; using var reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false); Assert.True(await reader.ReadAsync().ConfigureAwait(false)); Assert.Equal("utf8mb4", reader.GetString(0)); Assert.Equal("utf8mb4", reader.GetString(1)); Assert.False(await reader.ReadAsync().ConfigureAwait(false)); } [Fact] public async Task ClearConnectionPool() { var csb = AppConfig.CreateConnectionStringBuilder(); csb.Pooling = true; csb.MinimumPoolSize = 0; csb.MaximumPoolSize = 3; var connections = new List<MySqlConnection>(); for (int i = 0; i < csb.MaximumPoolSize; i++) { var connection = new MySqlConnection(csb.ConnectionString); connections.Add(connection); } Func<HashSet<long>> getConnectionIds = () => { var cids = GetConnectionIds(connections); Assert.Equal(connections.Count, cids.Count); return cids; }; Func<Task> openConnections = async () => { foreach (var connection in connections) { await connection.OpenAsync(); } }; Action closeConnections = () => { foreach (var connection in connections) { connection.Close(); } }; // connections should all be disposed when returned to pool await openConnections(); var connectionIds = getConnectionIds(); await ClearPoolAsync(connections[0]); closeConnections(); await openConnections(); var connectionIds2 = getConnectionIds(); Assert.Empty(connectionIds.Intersect(connectionIds2)); closeConnections(); // connections should all be disposed in ClearPoolAsync await ClearPoolAsync(connections[0]); await openConnections(); var connectionIds3 = getConnectionIds(); Assert.Empty(connectionIds2.Intersect(connectionIds3)); closeConnections(); // some connections may be disposed in ClearPoolAsync, others in OpenAsync var clearTask = ClearPoolAsync(connections[0]); await openConnections(); var connectionIds4 = GetConnectionIds(connections); Assert.Empty(connectionIds3.Intersect(connectionIds4)); await clearTask; closeConnections(); foreach (var connection in connections) connection.Dispose(); } #if !BASELINE [Theory] [InlineData(1u, 3u, 0u, 5u)] [InlineData(1u, 3u, 3u, 5u)] public async Task ConnectionLifeTime(uint idleTimeout, uint delaySeconds, uint minPoolSize, uint maxPoolSize) { var csb = AppConfig.CreateConnectionStringBuilder(); csb.Pooling = true; csb.MinimumPoolSize = minPoolSize; csb.MaximumPoolSize = maxPoolSize; csb.ConnectionIdleTimeout = idleTimeout; HashSet<int> serverThreadIdsBegin = new HashSet<int>(); HashSet<int> serverThreadIdsEnd = new HashSet<int>(); async Task OpenConnections(uint numConnections, HashSet<int> serverIdSet) { using var connection = new MySqlConnection(csb.ConnectionString); await connection.OpenAsync(); serverIdSet.Add(connection.ServerThread); if (--numConnections <= 0) return; await OpenConnections(numConnections, serverIdSet); } await OpenConnections(maxPoolSize, serverThreadIdsBegin); await Task.Delay(TimeSpan.FromSeconds(delaySeconds)); await OpenConnections(maxPoolSize, serverThreadIdsEnd); serverThreadIdsEnd.IntersectWith(serverThreadIdsBegin); Assert.Equal((int) minPoolSize, serverThreadIdsEnd.Count); } #endif private Task ClearPoolAsync(MySqlConnection connection) { #if BASELINE return connection.ClearPoolAsync(connection); #else return MySqlConnection.ClearPoolAsync(connection); #endif } private static HashSet<long> GetConnectionIds(IEnumerable<MySqlConnection> connections) => new HashSet<long>(connections.Select(x => (long) x.ServerThread)); }
using System; using System.Collections.Generic; using System.Linq; using Signum.Utilities; using Signum.Entities.Reflection; using System.Reflection; using Signum.Utilities.Reflection; using System.Linq.Expressions; using System.Globalization; using Signum.Utilities.ExpressionTrees; using System.Text.RegularExpressions; namespace Signum.Entities.DynamicQuery { public static class QueryUtils { public static string GetKey(object queryName) { return queryName is Type t ? Reflector.CleanTypeName(EnumEntity.Extract(t) ?? t) : queryName.ToString()!; } public static string GetNiceName(object queryName) { return queryName is Type t ? (EnumEntity.Extract(t) ?? t).NicePluralName() : queryName is Enum e ? e.NiceToString() : queryName.ToString()!; } public static FilterType GetFilterType(Type type) { FilterType? filterType = TryGetFilterType(type); if(filterType == null) throw new NotSupportedException("Type {0} not supported".FormatWith(type)); return filterType.Value; } public static FilterType? TryGetFilterType(Type type) { var uType = type.UnNullify(); if (uType == typeof(Guid)) return FilterType.Guid; if (uType == typeof(Date)) return FilterType.DateTime; if (uType.IsEnum) return FilterType.Enum; switch (Type.GetTypeCode(uType)) { case TypeCode.Boolean: return FilterType.Boolean; case TypeCode.Double: case TypeCode.Decimal: case TypeCode.Single: return FilterType.Decimal; case TypeCode.Byte: case TypeCode.SByte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: return FilterType.Integer; case TypeCode.DateTime: return FilterType.DateTime; case TypeCode.Char: case TypeCode.String: return FilterType.String; case TypeCode.Object: if (type.IsLite()) return FilterType.Lite; if (type.IsIEntity()) return FilterType.Lite; if (type.IsEmbeddedEntity()) return FilterType.Embedded; goto default; default: return null; } } public static List<FilterOperation> GetFilterOperations(FilterType filtertype) { return FilterOperations[filtertype]; } static readonly Dictionary<FilterType, List<FilterOperation>> FilterOperations = new Dictionary<FilterType, List<FilterOperation>> { { FilterType.String, new List<FilterOperation> { FilterOperation.Contains, FilterOperation.EqualTo, FilterOperation.StartsWith, FilterOperation.EndsWith, FilterOperation.Like, FilterOperation.NotContains, FilterOperation.DistinctTo, FilterOperation.NotStartsWith, FilterOperation.NotEndsWith, FilterOperation.NotLike, FilterOperation.IsIn, FilterOperation.IsNotIn } }, { FilterType.DateTime, new List<FilterOperation> { FilterOperation.EqualTo, FilterOperation.DistinctTo, FilterOperation.GreaterThan, FilterOperation.GreaterThanOrEqual, FilterOperation.LessThan, FilterOperation.LessThanOrEqual, FilterOperation.IsIn, FilterOperation.IsNotIn, } }, { FilterType.Integer, new List<FilterOperation> { FilterOperation.EqualTo, FilterOperation.DistinctTo, FilterOperation.GreaterThan, FilterOperation.GreaterThanOrEqual, FilterOperation.LessThan, FilterOperation.LessThanOrEqual, FilterOperation.IsIn, FilterOperation.IsNotIn, } }, { FilterType.Decimal, new List<FilterOperation> { FilterOperation.EqualTo, FilterOperation.DistinctTo, FilterOperation.GreaterThan, FilterOperation.GreaterThanOrEqual, FilterOperation.LessThan, FilterOperation.LessThanOrEqual, FilterOperation.IsIn, FilterOperation.IsNotIn, } }, { FilterType.Enum, new List<FilterOperation> { FilterOperation.EqualTo, FilterOperation.DistinctTo, FilterOperation.IsIn, FilterOperation.IsNotIn, FilterOperation.GreaterThan, FilterOperation.GreaterThanOrEqual, FilterOperation.LessThan, FilterOperation.LessThanOrEqual, } }, { FilterType.Guid, new List<FilterOperation> { FilterOperation.EqualTo, FilterOperation.DistinctTo, FilterOperation.IsIn, FilterOperation.IsNotIn, } }, { FilterType.Lite, new List<FilterOperation> { FilterOperation.EqualTo, FilterOperation.DistinctTo, FilterOperation.IsIn, FilterOperation.IsNotIn, } }, { FilterType.Embedded, new List<FilterOperation> { FilterOperation.EqualTo, FilterOperation.DistinctTo, } }, { FilterType.Boolean, new List<FilterOperation> { FilterOperation.EqualTo, FilterOperation.DistinctTo, } }, }; public static QueryToken? SubToken(QueryToken? token, QueryDescription qd, SubTokensOptions options, string key) { var result = SubTokenBasic(token, qd, options, key); if (result != null) return result; if ((options & SubTokensOptions.CanAggregate) != 0) return AggregateTokens(token, qd).SingleOrDefaultEx(a => a.Key == key); return null; } public static List<QueryToken> SubTokens(this QueryToken? token, QueryDescription qd, SubTokensOptions options) { var result = SubTokensBasic(token, qd, options); if ((options & SubTokensOptions.CanAggregate) != 0) result.InsertRange(0, AggregateTokens(token, qd)); return result; } private static IEnumerable<QueryToken> AggregateTokens(QueryToken? token, QueryDescription qd) { if (token == null) { yield return new AggregateToken(AggregateFunction.Count, qd.QueryName); } else if (!(token is AggregateToken)) { FilterType? ft = QueryUtils.TryGetFilterType(token.Type); if (ft == FilterType.Integer || ft == FilterType.Decimal || ft == FilterType.Boolean) { yield return new AggregateToken(AggregateFunction.Average, token); yield return new AggregateToken(AggregateFunction.Sum, token); yield return new AggregateToken(AggregateFunction.Min, token); yield return new AggregateToken(AggregateFunction.Max, token); } else if (ft == FilterType.DateTime) /*ft == FilterType.String || */ { yield return new AggregateToken(AggregateFunction.Min, token); yield return new AggregateToken(AggregateFunction.Max, token); } if(ft != null) { yield return new AggregateToken(AggregateFunction.Count, token, FilterOperation.DistinctTo, null); yield return new AggregateToken(AggregateFunction.Count, token, FilterOperation.EqualTo, null); } if (token.IsGroupable) { yield return new AggregateToken(AggregateFunction.Count, token, distinct: true); } if (ft == FilterType.Enum) { foreach (var v in Enum.GetValues(token.Type.UnNullify())) { yield return new AggregateToken(AggregateFunction.Count, token, FilterOperation.EqualTo, v); yield return new AggregateToken(AggregateFunction.Count, token, FilterOperation.DistinctTo, v); } } if (ft == FilterType.Boolean) { yield return new AggregateToken(AggregateFunction.Count, token, FilterOperation.EqualTo, true); yield return new AggregateToken(AggregateFunction.Count, token, FilterOperation.EqualTo, false); } } } static QueryToken? SubTokenBasic(QueryToken? token, QueryDescription qd, SubTokensOptions options, string key) { if (token == null) { var column = qd.Columns.SingleOrDefaultEx(a=>a.Name == key); if (column == null) return null; return new ColumnToken(column, qd.QueryName); } else { return token.SubTokenInternal(key, options); } } public static Func<bool>? MergeEntityColumns = null; static List<QueryToken> SubTokensBasic(QueryToken? token, QueryDescription qd, SubTokensOptions options) { if (token == null) { if (MergeEntityColumns != null && !MergeEntityColumns()) return qd.Columns.Select(cd => (QueryToken)new ColumnToken(cd, qd.QueryName)).ToList(); var dictonary = qd.Columns.Where(a => !a.IsEntity).Select(cd => (QueryToken)new ColumnToken(cd, qd.QueryName)).ToDictionary(t => t.Key); var entity = new ColumnToken(qd.Columns.SingleEx(a => a.IsEntity), qd.QueryName); dictonary.Add(entity.Key, entity); foreach (var item in entity.SubTokensInternal(options).OrderByDescending(a=>a.Priority).ThenBy(a => a.ToString())) { if (!dictonary.ContainsKey(item.Key)) { dictonary.Add(item.Key, item); } } return dictonary.Values.ToList(); } else return token.SubTokensInternal(options); } public static bool IsColumnToken(string tokenString) { return tokenString.IndexOf('.') == -1 && tokenString != "Entity"; } public static QueryToken Parse(string tokenString, QueryDescription qd, SubTokensOptions options) { if (string.IsNullOrEmpty(tokenString)) throw new ArgumentNullException(nameof(tokenString)); //https://stackoverflow.com/questions/35418597/split-string-on-the-dot-characters-that-are-not-inside-of-brackets string[] parts = Regex.Split(tokenString, @"\.(?!([^[]*\]|[^(]*\)))"); string firstPart = parts.FirstEx(); QueryToken? result = SubToken(null, qd, options, firstPart); if (result == null) throw new FormatException("Column {0} not found on query {1}".FormatWith(firstPart, QueryUtils.GetKey(qd.QueryName))); foreach (var part in parts.Skip(1)) { var newResult = SubToken(result, qd, options, part); result = newResult ?? throw new FormatException("Token with key '{0}' not found on {1} of query {2}".FormatWith(part, result.FullKey(), QueryUtils.GetKey(qd.QueryName))); } return result; } public static string? CanFilter(QueryToken token) { if (token == null) return "No column selected"; if (token.Type != typeof(string) && token.Type.ElementType() != null) return "You can not filter by collections, continue the sequence"; return null; } public static string? CanColumn(QueryToken token) { if (token == null) return "No column selected"; if (token.Type != typeof(string) && token.Type != typeof(byte[]) && token.Type.ElementType() != null) return "You can not add collections as columns"; if (token.HasAllOrAny()) return "Columns can not contain '{0}', '{1}', {2} or {3}".FormatWith( CollectionAnyAllType.All.NiceToString(), CollectionAnyAllType.Any.NiceToString(), CollectionAnyAllType.NoOne.NiceToString(), CollectionAnyAllType.AnyNo.NiceToString()); return null; } public static Dictionary<Type, Func<Expression, Expression>> OrderAdapters = new Dictionary<Type, Func<Expression, Expression>>(); public static LambdaExpression CreateOrderLambda(QueryToken token, BuildExpressionContext ctx) { var body = token.BuildExpression(ctx); var adapter = QueryUtils.OrderAdapters.TryGetC(token.Type); if (adapter != null) body = adapter(body); return Expression.Lambda(body, ctx.Parameter); } public static string? CanOrder(QueryToken token) { if (token == null) return "No column selected"; if (token.Type.IsEmbeddedEntity() && !OrderAdapters.ContainsKey(token.Type)) return "{0} can not be ordered".FormatWith(token.Type.NicePluralName()); if (QueryToken.IsCollection(token.Type)) return "Collections can not be ordered"; if (token.HasAllOrAny()) return "'{0}', '{1}', '{2}' or '{3}' can not be ordered".FormatWith( CollectionAnyAllType.All.NiceToString(), CollectionAnyAllType.Any.NiceToString(), CollectionAnyAllType.NoOne.NiceToString(), CollectionAnyAllType.AnyNo.NiceToString()); return null; } static readonly MethodInfo miToLite = ReflectionTools.GetMethodInfo((Entity ident) => ident.ToLite()).GetGenericMethodDefinition(); internal static Expression ExtractEntity(this Expression expression, bool idAndToStr) { if (expression.Type.IsLite()) { if (expression is MethodCallExpression mce && mce.Method.IsInstantiationOf(miToLite)) return mce.Arguments[0]; if (!idAndToStr) return Expression.Property(expression, "Entity"); } return expression; } internal static Expression BuildLiteNulifyUnwrapPrimaryKey(this Expression expression, PropertyRoute[] routes) { var buildLite = BuildLite(expression); var primaryKey = UnwrapPrimaryKey(buildLite, routes); var nullify = primaryKey.Nullify(); return nullify; } internal static Type BuildLiteNullifyUnwrapPrimaryKey(this Type type, PropertyRoute[] routes) { var buildLite = BuildLite(type); var primaryKey = UnwrapPrimaryKey(buildLite, routes); var nullify = primaryKey.Nullify(); return nullify; } internal static Expression UnwrapPrimaryKey(Expression expression, PropertyRoute[] routes) { if (expression.Type.UnNullify() == typeof(PrimaryKey)) { var unwrappedType = routes.Select(r => PrimaryKey.Type(r.RootType)).Distinct().SingleEx(); return Expression.Convert(Expression.Field(expression.UnNullify(), "Object"), unwrappedType.Nullify()); } return expression; } internal static Type UnwrapPrimaryKey(Type type, PropertyRoute[] routes) { if (type.UnNullify() == typeof(PrimaryKey)) { return routes.Select(r => PrimaryKey.Type(r.RootType)).Distinct().SingleEx().Nullify(); } return type; } internal static Expression BuildLite(this Expression expression) { if (Reflector.IsIEntity(expression.Type)) return Expression.Call(miToLite.MakeGenericMethod(expression.Type), expression); return expression; } internal static Type BuildLite(this Type type) { if (Reflector.IsIEntity(type)) return Lite.Generate(type); return type; } static readonly MethodInfo miContains = ReflectionTools.GetMethodInfo((string s) => s.Contains(s, StringComparison.InvariantCultureIgnoreCase)); static readonly MethodInfo miStartsWith = ReflectionTools.GetMethodInfo((string s) => s.StartsWith(s, StringComparison.InvariantCultureIgnoreCase)); static readonly MethodInfo miEndsWith = ReflectionTools.GetMethodInfo((string s) => s.EndsWith(s, StringComparison.InvariantCultureIgnoreCase)); static readonly MethodInfo miLike = ReflectionTools.GetMethodInfo((string s) => s.Like(s)); static readonly MethodInfo miDistinctNullable = ReflectionTools.GetMethodInfo((string s) => LinqHints.DistinctNull<int>(null, null)).GetGenericMethodDefinition(); static readonly MethodInfo miDistinct = ReflectionTools.GetMethodInfo((string s) => LinqHints.DistinctNull<string>(null, null)).GetGenericMethodDefinition(); public static Expression GetCompareExpression(FilterOperation operation, Expression left, Expression right, bool inMemory = false) { switch (operation) { case FilterOperation.EqualTo: return Expression.Equal(left, right); case FilterOperation.DistinctTo: { var t = left.Type.UnNullify(); var mi = t.IsValueType ? miDistinctNullable : miDistinct; return Expression.Call(mi.MakeGenericMethod(t), left.Nullify(), right.Nullify()); } case FilterOperation.GreaterThan: return Expression.GreaterThan(CastNumber(left), CastNumber(right)); case FilterOperation.GreaterThanOrEqual: return Expression.GreaterThanOrEqual(CastNumber(left), CastNumber(right)); case FilterOperation.LessThan: return Expression.LessThan(CastNumber(left), CastNumber(right)); case FilterOperation.LessThanOrEqual: return Expression.LessThanOrEqual(CastNumber(left), CastNumber(right)); case FilterOperation.Contains: return Expression.Call(Fix(left, inMemory), miContains, right, Expression.Constant(StringComparison.InvariantCultureIgnoreCase)); case FilterOperation.StartsWith: return Expression.Call(Fix(left, inMemory), miStartsWith, right, Expression.Constant(StringComparison.InvariantCultureIgnoreCase)); case FilterOperation.EndsWith: return Expression.Call(Fix(left, inMemory), miEndsWith, right, Expression.Constant(StringComparison.InvariantCultureIgnoreCase)); case FilterOperation.Like: return Expression.Call(miLike, Fix(left, inMemory), right); case FilterOperation.NotContains: return Expression.Not(Expression.Call(Fix(left, inMemory), miContains, right)); case FilterOperation.NotStartsWith: return Expression.Not(Expression.Call(Fix(left, inMemory), miStartsWith, right)); case FilterOperation.NotEndsWith: return Expression.Not(Expression.Call(Fix(left, inMemory), miEndsWith, right)); case FilterOperation.NotLike: return Expression.Not(Expression.Call(miLike, Fix(left, inMemory), right)); default: throw new InvalidOperationException("Unknown operation {0}".FormatWith(operation)); } } static Expression CastNumber(Expression expression) { var type = expression.Type.UnNullify(); if (!type.IsEnum) return expression; var uType = Enum.GetUnderlyingType(type); if(expression.Type.IsNullable()) uType = uType.Nullify(); return Expression.Convert(expression, uType); } private static Expression Fix(Expression left, bool inMemory) { if (inMemory) return Expression.Coalesce(left, Expression.Constant("")); return left; } public static bool IsList(this FilterOperation fo) { return fo == FilterOperation.IsIn || fo == FilterOperation.IsNotIn; } } public enum SubTokensOptions { CanAggregate = 1, CanAnyAll = 2, CanElement = 4, } }