context
stringlengths
2.52k
185k
gt
stringclasses
1 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.V8.Resources { /// <summary>Resource name for the <c>MerchantCenterLink</c> resource.</summary> public sealed partial class MerchantCenterLinkName : gax::IResourceName, sys::IEquatable<MerchantCenterLinkName> { /// <summary>The possible contents of <see cref="MerchantCenterLinkName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/merchantCenterLinks/{merchant_center_id}</c>. /// </summary> CustomerMerchantCenter = 1, } private static gax::PathTemplate s_customerMerchantCenter = new gax::PathTemplate("customers/{customer_id}/merchantCenterLinks/{merchant_center_id}"); /// <summary>Creates a <see cref="MerchantCenterLinkName"/> 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="MerchantCenterLinkName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static MerchantCenterLinkName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new MerchantCenterLinkName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="MerchantCenterLinkName"/> with the pattern /// <c>customers/{customer_id}/merchantCenterLinks/{merchant_center_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="merchantCenterId">The <c>MerchantCenter</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="MerchantCenterLinkName"/> constructed from the provided ids.</returns> public static MerchantCenterLinkName FromCustomerMerchantCenter(string customerId, string merchantCenterId) => new MerchantCenterLinkName(ResourceNameType.CustomerMerchantCenter, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), merchantCenterId: gax::GaxPreconditions.CheckNotNullOrEmpty(merchantCenterId, nameof(merchantCenterId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="MerchantCenterLinkName"/> with pattern /// <c>customers/{customer_id}/merchantCenterLinks/{merchant_center_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="merchantCenterId">The <c>MerchantCenter</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="MerchantCenterLinkName"/> with pattern /// <c>customers/{customer_id}/merchantCenterLinks/{merchant_center_id}</c>. /// </returns> public static string Format(string customerId, string merchantCenterId) => FormatCustomerMerchantCenter(customerId, merchantCenterId); /// <summary> /// Formats the IDs into the string representation of this <see cref="MerchantCenterLinkName"/> with pattern /// <c>customers/{customer_id}/merchantCenterLinks/{merchant_center_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="merchantCenterId">The <c>MerchantCenter</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="MerchantCenterLinkName"/> with pattern /// <c>customers/{customer_id}/merchantCenterLinks/{merchant_center_id}</c>. /// </returns> public static string FormatCustomerMerchantCenter(string customerId, string merchantCenterId) => s_customerMerchantCenter.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(merchantCenterId, nameof(merchantCenterId))); /// <summary> /// Parses the given resource name string into a new <see cref="MerchantCenterLinkName"/> 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}/merchantCenterLinks/{merchant_center_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="merchantCenterLinkName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="MerchantCenterLinkName"/> if successful.</returns> public static MerchantCenterLinkName Parse(string merchantCenterLinkName) => Parse(merchantCenterLinkName, false); /// <summary> /// Parses the given resource name string into a new <see cref="MerchantCenterLinkName"/> 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}/merchantCenterLinks/{merchant_center_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="merchantCenterLinkName">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="MerchantCenterLinkName"/> if successful.</returns> public static MerchantCenterLinkName Parse(string merchantCenterLinkName, bool allowUnparsed) => TryParse(merchantCenterLinkName, allowUnparsed, out MerchantCenterLinkName 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="MerchantCenterLinkName"/> 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}/merchantCenterLinks/{merchant_center_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="merchantCenterLinkName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="MerchantCenterLinkName"/>, 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 merchantCenterLinkName, out MerchantCenterLinkName result) => TryParse(merchantCenterLinkName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="MerchantCenterLinkName"/> 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}/merchantCenterLinks/{merchant_center_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="merchantCenterLinkName">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="MerchantCenterLinkName"/>, 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 merchantCenterLinkName, bool allowUnparsed, out MerchantCenterLinkName result) { gax::GaxPreconditions.CheckNotNull(merchantCenterLinkName, nameof(merchantCenterLinkName)); gax::TemplatedResourceName resourceName; if (s_customerMerchantCenter.TryParseName(merchantCenterLinkName, out resourceName)) { result = FromCustomerMerchantCenter(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(merchantCenterLinkName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private MerchantCenterLinkName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string merchantCenterId = null) { Type = type; UnparsedResource = unparsedResourceName; CustomerId = customerId; MerchantCenterId = merchantCenterId; } /// <summary> /// Constructs a new instance of a <see cref="MerchantCenterLinkName"/> class from the component parts of /// pattern <c>customers/{customer_id}/merchantCenterLinks/{merchant_center_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="merchantCenterId">The <c>MerchantCenter</c> ID. Must not be <c>null</c> or empty.</param> public MerchantCenterLinkName(string customerId, string merchantCenterId) : this(ResourceNameType.CustomerMerchantCenter, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), merchantCenterId: gax::GaxPreconditions.CheckNotNullOrEmpty(merchantCenterId, nameof(merchantCenterId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>MerchantCenter</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string MerchantCenterId { 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.CustomerMerchantCenter: return s_customerMerchantCenter.Expand(CustomerId, MerchantCenterId); 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 MerchantCenterLinkName); /// <inheritdoc/> public bool Equals(MerchantCenterLinkName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(MerchantCenterLinkName a, MerchantCenterLinkName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(MerchantCenterLinkName a, MerchantCenterLinkName b) => !(a == b); } public partial class MerchantCenterLink { /// <summary> /// <see cref="MerchantCenterLinkName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal MerchantCenterLinkName ResourceNameAsMerchantCenterLinkName { get => string.IsNullOrEmpty(ResourceName) ? null : MerchantCenterLinkName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } } }
namespace EIDSS.RAM.Layout { partial class LayoutDetail { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(LayoutDetail)); this.grcLayout = new DevExpress.XtraEditors.GroupControl(); this.cmdCopy = new DevExpress.XtraEditors.SimpleButton(); this.cmdNew = new DevExpress.XtraEditors.SimpleButton(); this.cmdSave = new DevExpress.XtraEditors.SimpleButton(); this.cmdDelete = new DevExpress.XtraEditors.SimpleButton(); this.cmdCancelChanges = new DevExpress.XtraEditors.SimpleButton(); this.tabControl = new DevExpress.XtraTab.XtraTabControl(); this.tabPageGrid = new DevExpress.XtraTab.XtraTabPage(); this.pivotForm = new EIDSS.RAM.Layout.PivotForm(); this.tabPageReport = new DevExpress.XtraTab.XtraTabPage(); this.grcReport = new DevExpress.XtraEditors.GroupControl(); this.pivotReportForm = new EIDSS.RAM.Layout.PivotReportForm(); this.tabPageChart = new DevExpress.XtraTab.XtraTabPage(); this.chartForm = new EIDSS.RAM.Layout.ChartForm(); this.tabPageMap = new DevExpress.XtraTab.XtraTabPage(); this.mapForm = new EIDSS.RAM.Layout.MapForm(); this.timerUpdateChart = new System.Windows.Forms.Timer(this.components); ((System.ComponentModel.ISupportInitialize)(this.grcLayout)).BeginInit(); this.grcLayout.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.tabControl)).BeginInit(); this.tabControl.SuspendLayout(); this.tabPageGrid.SuspendLayout(); this.tabPageReport.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.grcReport)).BeginInit(); this.grcReport.SuspendLayout(); this.tabPageChart.SuspendLayout(); this.tabPageMap.SuspendLayout(); this.SuspendLayout(); // // grcLayout // this.grcLayout.Appearance.Options.UseFont = true; this.grcLayout.AppearanceCaption.Options.UseFont = true; this.grcLayout.Controls.Add(this.cmdCopy); this.grcLayout.Controls.Add(this.cmdNew); this.grcLayout.Controls.Add(this.cmdSave); this.grcLayout.Controls.Add(this.cmdDelete); this.grcLayout.Controls.Add(this.cmdCancelChanges); this.grcLayout.Controls.Add(this.tabControl); resources.ApplyResources(this.grcLayout, "grcLayout"); this.grcLayout.MinimumSize = new System.Drawing.Size(500, 300); this.grcLayout.Name = "grcLayout"; this.grcLayout.ShowCaption = false; // // cmdCopy // resources.ApplyResources(this.cmdCopy, "cmdCopy"); this.cmdCopy.Image = global::EIDSS.RAM.Properties.Resources.query_copy; this.cmdCopy.Name = "cmdCopy"; this.cmdCopy.Click += new System.EventHandler(this.cmdCopy_Click); // // cmdNew // resources.ApplyResources(this.cmdNew, "cmdNew"); this.cmdNew.Image = global::EIDSS.RAM.Properties.Resources.layout_new; this.cmdNew.Name = "cmdNew"; this.cmdNew.Click += new System.EventHandler(this.cmdNew_Click); // // cmdSave // resources.ApplyResources(this.cmdSave, "cmdSave"); this.cmdSave.Image = global::EIDSS.RAM.Properties.Resources.layout_save_1; this.cmdSave.Name = "cmdSave"; this.cmdSave.Click += new System.EventHandler(this.cmdSave_Click); // // cmdDelete // resources.ApplyResources(this.cmdDelete, "cmdDelete"); this.cmdDelete.Image = global::EIDSS.RAM.Properties.Resources.layout_deleted; this.cmdDelete.Name = "cmdDelete"; this.cmdDelete.Click += new System.EventHandler(this.cmdDelete_Click); // // cmdCancelChanges // resources.ApplyResources(this.cmdCancelChanges, "cmdCancelChanges"); this.cmdCancelChanges.Image = global::EIDSS.RAM.Properties.Resources.layout_undo3; this.cmdCancelChanges.Name = "cmdCancelChanges"; this.cmdCancelChanges.Click += new System.EventHandler(this.cmdCancel_Click); // // tabControl // resources.ApplyResources(this.tabControl, "tabControl"); this.tabControl.Appearance.Options.UseFont = true; this.tabControl.AppearancePage.Header.Options.UseFont = true; this.tabControl.AppearancePage.HeaderActive.Options.UseFont = true; this.tabControl.AppearancePage.HeaderDisabled.Options.UseFont = true; this.tabControl.AppearancePage.HeaderHotTracked.Options.UseFont = true; this.tabControl.AppearancePage.PageClient.Options.UseFont = true; this.tabControl.Name = "tabControl"; this.tabControl.SelectedTabPage = this.tabPageGrid; this.tabControl.TabPages.AddRange(new DevExpress.XtraTab.XtraTabPage[] { this.tabPageGrid, this.tabPageReport, this.tabPageChart, this.tabPageMap}); this.tabControl.SelectedPageChanging += new DevExpress.XtraTab.TabPageChangingEventHandler(this.tabControl_SelectedPageChanging); // // tabPageGrid // this.tabPageGrid.Appearance.Header.Options.UseFont = true; this.tabPageGrid.Appearance.HeaderActive.Options.UseFont = true; this.tabPageGrid.Appearance.HeaderDisabled.Options.UseFont = true; this.tabPageGrid.Appearance.HeaderHotTracked.Options.UseFont = true; this.tabPageGrid.Appearance.PageClient.Options.UseFont = true; this.tabPageGrid.Controls.Add(this.pivotForm); resources.ApplyResources(this.tabPageGrid, "tabPageGrid"); this.tabPageGrid.Name = "tabPageGrid"; // // pivotForm // resources.ApplyResources(this.pivotForm, "pivotForm"); this.pivotForm.DefaultFormState = System.Windows.Forms.FormWindowState.Normal; this.pivotForm.FormID = null; this.pivotForm.HelpTopicID = null; this.pivotForm.IsStatusReadOnly = false; this.pivotForm.KeyFieldName = null; this.pivotForm.MinimumSize = new System.Drawing.Size(500, 300); this.pivotForm.MultiSelect = false; this.pivotForm.Name = "pivotForm"; this.pivotForm.ObjectName = null; this.pivotForm.Status = bv.common.win.FormStatus.Draft; this.pivotForm.TableName = null; // // tabPageReport // this.tabPageReport.Appearance.Header.Options.UseFont = true; this.tabPageReport.Appearance.HeaderActive.Options.UseFont = true; this.tabPageReport.Appearance.HeaderDisabled.Options.UseFont = true; this.tabPageReport.Appearance.HeaderHotTracked.Options.UseFont = true; this.tabPageReport.Appearance.PageClient.Options.UseFont = true; this.tabPageReport.Controls.Add(this.grcReport); this.tabPageReport.Name = "tabPageReport"; resources.ApplyResources(this.tabPageReport, "tabPageReport"); // // grcReport // this.grcReport.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder; this.grcReport.Controls.Add(this.pivotReportForm); resources.ApplyResources(this.grcReport, "grcReport"); this.grcReport.Name = "grcReport"; // // pivotReportForm // resources.ApplyResources(this.pivotReportForm, "pivotReportForm"); this.pivotReportForm.DefaultFormState = System.Windows.Forms.FormWindowState.Normal; this.pivotReportForm.FilterText = ""; this.pivotReportForm.FormID = null; this.pivotReportForm.HelpTopicID = null; this.pivotReportForm.IsStatusReadOnly = false; this.pivotReportForm.KeyFieldName = null; this.pivotReportForm.MultiSelect = false; this.pivotReportForm.Name = "pivotReportForm"; this.pivotReportForm.ObjectName = null; this.pivotReportForm.PivotName = ""; this.pivotReportForm.Status = bv.common.win.FormStatus.Draft; this.pivotReportForm.TableName = null; this.pivotReportForm.UseParentDataset = true; // // tabPageChart // this.tabPageChart.Appearance.Header.Options.UseFont = true; this.tabPageChart.Appearance.HeaderActive.Options.UseFont = true; this.tabPageChart.Appearance.HeaderDisabled.Options.UseFont = true; this.tabPageChart.Appearance.HeaderHotTracked.Options.UseFont = true; this.tabPageChart.Appearance.PageClient.Options.UseFont = true; this.tabPageChart.Controls.Add(this.chartForm); this.tabPageChart.Name = "tabPageChart"; resources.ApplyResources(this.tabPageChart, "tabPageChart"); // // chartForm // resources.ApplyResources(this.chartForm, "chartForm"); this.chartForm.ChartName = ""; this.chartForm.DataSource = null; this.chartForm.DefaultFormState = System.Windows.Forms.FormWindowState.Normal; this.chartForm.FilterText = ""; this.chartForm.FormID = null; this.chartForm.HelpTopicID = null; this.chartForm.IsStatusReadOnly = false; this.chartForm.KeyFieldName = null; this.chartForm.MinimumSize = new System.Drawing.Size(500, 300); this.chartForm.MultiSelect = false; this.chartForm.Name = "chartForm"; this.chartForm.ObjectName = null; this.chartForm.Status = bv.common.win.FormStatus.Draft; this.chartForm.TableName = null; this.chartForm.UseParentDataset = true; // // tabPageMap // this.tabPageMap.Appearance.Header.Options.UseFont = true; this.tabPageMap.Appearance.HeaderActive.Options.UseFont = true; this.tabPageMap.Appearance.HeaderDisabled.Options.UseFont = true; this.tabPageMap.Appearance.HeaderHotTracked.Options.UseFont = true; this.tabPageMap.Appearance.PageClient.Options.UseFont = true; this.tabPageMap.Controls.Add(this.mapForm); this.tabPageMap.Name = "tabPageMap"; this.tabPageMap.PageEnabled = false; resources.ApplyResources(this.tabPageMap, "tabPageMap"); // // mapForm // resources.ApplyResources(this.mapForm, "mapForm"); this.mapForm.DefaultFormState = System.Windows.Forms.FormWindowState.Normal; this.mapForm.FilterText = ""; this.mapForm.FormID = null; this.mapForm.HelpTopicID = null; this.mapForm.IsStatusReadOnly = false; this.mapForm.KeyFieldName = null; this.mapForm.MapName = ""; this.mapForm.MinimumSize = new System.Drawing.Size(500, 300); this.mapForm.MultiSelect = false; this.mapForm.Name = "mapForm"; this.mapForm.ObjectName = null; this.mapForm.Status = bv.common.win.FormStatus.Draft; this.mapForm.TableName = null; this.mapForm.UseParentDataset = true; // // timerUpdateChart // this.timerUpdateChart.Tick += new System.EventHandler(this.timerUpdateChart_Tick); // // LayoutDetail // this.Controls.Add(this.grcLayout); this.HelpTopicID = "Predefined_Layouts_List"; this.Name = "LayoutDetail"; resources.ApplyResources(this, "$this"); ((System.ComponentModel.ISupportInitialize)(this.grcLayout)).EndInit(); this.grcLayout.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.tabControl)).EndInit(); this.tabControl.ResumeLayout(false); this.tabPageGrid.ResumeLayout(false); this.tabPageReport.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.grcReport)).EndInit(); this.grcReport.ResumeLayout(false); this.tabPageChart.ResumeLayout(false); this.tabPageMap.ResumeLayout(false); this.ResumeLayout(false); } #endregion private DevExpress.XtraEditors.GroupControl grcLayout; private DevExpress.XtraTab.XtraTabControl tabControl; private DevExpress.XtraTab.XtraTabPage tabPageGrid; private PivotForm pivotForm; private DevExpress.XtraTab.XtraTabPage tabPageReport; private PivotReportForm pivotReportForm; private DevExpress.XtraTab.XtraTabPage tabPageChart; private ChartForm chartForm; private DevExpress.XtraTab.XtraTabPage tabPageMap; private MapForm mapForm; protected DevExpress.XtraEditors.SimpleButton cmdNew; protected DevExpress.XtraEditors.SimpleButton cmdSave; protected DevExpress.XtraEditors.SimpleButton cmdDelete; protected internal DevExpress.XtraEditors.SimpleButton cmdCancelChanges; protected internal DevExpress.XtraEditors.SimpleButton cmdCopy; private System.Windows.Forms.Timer timerUpdateChart; private DevExpress.XtraEditors.GroupControl grcReport; } }
// 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.Xml; #if !SILVERLIGHT using System.Net; #endif using System.Text; using System.Reflection; using System.Diagnostics; using System.Collections.Generic; using System.Runtime.Versioning; namespace System.Xml.Resolvers { // // XmlPreloadedResolver is an XmlResolver that which can be pre-loaded with data. // By default it contains well-known DTDs for XHTML 1.0 and RSS 0.91. // Custom mappings of URIs to data can be added with the Add method. // public partial class XmlPreloadedResolver : XmlResolver { // // PreloadedData class // private abstract class PreloadedData { // Returns preloaded data as Stream; Stream must always be supported internal abstract Stream AsStream(); // Returns preloaded data as TextReader, or throws when not supported internal virtual TextReader AsTextReader() { throw new XmlException(SR.Xml_UnsupportedClass); } // Returns true for types that are supported for this preloaded data; Stream must always be supported internal virtual bool SupportsType(Type type) { if (type == null || type == typeof(Stream)) { return true; } return false; } }; // // XmlKnownDtdData class // private class XmlKnownDtdData : PreloadedData { internal string publicId; internal string systemId; private string _resourceName; internal XmlKnownDtdData(string publicId, string systemId, string resourceName) { this.publicId = publicId; this.systemId = systemId; _resourceName = resourceName; } internal override Stream AsStream() { Assembly asm = GetType().Assembly; return asm.GetManifestResourceStream(_resourceName); } } private class ByteArrayChunk : PreloadedData { private byte[] _array; private int _offset; private int _length; internal ByteArrayChunk(byte[] array) : this(array, 0, array.Length) { } internal ByteArrayChunk(byte[] array, int offset, int length) { _array = array; _offset = offset; _length = length; } internal override Stream AsStream() { return new MemoryStream(_array, _offset, _length); } } private class StringData : PreloadedData { private string _str; internal StringData(string str) { _str = str; } internal override Stream AsStream() { return new MemoryStream(Encoding.Unicode.GetBytes(_str)); } internal override TextReader AsTextReader() { return new StringReader(_str); } internal override bool SupportsType(Type type) { if (type == typeof(TextReader)) { return true; } return base.SupportsType(type); } } // // Fields // private XmlResolver _fallbackResolver; private Dictionary<Uri, PreloadedData> _mappings; private XmlKnownDtds _preloadedDtds; // // Static/constant fiels // private static XmlKnownDtdData[] s_xhtml10_Dtd = new XmlKnownDtdData[] { new XmlKnownDtdData( "-//W3C//DTD XHTML 1.0 Strict//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd", "xhtml1-strict.dtd" ), new XmlKnownDtdData( "-//W3C//DTD XHTML 1.0 Transitional//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd", "xhtml1-transitional.dtd" ), new XmlKnownDtdData( "-//W3C//DTD XHTML 1.0 Frameset//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd", "xhtml1-frameset.dtd" ), new XmlKnownDtdData( "-//W3C//ENTITIES Latin 1 for XHTML//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml-lat1.ent", "xhtml-lat1.ent" ), new XmlKnownDtdData( "-//W3C//ENTITIES Symbols for XHTML//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml-symbol.ent", "xhtml-symbol.ent" ), new XmlKnownDtdData( "-//W3C//ENTITIES Special for XHTML//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml-special.ent", "xhtml-special.ent" ), }; private static XmlKnownDtdData[] s_rss091_Dtd = new XmlKnownDtdData[] { new XmlKnownDtdData( "-//Netscape Communications//DTD RSS 0.91//EN", "http://my.netscape.com/publish/formats/rss-0.91.dtd", "rss-0.91.dtd" ), }; // // Constructors // public XmlPreloadedResolver() : this(null) { } public XmlPreloadedResolver(XmlKnownDtds preloadedDtds) : this(null, preloadedDtds, null) { } public XmlPreloadedResolver(XmlResolver fallbackResolver) : this(fallbackResolver, XmlKnownDtds.All, null) { } public XmlPreloadedResolver(XmlResolver fallbackResolver, XmlKnownDtds preloadedDtds) : this(fallbackResolver, preloadedDtds, null) { } public XmlPreloadedResolver(XmlResolver fallbackResolver, XmlKnownDtds preloadedDtds, IEqualityComparer<Uri> uriComparer) { _fallbackResolver = fallbackResolver; _mappings = new Dictionary<Uri, PreloadedData>(16, uriComparer); _preloadedDtds = preloadedDtds; // load known DTDs if (preloadedDtds != 0) { if ((preloadedDtds & XmlKnownDtds.Xhtml10) != 0) { AddKnownDtd(s_xhtml10_Dtd); } if ((preloadedDtds & XmlKnownDtds.Rss091) != 0) { AddKnownDtd(s_rss091_Dtd); } } } public override Uri ResolveUri(Uri baseUri, string relativeUri) { // 1) special-case well-known public IDs // 2) To make FxCop happy we need to use StartsWith() overload that takes StringComparison -> // .StartsWith(string) is equal to .StartsWith(string, StringComparison.CurrentCulture); if (relativeUri != null && relativeUri.StartsWith("-//", StringComparison.CurrentCulture)) { // 1) XHTML 1.0 public IDs // 2) To make FxCop happy we need to use StartsWith() overload that takes StringComparison -> // .StartsWith(string) is equal to .StartsWith(string, StringComparison.CurrentCulture); if ((_preloadedDtds & XmlKnownDtds.Xhtml10) != 0 && relativeUri.StartsWith("-//W3C//", StringComparison.CurrentCulture)) { for (int i = 0; i < s_xhtml10_Dtd.Length; i++) { if (relativeUri == s_xhtml10_Dtd[i].publicId) { return new Uri(relativeUri, UriKind.Relative); } } } // RSS 0.91 public IDs if ((_preloadedDtds & XmlKnownDtds.Rss091) != 0) { Debug.Assert(s_rss091_Dtd.Length == 1); if (relativeUri == s_rss091_Dtd[0].publicId) { return new Uri(relativeUri, UriKind.Relative); } } } return base.ResolveUri(baseUri, relativeUri); } public override Object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn) { if (absoluteUri == null) { throw new ArgumentNullException(nameof(absoluteUri)); } PreloadedData data; if (!_mappings.TryGetValue(absoluteUri, out data)) { if (_fallbackResolver != null) { return _fallbackResolver.GetEntity(absoluteUri, role, ofObjectToReturn); } throw new XmlException(SR.Format(SR.Xml_CannotResolveUrl, absoluteUri.ToString())); } if (ofObjectToReturn == null || ofObjectToReturn == typeof(Stream) || ofObjectToReturn == typeof(Object)) { return data.AsStream(); } else if (ofObjectToReturn == typeof(TextReader)) { return data.AsTextReader(); } else { throw new XmlException(SR.Xml_UnsupportedClass); } } #if !SILVERLIGHT public override ICredentials Credentials { set { if (_fallbackResolver != null) { _fallbackResolver.Credentials = value; } } } #endif public override bool SupportsType(Uri absoluteUri, Type type) { if (absoluteUri == null) { throw new ArgumentNullException(nameof(absoluteUri)); } PreloadedData data; if (!_mappings.TryGetValue(absoluteUri, out data)) { if (_fallbackResolver != null) { return _fallbackResolver.SupportsType(absoluteUri, type); } return base.SupportsType(absoluteUri, type); } return data.SupportsType(type); } public void Add(Uri uri, byte[] value) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } Add(uri, new ByteArrayChunk(value, 0, value.Length)); } public void Add(Uri uri, byte[] value, int offset, int count) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (value.Length - offset < count) { throw new ArgumentOutOfRangeException(nameof(count)); } Add(uri, new ByteArrayChunk(value, offset, count)); } public void Add(Uri uri, Stream value) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } if (value.CanSeek) { // stream of known length -> allocate the byte array and read all data into it int size = checked((int)value.Length); byte[] bytes = new byte[size]; value.Read(bytes, 0, size); Add(uri, new ByteArrayChunk(bytes)); } else { // stream of unknown length -> read into memory stream and then get internal the byte array MemoryStream ms = new MemoryStream(); byte[] buffer = new byte[4096]; int read; while ((read = value.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } int size = checked((int)ms.Position); byte[] bytes = new byte[size]; Array.Copy(ms.ToArray(), bytes, size); Add(uri, new ByteArrayChunk(bytes)); } } public void Add(Uri uri, string value) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } Add(uri, new StringData(value)); } public IEnumerable<Uri> PreloadedUris { get { // read-only collection of keys return _mappings.Keys; } } public void Remove(Uri uri) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } _mappings.Remove(uri); } // // Private implementation methods // private void Add(Uri uri, PreloadedData data) { Debug.Assert(uri != null); // override if exists if (_mappings.ContainsKey(uri)) { _mappings[uri] = data; } else { _mappings.Add(uri, data); } } private void AddKnownDtd(XmlKnownDtdData[] dtdSet) { for (int i = 0; i < dtdSet.Length; i++) { XmlKnownDtdData dtdInfo = dtdSet[i]; _mappings.Add(new Uri(dtdInfo.publicId, UriKind.RelativeOrAbsolute), dtdInfo); _mappings.Add(new Uri(dtdInfo.systemId, UriKind.RelativeOrAbsolute), dtdInfo); } } } }
// 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; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.InteropServices; using System.Text; using SysTx = System.Transactions; namespace System.Data.Odbc { public sealed partial class OdbcConnection : DbConnection, ICloneable { private int _connectionTimeout = ADP.DefaultConnectionTimeout; private OdbcInfoMessageEventHandler _infoMessageEventHandler; private WeakReference _weakTransaction; private OdbcConnectionHandle _connectionHandle; private ConnectionState _extraState = default(ConnectionState); // extras, like Executing and Fetching, that we add to the State. public OdbcConnection(string connectionString) : this() { ConnectionString = connectionString; } private OdbcConnection(OdbcConnection connection) : this() { // Clone CopyFrom(connection); _connectionTimeout = connection._connectionTimeout; } internal OdbcConnectionHandle ConnectionHandle { get { return _connectionHandle; } set { Debug.Assert(null == _connectionHandle, "reopening a connection?"); _connectionHandle = value; } } public override string ConnectionString { get { return ConnectionString_Get(); } set { ConnectionString_Set(value); } } [ DefaultValue(ADP.DefaultConnectionTimeout), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] public new int ConnectionTimeout { get { return _connectionTimeout; } set { if (value < 0) throw ODBC.NegativeArgument(); if (IsOpen) throw ODBC.CantSetPropertyOnOpenConnection(); _connectionTimeout = value; } } [ DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] public override string Database { get { if (IsOpen && !ProviderInfo.NoCurrentCatalog) { //Note: CURRENT_CATALOG may not be supported by the current driver. In which //case we ignore any error (without throwing), and just return string.empty. //As we really don't want people to have to have try/catch around simple properties return GetConnectAttrString(ODBC32.SQL_ATTR.CURRENT_CATALOG); } //Database is not available before open, and its not worth parsing the //connection string over. return string.Empty; } } [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] public override string DataSource { get { if (IsOpen) { // note: This will return an empty string if the driver keyword was used to connect // see ODBC3.0 Programmers Reference, SQLGetInfo // return GetInfoStringUnhandled(ODBC32.SQL_INFO.SERVER_NAME, true); } return string.Empty; } } [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] public override string ServerVersion { get { return InnerConnection.ServerVersion; } } [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] public override ConnectionState State { get { return InnerConnection.State; } } internal OdbcConnectionPoolGroupProviderInfo ProviderInfo { get { Debug.Assert(null != this.PoolGroup, "PoolGroup must never be null when accessing ProviderInfo"); return (OdbcConnectionPoolGroupProviderInfo)this.PoolGroup.ProviderInfo; } } internal ConnectionState InternalState { get { return (this.State | _extraState); } } internal bool IsOpen { get { return (InnerConnection is OdbcConnectionOpen); } } internal OdbcTransaction LocalTransaction { get { OdbcTransaction result = null; if (null != _weakTransaction) { result = ((OdbcTransaction)_weakTransaction.Target); } return result; } set { _weakTransaction = null; if (null != value) { _weakTransaction = new WeakReference((OdbcTransaction)value); } } } [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] public string Driver { get { if (IsOpen) { if (ProviderInfo.DriverName == null) { ProviderInfo.DriverName = GetInfoStringUnhandled(ODBC32.SQL_INFO.DRIVER_NAME); } return ProviderInfo.DriverName; } return ADP.StrEmpty; } } internal bool IsV3Driver { get { if (ProviderInfo.DriverVersion == null) { ProviderInfo.DriverVersion = GetInfoStringUnhandled(ODBC32.SQL_INFO.DRIVER_ODBC_VER); // protected against null and index out of range. Number cannot be bigger than 99 if (ProviderInfo.DriverVersion != null && ProviderInfo.DriverVersion.Length >= 2) { try { // mdac 89269: driver may return malformatted string ProviderInfo.IsV3Driver = (int.Parse(ProviderInfo.DriverVersion.Substring(0, 2), CultureInfo.InvariantCulture) >= 3); } catch (System.FormatException e) { ProviderInfo.IsV3Driver = false; ADP.TraceExceptionWithoutRethrow(e); } } else { ProviderInfo.DriverVersion = ""; } } return ProviderInfo.IsV3Driver; } } public event OdbcInfoMessageEventHandler InfoMessage { add { _infoMessageEventHandler += value; } remove { _infoMessageEventHandler -= value; } } internal char EscapeChar(string method) { CheckState(method); if (!ProviderInfo.HasEscapeChar) { string escapeCharString; escapeCharString = GetInfoStringUnhandled(ODBC32.SQL_INFO.SEARCH_PATTERN_ESCAPE); Debug.Assert((escapeCharString.Length <= 1), "Can't handle multichar quotes"); ProviderInfo.EscapeChar = (escapeCharString.Length == 1) ? escapeCharString[0] : QuoteChar(method)[0]; } return ProviderInfo.EscapeChar; } internal string QuoteChar(string method) { CheckState(method); if (!ProviderInfo.HasQuoteChar) { string quoteCharString; quoteCharString = GetInfoStringUnhandled(ODBC32.SQL_INFO.IDENTIFIER_QUOTE_CHAR); Debug.Assert((quoteCharString.Length <= 1), "Can't handle multichar quotes"); ProviderInfo.QuoteChar = (1 == quoteCharString.Length) ? quoteCharString : "\0"; } return ProviderInfo.QuoteChar; } public new OdbcTransaction BeginTransaction() { return BeginTransaction(IsolationLevel.Unspecified); } public new OdbcTransaction BeginTransaction(IsolationLevel isolevel) { return (OdbcTransaction)InnerConnection.BeginTransaction(isolevel); } private void RollbackDeadTransaction() { WeakReference weak = _weakTransaction; if ((null != weak) && !weak.IsAlive) { _weakTransaction = null; ConnectionHandle.CompleteTransaction(ODBC32.SQL_ROLLBACK); } } public override void ChangeDatabase(string value) { InnerConnection.ChangeDatabase(value); } internal void CheckState(string method) { ConnectionState state = InternalState; if (ConnectionState.Open != state) { throw ADP.OpenConnectionRequired(method, state); // MDAC 68323 } } object ICloneable.Clone() { OdbcConnection clone = new OdbcConnection(this); return clone; } internal bool ConnectionIsAlive(Exception innerException) { if (IsOpen) { if (!ProviderInfo.NoConnectionDead) { int isDead = GetConnectAttr(ODBC32.SQL_ATTR.CONNECTION_DEAD, ODBC32.HANDLER.IGNORE); if (ODBC32.SQL_CD_TRUE == isDead) { Close(); throw ADP.ConnectionIsDisabled(innerException); } } // else connection is still alive or attribute not supported return true; } return false; } public new OdbcCommand CreateCommand() { return new OdbcCommand(string.Empty, this); } internal OdbcStatementHandle CreateStatementHandle() { return new OdbcStatementHandle(ConnectionHandle); } public override void Close() { InnerConnection.CloseConnection(this, ConnectionFactory); OdbcConnectionHandle connectionHandle = _connectionHandle; if (null != connectionHandle) { _connectionHandle = null; // If there is a pending transaction, automatically rollback. WeakReference weak = _weakTransaction; if (null != weak) { _weakTransaction = null; IDisposable transaction = weak.Target as OdbcTransaction; if ((null != transaction) && weak.IsAlive) { transaction.Dispose(); } // else transaction will be rolled back when handle is disposed } connectionHandle.Dispose(); } } private void DisposeMe(bool disposing) { // MDAC 65459 } internal string GetConnectAttrString(ODBC32.SQL_ATTR attribute) { string value = ""; int cbActual = 0; byte[] buffer = new byte[100]; OdbcConnectionHandle connectionHandle = ConnectionHandle; if (null != connectionHandle) { ODBC32.RetCode retcode = connectionHandle.GetConnectionAttribute(attribute, buffer, out cbActual); if (buffer.Length + 2 <= cbActual) { // 2 bytes for unicode null-termination character // retry with cbActual because original buffer was too small buffer = new byte[cbActual + 2]; retcode = connectionHandle.GetConnectionAttribute(attribute, buffer, out cbActual); } if ((ODBC32.RetCode.SUCCESS == retcode) || (ODBC32.RetCode.SUCCESS_WITH_INFO == retcode)) { value = (BitConverter.IsLittleEndian ? Encoding.Unicode : Encoding.BigEndianUnicode).GetString(buffer, 0, Math.Min(cbActual, buffer.Length)); } else if (retcode == ODBC32.RetCode.ERROR) { string sqlstate = GetDiagSqlState(); if (("HYC00" == sqlstate) || ("HY092" == sqlstate) || ("IM001" == sqlstate)) { FlagUnsupportedConnectAttr(attribute); } // not throwing errors if not supported or other failure } } return value; } internal int GetConnectAttr(ODBC32.SQL_ATTR attribute, ODBC32.HANDLER handler) { int retval = -1; int cbActual = 0; byte[] buffer = new byte[4]; OdbcConnectionHandle connectionHandle = ConnectionHandle; if (null != connectionHandle) { ODBC32.RetCode retcode = connectionHandle.GetConnectionAttribute(attribute, buffer, out cbActual); if ((ODBC32.RetCode.SUCCESS == retcode) || (ODBC32.RetCode.SUCCESS_WITH_INFO == retcode)) { retval = BitConverter.ToInt32(buffer, 0); } else { if (retcode == ODBC32.RetCode.ERROR) { string sqlstate = GetDiagSqlState(); if (("HYC00" == sqlstate) || ("HY092" == sqlstate) || ("IM001" == sqlstate)) { FlagUnsupportedConnectAttr(attribute); } } if (handler == ODBC32.HANDLER.THROW) { this.HandleError(connectionHandle, retcode); } } } return retval; } private string GetDiagSqlState() { OdbcConnectionHandle connectionHandle = ConnectionHandle; string sqlstate; connectionHandle.GetDiagnosticField(out sqlstate); return sqlstate; } internal ODBC32.RetCode GetInfoInt16Unhandled(ODBC32.SQL_INFO info, out short resultValue) { byte[] buffer = new byte[2]; ODBC32.RetCode retcode = ConnectionHandle.GetInfo1(info, buffer); resultValue = BitConverter.ToInt16(buffer, 0); return retcode; } internal ODBC32.RetCode GetInfoInt32Unhandled(ODBC32.SQL_INFO info, out int resultValue) { byte[] buffer = new byte[4]; ODBC32.RetCode retcode = ConnectionHandle.GetInfo1(info, buffer); resultValue = BitConverter.ToInt32(buffer, 0); return retcode; } private int GetInfoInt32Unhandled(ODBC32.SQL_INFO infotype) { byte[] buffer = new byte[4]; ConnectionHandle.GetInfo1(infotype, buffer); return BitConverter.ToInt32(buffer, 0); } internal string GetInfoStringUnhandled(ODBC32.SQL_INFO info) { return GetInfoStringUnhandled(info, false); } private string GetInfoStringUnhandled(ODBC32.SQL_INFO info, bool handleError) { //SQLGetInfo string value = null; short cbActual = 0; byte[] buffer = new byte[100]; OdbcConnectionHandle connectionHandle = ConnectionHandle; if (null != connectionHandle) { ODBC32.RetCode retcode = connectionHandle.GetInfo2(info, buffer, out cbActual); if (buffer.Length < cbActual - 2) { // 2 bytes for unicode null-termination character // retry with cbActual because original buffer was too small buffer = new byte[cbActual + 2]; retcode = connectionHandle.GetInfo2(info, buffer, out cbActual); } if (retcode == ODBC32.RetCode.SUCCESS || retcode == ODBC32.RetCode.SUCCESS_WITH_INFO) { value = (BitConverter.IsLittleEndian ? Encoding.Unicode : Encoding.BigEndianUnicode).GetString(buffer, 0, Math.Min(cbActual, buffer.Length)); } else if (handleError) { this.HandleError(ConnectionHandle, retcode); } } else if (handleError) { value = ""; } return value; } // non-throwing HandleError internal Exception HandleErrorNoThrow(OdbcHandle hrHandle, ODBC32.RetCode retcode) { Debug.Assert(retcode != ODBC32.RetCode.INVALID_HANDLE, "retcode must never be ODBC32.RetCode.INVALID_HANDLE"); switch (retcode) { case ODBC32.RetCode.SUCCESS: break; case ODBC32.RetCode.SUCCESS_WITH_INFO: { //Optimize to only create the event objects and obtain error info if //the user is really interested in retriveing the events... if (_infoMessageEventHandler != null) { OdbcErrorCollection errors = ODBC32.GetDiagErrors(null, hrHandle, retcode); errors.SetSource(this.Driver); OnInfoMessage(new OdbcInfoMessageEventArgs(errors)); } break; } default: OdbcException e = OdbcException.CreateException(ODBC32.GetDiagErrors(null, hrHandle, retcode), retcode); if (e != null) { e.Errors.SetSource(this.Driver); } ConnectionIsAlive(e); // this will close and throw if the connection is dead return (Exception)e; } return null; } internal void HandleError(OdbcHandle hrHandle, ODBC32.RetCode retcode) { Exception e = HandleErrorNoThrow(hrHandle, retcode); switch (retcode) { case ODBC32.RetCode.SUCCESS: case ODBC32.RetCode.SUCCESS_WITH_INFO: Debug.Assert(null == e, "success exception"); break; default: Debug.Assert(null != e, "failure without exception"); throw e; } } public override void Open() { try { InnerConnection.OpenConnection(this, ConnectionFactory); } catch (DllNotFoundException e) when (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { throw new DllNotFoundException(SR.Odbc_UnixOdbcNotFound + Environment.NewLine + e.Message); } // SQLBUDT #276132 - need to manually enlist in some cases, because // native ODBC doesn't know about SysTx transactions. if (ADP.NeedManualEnlistment()) { EnlistTransaction(SysTx.Transaction.Current); } } private void OnInfoMessage(OdbcInfoMessageEventArgs args) { if (null != _infoMessageEventHandler) { try { _infoMessageEventHandler(this, args); } catch (Exception e) { // if (!ADP.IsCatchableOrSecurityExceptionType(e)) { throw; } ADP.TraceExceptionWithoutRethrow(e); } } } public static void ReleaseObjectPool() { OdbcEnvironment.ReleaseObjectPool(); } internal OdbcTransaction SetStateExecuting(string method, OdbcTransaction transaction) { // MDAC 69003 if (null != _weakTransaction) { // transaction may exist OdbcTransaction weak = (_weakTransaction.Target as OdbcTransaction); if (transaction != weak) { // transaction doesn't exist if (null == transaction) { // transaction exists throw ADP.TransactionRequired(method); } if (this != transaction.Connection) { // transaction can't have come from this connection throw ADP.TransactionConnectionMismatch(); } // if transaction is zombied, we don't know the original connection transaction = null; // MDAC 69264 } } else if (null != transaction) { // no transaction started if (null != transaction.Connection) { // transaction can't have come from this connection throw ADP.TransactionConnectionMismatch(); } // if transaction is zombied, we don't know the original connection transaction = null; // MDAC 69264 } ConnectionState state = InternalState; if (ConnectionState.Open != state) { NotifyWeakReference(OdbcReferenceCollection.Recover); // recover for a potentially finalized reader state = InternalState; if (ConnectionState.Open != state) { if (0 != (ConnectionState.Fetching & state)) { throw ADP.OpenReaderExists(); } throw ADP.OpenConnectionRequired(method, state); } } return transaction; } // This adds a type to the list of types that are supported by the driver // (don't need to know that for all the types) // internal void SetSupportedType(ODBC32.SQL_TYPE sqltype) { ODBC32.SQL_CVT sqlcvt; switch (sqltype) { case ODBC32.SQL_TYPE.NUMERIC: { sqlcvt = ODBC32.SQL_CVT.NUMERIC; break; } case ODBC32.SQL_TYPE.WCHAR: { sqlcvt = ODBC32.SQL_CVT.WCHAR; break; } case ODBC32.SQL_TYPE.WVARCHAR: { sqlcvt = ODBC32.SQL_CVT.WVARCHAR; break; } case ODBC32.SQL_TYPE.WLONGVARCHAR: { sqlcvt = ODBC32.SQL_CVT.WLONGVARCHAR; break; } default: // other types are irrelevant at this time return; } ProviderInfo.TestedSQLTypes |= (int)sqlcvt; ProviderInfo.SupportedSQLTypes |= (int)sqlcvt; } internal void FlagRestrictedSqlBindType(ODBC32.SQL_TYPE sqltype) { ODBC32.SQL_CVT sqlcvt; switch (sqltype) { case ODBC32.SQL_TYPE.NUMERIC: { sqlcvt = ODBC32.SQL_CVT.NUMERIC; break; } case ODBC32.SQL_TYPE.DECIMAL: { sqlcvt = ODBC32.SQL_CVT.DECIMAL; break; } default: // other types are irrelevant at this time return; } ProviderInfo.RestrictedSQLBindTypes |= (int)sqlcvt; } internal void FlagUnsupportedConnectAttr(ODBC32.SQL_ATTR Attribute) { switch (Attribute) { case ODBC32.SQL_ATTR.CURRENT_CATALOG: ProviderInfo.NoCurrentCatalog = true; break; case ODBC32.SQL_ATTR.CONNECTION_DEAD: ProviderInfo.NoConnectionDead = true; break; default: Debug.Fail("Can't flag unknown Attribute"); break; } } internal void FlagUnsupportedStmtAttr(ODBC32.SQL_ATTR Attribute) { switch (Attribute) { case ODBC32.SQL_ATTR.QUERY_TIMEOUT: ProviderInfo.NoQueryTimeout = true; break; case (ODBC32.SQL_ATTR)ODBC32.SQL_SOPT_SS.NOBROWSETABLE: ProviderInfo.NoSqlSoptSSNoBrowseTable = true; break; case (ODBC32.SQL_ATTR)ODBC32.SQL_SOPT_SS.HIDDEN_COLUMNS: ProviderInfo.NoSqlSoptSSHiddenColumns = true; break; default: Debug.Fail("Can't flag unknown Attribute"); break; } } internal void FlagUnsupportedColAttr(ODBC32.SQL_DESC v3FieldId, ODBC32.SQL_COLUMN v2FieldId) { if (IsV3Driver) { switch (v3FieldId) { case (ODBC32.SQL_DESC)ODBC32.SQL_CA_SS.COLUMN_KEY: // SSS_WARNINGS_OFF ProviderInfo.NoSqlCASSColumnKey = true; break; // SSS_WARNINGS_ON default: Debug.Fail("Can't flag unknown Attribute"); break; } } else { switch (v2FieldId) { default: Debug.Fail("Can't flag unknown Attribute"); break; } } } internal bool SQLGetFunctions(ODBC32.SQL_API odbcFunction) { //SQLGetFunctions ODBC32.RetCode retcode; short fExists; Debug.Assert((short)odbcFunction != 0, "SQL_API_ALL_FUNCTIONS is not supported"); OdbcConnectionHandle connectionHandle = ConnectionHandle; if (null != connectionHandle) { retcode = connectionHandle.GetFunctions(odbcFunction, out fExists); } else { Debug.Fail("GetFunctions called and ConnectionHandle is null (connection is disposed?)"); throw ODBC.ConnectionClosed(); } if (retcode != ODBC32.RetCode.SUCCESS) this.HandleError(connectionHandle, retcode); if (fExists == 0) { return false; } else { return true; } } internal bool TestTypeSupport(ODBC32.SQL_TYPE sqltype) { ODBC32.SQL_CONVERT sqlconvert; ODBC32.SQL_CVT sqlcvt; // we need to convert the sqltype to sqlconvert and sqlcvt first // switch (sqltype) { case ODBC32.SQL_TYPE.NUMERIC: { sqlconvert = ODBC32.SQL_CONVERT.NUMERIC; sqlcvt = ODBC32.SQL_CVT.NUMERIC; break; } case ODBC32.SQL_TYPE.WCHAR: { sqlconvert = ODBC32.SQL_CONVERT.CHAR; sqlcvt = ODBC32.SQL_CVT.WCHAR; break; } case ODBC32.SQL_TYPE.WVARCHAR: { sqlconvert = ODBC32.SQL_CONVERT.VARCHAR; sqlcvt = ODBC32.SQL_CVT.WVARCHAR; break; } case ODBC32.SQL_TYPE.WLONGVARCHAR: { sqlconvert = ODBC32.SQL_CONVERT.LONGVARCHAR; sqlcvt = ODBC32.SQL_CVT.WLONGVARCHAR; break; } default: Debug.Fail("Testing that sqltype is currently not supported"); return false; } // now we can check if we have already tested that type // if not we need to do so if (0 == (ProviderInfo.TestedSQLTypes & (int)sqlcvt)) { int flags; flags = GetInfoInt32Unhandled((ODBC32.SQL_INFO)sqlconvert); flags = flags & (int)sqlcvt; ProviderInfo.TestedSQLTypes |= (int)sqlcvt; ProviderInfo.SupportedSQLTypes |= flags; } // now check if the type is supported and return the result // return (0 != (ProviderInfo.SupportedSQLTypes & (int)sqlcvt)); } internal bool TestRestrictedSqlBindType(ODBC32.SQL_TYPE sqltype) { ODBC32.SQL_CVT sqlcvt; switch (sqltype) { case ODBC32.SQL_TYPE.NUMERIC: { sqlcvt = ODBC32.SQL_CVT.NUMERIC; break; } case ODBC32.SQL_TYPE.DECIMAL: { sqlcvt = ODBC32.SQL_CVT.DECIMAL; break; } default: Debug.Fail("Testing that sqltype is currently not supported"); return false; } return (0 != (ProviderInfo.RestrictedSQLBindTypes & (int)sqlcvt)); } // suppress this message - we cannot use SafeHandle here. Also, see notes in the code (VSTFDEVDIV# 560355) [SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive")] protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { DbTransaction transaction = InnerConnection.BeginTransaction(isolationLevel); // VSTFDEVDIV# 560355 - InnerConnection doesn't maintain a ref on the outer connection (this) and // subsequently leaves open the possibility that the outer connection could be GC'ed before the DbTransaction // is fully hooked up (leaving a DbTransaction with a null connection property). Ensure that this is reachable // until the completion of BeginTransaction with KeepAlive GC.KeepAlive(this); return transaction; } internal OdbcTransaction Open_BeginTransaction(IsolationLevel isolevel) { CheckState(ADP.BeginTransaction); // MDAC 68323 RollbackDeadTransaction(); if ((null != _weakTransaction) && _weakTransaction.IsAlive) { // regression from Dispose/Finalize work throw ADP.ParallelTransactionsNotSupported(this); } //Use the default for unspecified. switch (isolevel) { case IsolationLevel.Unspecified: case IsolationLevel.ReadUncommitted: case IsolationLevel.ReadCommitted: case IsolationLevel.RepeatableRead: case IsolationLevel.Serializable: case IsolationLevel.Snapshot: break; case IsolationLevel.Chaos: throw ODBC.NotSupportedIsolationLevel(isolevel); default: throw ADP.InvalidIsolationLevel(isolevel); }; //Start the transaction OdbcConnectionHandle connectionHandle = ConnectionHandle; ODBC32.RetCode retcode = connectionHandle.BeginTransaction(ref isolevel); if (retcode == ODBC32.RetCode.ERROR) { HandleError(connectionHandle, retcode); } OdbcTransaction transaction = new OdbcTransaction(this, isolevel, connectionHandle); _weakTransaction = new WeakReference(transaction); // MDAC 69188 return transaction; } internal void Open_ChangeDatabase(string value) { CheckState(ADP.ChangeDatabase); // Database name must not be null, empty or whitspace if ((null == value) || (0 == value.Trim().Length)) { // MDAC 62679 throw ADP.EmptyDatabaseName(); } if (1024 < value.Length * 2 + 2) { throw ADP.DatabaseNameTooLong(); } RollbackDeadTransaction(); //Set the database OdbcConnectionHandle connectionHandle = ConnectionHandle; ODBC32.RetCode retcode = connectionHandle.SetConnectionAttribute3(ODBC32.SQL_ATTR.CURRENT_CATALOG, value, checked((int)value.Length * 2)); if (retcode != ODBC32.RetCode.SUCCESS) { HandleError(connectionHandle, retcode); } } internal string Open_GetServerVersion() { //SQLGetInfo - SQL_DBMS_VER return GetInfoStringUnhandled(ODBC32.SQL_INFO.DBMS_VER, true); } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type PostRequest. /// </summary> public partial class PostRequest : BaseRequest, IPostRequest { /// <summary> /// Constructs a new PostRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public PostRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified Post using POST. /// </summary> /// <param name="postToCreate">The Post to create.</param> /// <returns>The created Post.</returns> public System.Threading.Tasks.Task<Post> CreateAsync(Post postToCreate) { return this.CreateAsync(postToCreate, CancellationToken.None); } /// <summary> /// Creates the specified Post using POST. /// </summary> /// <param name="postToCreate">The Post to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Post.</returns> public async System.Threading.Tasks.Task<Post> CreateAsync(Post postToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<Post>(postToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified Post. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified Post. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<Post>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified Post. /// </summary> /// <returns>The Post.</returns> public System.Threading.Tasks.Task<Post> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified Post. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The Post.</returns> public async System.Threading.Tasks.Task<Post> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<Post>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified Post using PATCH. /// </summary> /// <param name="postToUpdate">The Post to update.</param> /// <returns>The updated Post.</returns> public System.Threading.Tasks.Task<Post> UpdateAsync(Post postToUpdate) { return this.UpdateAsync(postToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified Post using PATCH. /// </summary> /// <param name="postToUpdate">The Post to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated Post.</returns> public async System.Threading.Tasks.Task<Post> UpdateAsync(Post postToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<Post>(postToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IPostRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IPostRequest Expand(Expression<Func<Post, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IPostRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IPostRequest Select(Expression<Func<Post, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="postToInitialize">The <see cref="Post"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(Post postToInitialize) { if (postToInitialize != null && postToInitialize.AdditionalData != null) { if (postToInitialize.Extensions != null && postToInitialize.Extensions.CurrentPage != null) { postToInitialize.Extensions.AdditionalData = postToInitialize.AdditionalData; object nextPageLink; postToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { postToInitialize.Extensions.InitializeNextPageRequest( this.Client, nextPageLinkString); } } if (postToInitialize.Attachments != null && postToInitialize.Attachments.CurrentPage != null) { postToInitialize.Attachments.AdditionalData = postToInitialize.AdditionalData; object nextPageLink; postToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { postToInitialize.Attachments.InitializeNextPageRequest( this.Client, nextPageLinkString); } } } } } }
using System; using System.Data; using Csla; using Csla.Data; using ParentLoadSoftDelete.DataAccess; using ParentLoadSoftDelete.DataAccess.ERLevel; namespace ParentLoadSoftDelete.Business.ERLevel { /// <summary> /// E06_Country (editable child object).<br/> /// This is a generated base class of <see cref="E06_Country"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="E07_RegionObjects"/> of type <see cref="E07_RegionColl"/> (1:M relation to <see cref="E08_Region"/>)<br/> /// This class is an item of <see cref="E05_CountryColl"/> collection. /// </remarks> [Serializable] public partial class E06_Country : BusinessBase<E06_Country> { #region Static Fields private static int _lastID; #endregion #region State Fields [NotUndoable] private byte[] _rowVersion = new byte[] {}; [NotUndoable] [NonSerialized] internal int parent_SubContinent_ID = 0; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Country_ID"/> property. /// </summary> public static readonly PropertyInfo<int> Country_IDProperty = RegisterProperty<int>(p => p.Country_ID, "Countries ID"); /// <summary> /// Gets the Countries ID. /// </summary> /// <value>The Countries ID.</value> public int Country_ID { get { return GetProperty(Country_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="Country_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Country_NameProperty = RegisterProperty<string>(p => p.Country_Name, "Countries Name"); /// <summary> /// Gets or sets the Countries Name. /// </summary> /// <value>The Countries Name.</value> public string Country_Name { get { return GetProperty(Country_NameProperty); } set { SetProperty(Country_NameProperty, value); } } /// <summary> /// Maintains metadata about <see cref="ParentSubContinentID"/> property. /// </summary> public static readonly PropertyInfo<int> ParentSubContinentIDProperty = RegisterProperty<int>(p => p.ParentSubContinentID, "ParentSubContinentID"); /// <summary> /// Gets or sets the ParentSubContinentID. /// </summary> /// <value>The ParentSubContinentID.</value> public int ParentSubContinentID { get { return GetProperty(ParentSubContinentIDProperty); } set { SetProperty(ParentSubContinentIDProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="E07_Country_SingleObject"/> property. /// </summary> public static readonly PropertyInfo<E07_Country_Child> E07_Country_SingleObjectProperty = RegisterProperty<E07_Country_Child>(p => p.E07_Country_SingleObject, "E07 Country Single Object", RelationshipTypes.Child); /// <summary> /// Gets the E07 Country Single Object ("parent load" child property). /// </summary> /// <value>The E07 Country Single Object.</value> public E07_Country_Child E07_Country_SingleObject { get { return GetProperty(E07_Country_SingleObjectProperty); } private set { LoadProperty(E07_Country_SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="E07_Country_ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<E07_Country_ReChild> E07_Country_ASingleObjectProperty = RegisterProperty<E07_Country_ReChild>(p => p.E07_Country_ASingleObject, "E07 Country ASingle Object", RelationshipTypes.Child); /// <summary> /// Gets the E07 Country ASingle Object ("parent load" child property). /// </summary> /// <value>The E07 Country ASingle Object.</value> public E07_Country_ReChild E07_Country_ASingleObject { get { return GetProperty(E07_Country_ASingleObjectProperty); } private set { LoadProperty(E07_Country_ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="E07_RegionObjects"/> property. /// </summary> public static readonly PropertyInfo<E07_RegionColl> E07_RegionObjectsProperty = RegisterProperty<E07_RegionColl>(p => p.E07_RegionObjects, "E07 Region Objects", RelationshipTypes.Child); /// <summary> /// Gets the E07 Region Objects ("parent load" child property). /// </summary> /// <value>The E07 Region Objects.</value> public E07_RegionColl E07_RegionObjects { get { return GetProperty(E07_RegionObjectsProperty); } private set { LoadProperty(E07_RegionObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="E06_Country"/> object. /// </summary> /// <returns>A reference to the created <see cref="E06_Country"/> object.</returns> internal static E06_Country NewE06_Country() { return DataPortal.CreateChild<E06_Country>(); } /// <summary> /// Factory method. Loads a <see cref="E06_Country"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="E06_Country"/> object.</returns> internal static E06_Country GetE06_Country(SafeDataReader dr) { E06_Country obj = new E06_Country(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.LoadProperty(E07_RegionObjectsProperty, E07_RegionColl.NewE07_RegionColl()); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="E06_Country"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public E06_Country() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="E06_Country"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { LoadProperty(Country_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); LoadProperty(E07_Country_SingleObjectProperty, DataPortal.CreateChild<E07_Country_Child>()); LoadProperty(E07_Country_ASingleObjectProperty, DataPortal.CreateChild<E07_Country_ReChild>()); LoadProperty(E07_RegionObjectsProperty, DataPortal.CreateChild<E07_RegionColl>()); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="E06_Country"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Country_IDProperty, dr.GetInt32("Country_ID")); LoadProperty(Country_NameProperty, dr.GetString("Country_Name")); LoadProperty(ParentSubContinentIDProperty, dr.GetInt32("Parent_SubContinent_ID")); _rowVersion = dr.GetValue("RowVersion") as byte[]; // parent properties parent_SubContinent_ID = dr.GetInt32("Parent_SubContinent_ID"); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child <see cref="E07_Country_Child"/> object. /// </summary> /// <param name="child">The child object to load.</param> internal void LoadChild(E07_Country_Child child) { LoadProperty(E07_Country_SingleObjectProperty, child); } /// <summary> /// Loads child <see cref="E07_Country_ReChild"/> object. /// </summary> /// <param name="child">The child object to load.</param> internal void LoadChild(E07_Country_ReChild child) { LoadProperty(E07_Country_ASingleObjectProperty, child); } /// <summary> /// Inserts a new <see cref="E06_Country"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(E04_SubContinent parent) { using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnInsertPre(args); var dal = dalManager.GetProvider<IE06_CountryDal>(); using (BypassPropertyChecks) { int country_ID = -1; _rowVersion = dal.Insert( parent.SubContinent_ID, out country_ID, Country_Name ); LoadProperty(Country_IDProperty, country_ID); } OnInsertPost(args); // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="E06_Country"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update() { if (!IsDirty) return; using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnUpdatePre(args); var dal = dalManager.GetProvider<IE06_CountryDal>(); using (BypassPropertyChecks) { _rowVersion = dal.Update( Country_ID, Country_Name, ParentSubContinentID, _rowVersion ); } OnUpdatePost(args); // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Self deletes the <see cref="E06_Country"/> object from database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf() { using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); // flushes all pending data operations FieldManager.UpdateChildren(this); OnDeletePre(args); var dal = dalManager.GetProvider<IE06_CountryDal>(); using (BypassPropertyChecks) { dal.Delete(ReadProperty(Country_IDProperty)); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void MultiplySubtractNegatedSingle() { var test = new SimpleTernaryOpTest__MultiplySubtractNegatedSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleTernaryOpTest__MultiplySubtractNegatedSingle { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, Single[] inArray3, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Single, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Single> _fld1; public Vector256<Single> _fld2; public Vector256<Single> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__MultiplySubtractNegatedSingle testClass) { var result = Fma.MultiplySubtractNegated(_fld1, _fld2, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplySubtractNegatedSingle testClass) { fixed (Vector256<Single>* pFld1 = &_fld1) fixed (Vector256<Single>* pFld2 = &_fld2) fixed (Vector256<Single>* pFld3 = &_fld3) { var result = Fma.MultiplySubtractNegated( Avx.LoadVector256((Single*)(pFld1)), Avx.LoadVector256((Single*)(pFld2)), Avx.LoadVector256((Single*)(pFld3)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Single[] _data3 = new Single[Op3ElementCount]; private static Vector256<Single> _clsVar1; private static Vector256<Single> _clsVar2; private static Vector256<Single> _clsVar3; private Vector256<Single> _fld1; private Vector256<Single> _fld2; private Vector256<Single> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__MultiplySubtractNegatedSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); } public SimpleTernaryOpTest__MultiplySubtractNegatedSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, _data3, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Fma.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Fma.MultiplySubtractNegated( Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector256<Single>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Fma.MultiplySubtractNegated( Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr)), Avx.LoadVector256((Single*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Fma.MultiplySubtractNegated( Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr)), Avx.LoadAlignedVector256((Single*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtractNegated), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>), typeof(Vector256<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector256<Single>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtractNegated), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>), typeof(Vector256<Single>) }) .Invoke(null, new object[] { Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr)), Avx.LoadVector256((Single*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtractNegated), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>), typeof(Vector256<Single>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr)), Avx.LoadAlignedVector256((Single*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Fma.MultiplySubtractNegated( _clsVar1, _clsVar2, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Single>* pClsVar1 = &_clsVar1) fixed (Vector256<Single>* pClsVar2 = &_clsVar2) fixed (Vector256<Single>* pClsVar3 = &_clsVar3) { var result = Fma.MultiplySubtractNegated( Avx.LoadVector256((Single*)(pClsVar1)), Avx.LoadVector256((Single*)(pClsVar2)), Avx.LoadVector256((Single*)(pClsVar3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray3Ptr); var result = Fma.MultiplySubtractNegated(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr)); var op3 = Avx.LoadVector256((Single*)(_dataTable.inArray3Ptr)); var result = Fma.MultiplySubtractNegated(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr)); var op3 = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray3Ptr)); var result = Fma.MultiplySubtractNegated(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__MultiplySubtractNegatedSingle(); var result = Fma.MultiplySubtractNegated(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__MultiplySubtractNegatedSingle(); fixed (Vector256<Single>* pFld1 = &test._fld1) fixed (Vector256<Single>* pFld2 = &test._fld2) fixed (Vector256<Single>* pFld3 = &test._fld3) { var result = Fma.MultiplySubtractNegated( Avx.LoadVector256((Single*)(pFld1)), Avx.LoadVector256((Single*)(pFld2)), Avx.LoadVector256((Single*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Fma.MultiplySubtractNegated(_fld1, _fld2, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Single>* pFld1 = &_fld1) fixed (Vector256<Single>* pFld2 = &_fld2) fixed (Vector256<Single>* pFld3 = &_fld3) { var result = Fma.MultiplySubtractNegated( Avx.LoadVector256((Single*)(pFld1)), Avx.LoadVector256((Single*)(pFld2)), Avx.LoadVector256((Single*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Fma.MultiplySubtractNegated(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Fma.MultiplySubtractNegated( Avx.LoadVector256((Single*)(&test._fld1)), Avx.LoadVector256((Single*)(&test._fld2)), Avx.LoadVector256((Single*)(&test._fld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Single> op1, Vector256<Single> op2, Vector256<Single> op3, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] inArray3 = new Single[Op3ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] inArray3 = new Single[Op3ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector256<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] secondOp, Single[] thirdOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(MathF.Round(-(firstOp[0] * secondOp[0]) - thirdOp[0], 3)) != BitConverter.SingleToInt32Bits(MathF.Round(result[0], 3))) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(MathF.Round(-(firstOp[i] * secondOp[i]) - thirdOp[i], 3)) != BitConverter.SingleToInt32Bits(MathF.Round(result[i], 3))) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Fma)}.{nameof(Fma.MultiplySubtractNegated)}<Single>(Vector256<Single>, Vector256<Single>, Vector256<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections.Generic; using System.Text; using System.Web.UI.WebControls; using DotNetNuke.Common; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Modules; using DotNetNuke.Entities.Modules.Actions; using DotNetNuke.Security; using DotNetNuke.Services.Exceptions; using DotNetNuke.Services.Localization; using ICG.Modules.DnnQuiz.Components.Controllers; using ICG.Modules.DnnQuiz.Components.InfoObjects; namespace ICG.Modules.DnnQuiz { /// <summary> /// Main view control for working with the module /// </summary> public partial class ViewICGDNNQuiz : PortalModuleBase, IActionable { /// <summary> /// Handles the Load event of the Page control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e"> /// The <see cref="EventArgs" /> instance containing the event data. /// </param> protected void Page_Load(object sender, EventArgs e) { try { //Short circuit if a postback! if (IsPostBack) return; if (UserInfo.UserID > 0) { //Try to get the quizzes List<UserQuizDisplay> quizList; //If we can edit, or the user is a superuser get all quizzes if (IsEditable || UserInfo.IsSuperUser) quizList = QuizController.GetAllQuizzesForDisplay(UserId, ModuleId); else { //Otherwise get my quizzes! quizList = QuizController.GetQuizzesForUserDisplay(UserId, ModuleId); } //If we have them bind and display if (quizList != null && quizList.Count > 0) { rptQuizList.DataSource = quizList; rptQuizList.DataBind(); lblNoQuizzes.Visible = false; lblMustLogin.Visible = false; } else { rptQuizList.Visible = false; lblNoQuizzes.Visible = true; lblMustLogin.Visible = false; } } else { //Unauthenticated user rptQuizList.Visible = false; lblNoQuizzes.Visible = false; lblMustLogin.Visible = true; } } catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); } } #region IActionable Members /// <summary> /// Gets the module actions which allow users to add quizzes /// </summary> /// <value>The module actions.</value> public ModuleActionCollection ModuleActions { get { //create a new action to add an item, this will be added to the controls //dropdown menu var actions = new ModuleActionCollection(); actions.Add(GetNextActionID(), Localization.GetString("AddQuiz", LocalResourceFile), ModuleActionType.AddContent, "", "", EditUrl("QuizId", "-1"), false, SecurityAccessLevel.Edit, true, false); return actions; } } #endregion /// <summary> /// Handles the ItemDataBound event of the rptQuizList control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RepeaterItemEventArgs"/> instance containing the event data.</param> protected void rptQuizList_ItemDataBound(object sender, RepeaterItemEventArgs e) { //Only work with items if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) return; //Get the data object and the literal var oInfo = (UserQuizDisplay) e.Item.DataItem; var litItem = (Literal) e.Item.FindControl("litItem"); //Get the template var oBuilder = new StringBuilder(Localization.GetString("ItemTemplate", LocalResourceFile)); //Can edit, show edit and view results if (IsEditable) { oBuilder.Replace("[EDIT]", "<a href='" + EditUrl("QuizId", oInfo.QuizId.ToString()) + "'>Edit</a>"); oBuilder.Replace("[VIEWRESULTS]", "&nbsp;<a href='" + EditUrl("Quizid", oInfo.QuizId.ToString(), "QuizResults") + "'>View Results</a>"); } else { oBuilder.Replace("[EDIT]", ""); oBuilder.Replace("[VIEWRESULTS]", ""); } //Replace the title oBuilder.Replace("[QUIZTITLE]", oInfo.QuizTitle); //Build links var takeQuiz = Globals.NavigateURL("TakeQuiz", "mid=" + ModuleId, "quizId=" + Server.UrlEncode(UrlUtils.EncryptParameter(oInfo.QuizId.ToString()))); var certificate = Globals.NavigateURL("QuizCert", "mid=" + ModuleId, "quizId=" + Server.UrlEncode(UrlUtils.EncryptParameter(oInfo.QuizId.ToString())), "exp=" + Server.UrlEncode(UrlUtils.EncryptParameter( Server.UrlEncode(oInfo.ExpirationDate.ToShortDateString()))), "resId=" + oInfo.ResultId); const string noSkinQsParams = "&SkinSrc=[G]Skins%2f_default%2fNo+Skin&ContainerSrc=[G]Containers%2f_default%2fNo+Container"; //Set the status, take, and complete items if (oInfo.Passed) { if (oInfo.CanExpire) { //Set status, and completion link oBuilder.Replace("[STATUS]", Localization.GetString("CompleteWithExpiration", LocalResourceFile).Replace( "[EXPIRATION]", oInfo.ExpirationDate.ToShortDateString())); oBuilder.Replace("[COMPLETIONCERTIFICATE]", "<a href='" + certificate + "'>" + Localization.GetString("CompletionCertificate", LocalResourceFile) + "</a>"); if (DateTime.Now > oInfo.ExpirationDate.AddDays(-30)) oBuilder.Replace("[TAKEQUIZ]", "<a href='" + takeQuiz + "'>" + Localization.GetString("TakeQuiz", LocalResourceFile) + "</a>"); else oBuilder.Replace("[TAKEQUIZ]", ""); oBuilder.Replace("[COMPLETIONCERTIFICATEPRINT]", "<a href='" + certificate + noSkinQsParams + "'>" + Localization.GetString("CompletionCertificate", LocalResourceFile) + "</a>"); } else { oBuilder.Replace("[STATUS]", Localization.GetString("Complete", LocalResourceFile)); oBuilder.Replace("[COMPLETIONCERTIFICATE]", "<a href='" + certificate + "'>" + Localization.GetString("CompletionCertificate", LocalResourceFile) + "</a>"); oBuilder.Replace("[TAKEQUIZ]", ""); oBuilder.Replace("[COMPLETIONCERTIFICATEPRINT]", "<a href='" + certificate + noSkinQsParams + "'>" + Localization.GetString("CompletionCertificate", LocalResourceFile) + "</a>"); } } else { oBuilder.Replace("[STATUS]", Localization.GetString("NotComplete", LocalResourceFile)); //If taken, not passed, and not allowed retake hide link if (oInfo.ResultId > 0 && !oInfo.Passed && !oInfo.AllowRetake) oBuilder.Replace("[TAKEQUIZ]", string.Empty); else oBuilder.Replace("[TAKEQUIZ]", "<a href='" + takeQuiz + "'>" + Localization.GetString("TakeQuiz", LocalResourceFile) + "</a>"); oBuilder.Replace("[COMPLETIONCERTIFICATE]", ""); oBuilder.Replace("[COMPLETIONCERTIFICATEPRINT]", ""); } //Store it litItem.Text = oBuilder.ToString(); } } }
using HTTPlease; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Threading.Tasks; using VaultSharp; using VaultSharp.Backends.Secret.Models.PKI; namespace DaaSDemo.Provisioning.Provisioners { using Common.Options; using Crypto; using Models.Data; using KubeClient; using KubeClient.Models; /// <summary> /// Provisioning facility for Kubernetes Secrets from Vault certificate credentials. /// </summary> public class ServerCredentialsProvisioner : Provisioner { /// <summary> /// Create a new <see cref="ServerCredentialsProvisioner"/>. /// </summary> /// <param name="logger"> /// The provisioner's logger. /// </param> /// <param name="kubeClient"> /// The <see cref="KubeApiClient"/> used to communicate with the Kubernetes API. /// </param> /// <param name="vaultClient"> /// The <see cref="IVaultClient"/> used to communicate with the Vault API. /// </param> /// <param name="kubeResources"> /// A factory for Kubernetes resource models. /// </param> /// <param name="vaultOptions"> /// Application-level Vault settings. /// </param> /// <param name="kubeOptions"> /// Application-level Kubernetes settings. /// </param> public ServerCredentialsProvisioner(ILogger<DatabaseServerProvisioner> logger, KubeApiClient kubeClient, IVaultClient vaultClient, KubeResources kubeResources, IOptions<VaultOptions> vaultOptions, IOptions<KubernetesOptions> kubeOptions) : base(logger) { if (kubeClient == null) throw new ArgumentNullException(nameof(kubeClient)); if (vaultClient == null) throw new ArgumentNullException(nameof(vaultClient)); if (kubeResources == null) throw new ArgumentNullException(nameof(kubeResources)); if (vaultOptions == null) throw new ArgumentNullException(nameof(vaultOptions)); if (kubeOptions == null) throw new ArgumentNullException(nameof(kubeOptions)); KubeClient = kubeClient; VaultClient = vaultClient; KubeResources = kubeResources; VaultOptions = vaultOptions.Value; KubeOptions = kubeOptions.Value; } /// <summary> /// The server's current state (if known). /// </summary> public DatabaseServer State { get; set; } /// <summary> /// The <see cref="KubeApiClient"/> used to communicate with the Kubernetes API. /// </summary> KubeApiClient KubeClient { get; } /// <param name="vaultClient"> /// The <see cref="IVaultClient"/> used to communicate with the Vault API. /// </param> IVaultClient VaultClient { get; } /// <summary> /// A factory for Kubernetes resource models. /// </summary> KubeResources KubeResources { get; } /// <summary> /// Application-level Kubernetes settings. /// </summary> KubernetesOptions KubeOptions { get; } /// <summary> /// Application-level Vault settings. /// </summary> VaultOptions VaultOptions { get; } /// <summary> /// Find the server's associated Secret for credentials. /// </summary> /// <returns> /// The Secret, or <c>null</c> if it was not found. /// </returns> public async Task<SecretV1> FindCredentialsSecret() { RequireCurrentState(); List<SecretV1> matchingSecrets = await KubeClient.SecretsV1().List( labelSelector: $"cloud.dimensiondata.daas.server-id = {State.Id}, cloud.dimensiondata.daas.secret-type = credentials", kubeNamespace: KubeOptions.KubeNamespace ); if (matchingSecrets.Count == 0) return null; return matchingSecrets[matchingSecrets.Count - 1]; } /// <summary> /// Ensure that a Secret for data exists for the specified database server. /// </summary> /// <returns> /// The Secret resource, as a <see cref="SecretV1"/>. /// </returns> public async Task<SecretV1> EnsureCredentialsSecretPresent() { RequireCurrentState(); SecretV1 existingSecret = await FindCredentialsSecret(); if (existingSecret != null) { Log.LogInformation("Found existing credentials secret {SecretName} for server {ServerId}.", existingSecret.Metadata.Name, State.Id ); return existingSecret; } Log.LogInformation("Creating credentials secret for server {ServerId}...", State.Id ); Log.LogInformation("Requesting X.509 certificate..."); CertificateCredentials serverCertificate = await RequestServerCertificate(); SecretV1 createdSecret = await KubeClient.SecretsV1().Create( KubeResources.CredentialsSecret(State, serverCertificate, kubeNamespace: KubeOptions.KubeNamespace ) ); Log.LogInformation("Successfully created credentials secret {SecretName} for server {ServerId}.", createdSecret.Metadata.Name, State.Id ); return createdSecret; } /// <summary> /// Ensure that a Secret for credentials does not exist for the specified database server. /// </summary> /// <returns> /// <c>true</c>, if the controller is now absent; otherwise, <c>false</c>. /// </returns> public async Task<bool> EnsureCredentialsSecretAbsent() { RequireCurrentState(); SecretV1 credentialsSecret = await FindCredentialsSecret(); if (credentialsSecret == null) return true; Log.LogInformation("Deleting credentials secret {SecretName} for server {ServerId}...", credentialsSecret.Metadata.Name, State.Id ); try { await KubeClient.SecretsV1().Delete( name: credentialsSecret.Metadata.Name, kubeNamespace: KubeOptions.KubeNamespace ); } catch (HttpRequestException<StatusV1> deleteFailed) { Log.LogError("Failed to delete credentials secret {SecretName} for server {ServerId} (Message:{FailureMessage}, Reason:{FailureReason}).", credentialsSecret.Metadata.Name, State.Id, deleteFailed.Response.Message, deleteFailed.Response.Reason ); return false; } Log.LogInformation("Deleted credentials secret {SecretName} for server {ServerId}.", credentialsSecret.Metadata.Name, State.Id ); return true; } /// <summary> /// Request an X.509 certificate for the database server. /// </summary> /// <returns> /// <see cref="CertificateCredentials"> representing the certificate. /// </returns> async Task<CertificateCredentials> RequestServerCertificate() { RequireCurrentState(); string subjectName = $"database.{KubeOptions.ClusterPublicFQDN}"; string[] subjectAlternativeNames = new string[] { $"{State.Name}.database.{KubeOptions.ClusterPublicFQDN}" // TODO: Add SAN for server's internal Service FQDN'. }; Log.LogInformation("Requesting server certificate for {ServerId} (Subject = {SubjectName} , SANs = {@SubjectAlternativeNames}).", State.Id, subjectName, subjectAlternativeNames ); var credentials = await VaultClient.PKIGenerateDynamicCredentialsAsync( VaultOptions.CertificatePolicies.DatabaseServer, new CertificateCredentialsRequestOptions { CertificateFormat = CertificateFormat.pem, CommonName = subjectName, SubjectAlternativeNames = String.Join(",", subjectAlternativeNames), TimeToLive = "672h" }, VaultOptions.PkiBasePath ); Log.LogInformation("Acquired server certificate for {ServerId}.", State.Id ); return credentials.Data; } /// <summary> /// Ensure that <see cref="State"/> is populated. /// </summary> void RequireCurrentState() { if (State == null) throw new InvalidOperationException($"Cannot use {nameof(ServerCredentialsProvisioner)} without current state."); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.DoNotDeclareVisibleInstanceFieldsAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.DoNotDeclareVisibleInstanceFieldsAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests { public class DoNotDeclareVisibleInstanceFieldsTests { [Fact] public async Task CSharp_PublicVariable_PublicContainingType() { await VerifyCS.VerifyAnalyzerAsync(@" public class A { public string field; }", GetCSharpResultAt(4, 19)); } [Fact] public async Task VisualBasic_PublicVariable_PublicContainingType() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class A Public field As System.String End Class", GetBasicResultAt(3, 12)); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task CSharp_PublicVariable_InternalContainingType() { await VerifyCS.VerifyAnalyzerAsync(@" internal class A { public string field; public class B { public string field; } }"); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task VisualBasic_PublicVariable_InternalContainingType() { await VerifyVB.VerifyAnalyzerAsync(@" Friend Class A Public field As System.String Public Class B Public field As System.String End Class End Class "); } [Fact] public async Task CSharp_DefaultVisibility() { await VerifyCS.VerifyAnalyzerAsync(@" public class A { string field; }"); } [Fact] public async Task VisualBasic_DefaultVisibility() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class A Dim field As System.String End Class"); } [Fact] public async Task CSharp_PublicStaticVariable() { await VerifyCS.VerifyAnalyzerAsync(@" public class A { public static string field; }"); } [Fact] public async Task VisualBasic_PublicStaticVariable() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class A Public Shared field as System.String End Class"); } [Fact] public async Task CSharp_PublicStaticReadonlyVariable() { await VerifyCS.VerifyAnalyzerAsync(@" public class A { public static readonly string field; }"); } [Fact] public async Task VisualBasic_PublicStaticReadonlyVariable() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class A Public Shared ReadOnly field as System.String End Class"); } [Fact] public async Task CSharp_PublicConstVariable() { await VerifyCS.VerifyAnalyzerAsync(@" public class A { public const string field = ""X""; }"); } [Fact] public async Task VisualBasic_PublicConstVariable() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class A Public Const field as System.String = ""X"" End Class"); } [Fact] public async Task CSharp_ProtectedVariable_PublicContainingType() { await VerifyCS.VerifyAnalyzerAsync(@" public class A { protected string field; }", GetCSharpResultAt(4, 22)); } [Fact] public async Task VisualBasic_ProtectedVariable_PublicContainingType() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class A Protected field As System.String End Class", GetBasicResultAt(3, 15)); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task CSharp_ProtectedVariable_InternalContainingType() { await VerifyCS.VerifyAnalyzerAsync(@" internal class A { protected string field; public class B { protected string field; } }"); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task VisualBasic_ProtectedVariable_InternalContainingType() { await VerifyVB.VerifyAnalyzerAsync(@" Friend Class A Protected field As System.String Public Class B Protected field As System.String End Class End Class "); } [Fact] public async Task CSharp_ProtectedStaticVariable() { await VerifyCS.VerifyAnalyzerAsync(@" public class A { protected static string field; }"); } [Fact] public async Task VisualBasic_ProtectedStaticVariable() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class A Protected Shared field as System.String End Class"); } [Fact] public async Task CSharp_ProtectedStaticReadonlyVariable() { await VerifyCS.VerifyAnalyzerAsync(@" public class A { protected static readonly string field; }"); } [Fact] public async Task VisualBasic_ProtectedStaticReadonlyVariable() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class A Protected Shared ReadOnly field as System.String End Class"); } [Fact] public async Task CSharp_ProtectedConstVariable() { await VerifyCS.VerifyAnalyzerAsync(@" public class A { protected const string field = ""X""; }"); } [Fact] public async Task VisualBasic_ProtectedConstVariable() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class A Protected Const field as System.String = ""X"" End Class"); } [Fact] public async Task CSharp_ProtectedInternalVariable_PublicContainingType() { await VerifyCS.VerifyAnalyzerAsync(@" public class A { protected internal string field; }", GetCSharpResultAt(4, 31)); } [Fact] public async Task VisualBasic_ProtectedFriendVariable_PublicContainingType() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class A Protected Friend field As System.String End Class", GetBasicResultAt(3, 22)); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task CSharp_ProtectedInternalVariable_InternalContainingType() { await VerifyCS.VerifyAnalyzerAsync(@" internal class A { protected internal string field; public class B { protected internal string field; } }"); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task VisualBasic_ProtectedFriendVariable_InternalContainingType() { await VerifyVB.VerifyAnalyzerAsync(@" Friend Class A Protected Friend field As System.String Public Class B Protected Friend field As System.String End Class End Class "); } [Fact] public async Task CSharp_ProtectedInternalStaticVariable() { await VerifyCS.VerifyAnalyzerAsync(@" public class A { protected internal static string field; }"); } [Fact] public async Task VisualBasic_ProtectedFriendStaticVariable() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class A Protected Friend Shared field as System.String End Class"); } [Fact] public async Task CSharp_ProtectedInternalStaticReadonlyVariable() { await VerifyCS.VerifyAnalyzerAsync(@" public class A { protected internal static readonly string field; }"); } [Fact] public async Task VisualBasic_ProtectedFriendStaticReadonlyVariable() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class A Protected Friend Shared ReadOnly field as System.String End Class"); } [Fact] public async Task CSharp_ProtectedInternalConstVariable() { await VerifyCS.VerifyAnalyzerAsync(@" public class A { protected internal const string field = ""X""; }"); } [Fact] public async Task VisualBasic_ProtectedFriendConstVariable() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class A Protected Friend Const field as System.String = ""X"" End Class"); } [Fact, WorkItem(4149, "https://github.com/dotnet/roslyn-analyzers/issues/4149")] public async Task TypeWithStructLayoutAttribute_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] public class C { public int F; } [StructLayout(LayoutKind.Sequential)] public struct S { public int F; }"); await VerifyVB.VerifyAnalyzerAsync(@" Imports System.Runtime.InteropServices <StructLayout(LayoutKind.Sequential)> Public Class C Public F As Integer End Class <StructLayout(LayoutKind.Sequential)> Public Structure S Public F As Integer End Structure"); } [Theory, WorkItem(4149, "https://github.com/dotnet/roslyn-analyzers/issues/4149")] [InlineData("")] [InlineData("dotnet_code_quality.exclude_structs = true")] [InlineData("dotnet_code_quality.exclude_structs = false")] [InlineData("dotnet_code_quality.CA1051.exclude_structs = true")] [InlineData("dotnet_code_quality.CA1051.exclude_structs = false")] public async Task PublicFieldOnStruct_AnalyzerOption(string editorConfigText) { var expectsIssue = !editorConfigText.EndsWith("true", StringComparison.OrdinalIgnoreCase); var csharpCode = @" public struct S { public int " + (expectsIssue ? "[|F|]" : "F") + @"; }"; await new VerifyCS.Test { TestState = { Sources = { csharpCode }, AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true [*] {editorConfigText} ") } } }.RunAsync(); var vbCode = @" Public Structure S Public " + (expectsIssue ? "[|F|]" : "F") + @" As Integer End Structure"; await new VerifyVB.Test { TestState = { Sources = { vbCode }, AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true [*] {editorConfigText} ") } } }.RunAsync(); } private static DiagnosticResult GetCSharpResultAt(int line, int column) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic().WithLocation(line, column); #pragma warning restore RS0030 // Do not used banned APIs private static DiagnosticResult GetBasicResultAt(int line, int column) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic().WithLocation(line, column); #pragma warning restore RS0030 // Do not used banned APIs } }
// // Copyright (c) 2004-2016 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. // namespace NLog.UnitTests.Targets.Wrappers { using System; using System.Collections.Generic; using System.Threading; using NLog.Common; using NLog.Targets; using NLog.Targets.Wrappers; using Xunit; public class SplitGroupTargetTests : NLogTestBase { [Fact] public void SplitGroupSyncTest1() { var myTarget1 = new MyTarget(); var myTarget2 = new MyTarget(); var myTarget3 = new MyTarget(); var wrapper = new SplitGroupTarget() { Targets = { myTarget1, myTarget2, myTarget3 }, }; myTarget1.Initialize(null); myTarget2.Initialize(null); myTarget3.Initialize(null); wrapper.Initialize(null); List<Exception> exceptions = new List<Exception>(); var inputEvents = new List<LogEventInfo>(); for (int i = 0; i < 10; ++i) { inputEvents.Add(LogEventInfo.CreateNullEvent()); } int remaining = inputEvents.Count; var allDone = new ManualResetEvent(false); // no exceptions for (int i = 0; i < inputEvents.Count; ++i) { wrapper.WriteAsyncLogEvent(inputEvents[i].WithContinuation(ex => { lock (exceptions) { exceptions.Add(ex); if (Interlocked.Decrement(ref remaining) == 0) { allDone.Set(); } }; })); } allDone.WaitOne(); Assert.Equal(inputEvents.Count, exceptions.Count); foreach (var e in exceptions) { Assert.Null(e); } Assert.Equal(inputEvents.Count, myTarget1.WriteCount); Assert.Equal(inputEvents.Count, myTarget2.WriteCount); Assert.Equal(inputEvents.Count, myTarget3.WriteCount); for (int i = 0; i < inputEvents.Count; ++i) { Assert.Same(inputEvents[i], myTarget1.WrittenEvents[i]); Assert.Same(inputEvents[i], myTarget2.WrittenEvents[i]); Assert.Same(inputEvents[i], myTarget3.WrittenEvents[i]); } Exception flushException = null; var flushHit = new ManualResetEvent(false); wrapper.Flush(ex => { flushException = ex; flushHit.Set(); }); flushHit.WaitOne(); if (flushException != null) { Assert.True(false, flushException.ToString()); } Assert.Equal(1, myTarget1.FlushCount); Assert.Equal(1, myTarget2.FlushCount); Assert.Equal(1, myTarget3.FlushCount); } [Fact] public void SplitGroupSyncTest2() { var wrapper = new SplitGroupTarget() { // no targets }; wrapper.Initialize(null); List<Exception> exceptions = new List<Exception>(); // no exceptions for (int i = 0; i < 10; ++i) { wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); } Assert.Equal(10, exceptions.Count); foreach (var e in exceptions) { Assert.Null(e); } Exception flushException = new Exception("Flush not hit synchronously."); wrapper.Flush(ex => flushException = ex); if (flushException != null) { Assert.True(false, flushException.ToString()); } } public class MyAsyncTarget : Target { public int FlushCount { get; private set; } public int WriteCount { get; private set; } public MyAsyncTarget() : base() { } public MyAsyncTarget(string name) : this() { this.Name = name; } protected override void Write(LogEventInfo logEvent) { throw new NotSupportedException(); } protected override void Write(AsyncLogEventInfo logEvent) { Assert.True(this.FlushCount <= this.WriteCount); this.WriteCount++; ThreadPool.QueueUserWorkItem( s => { if (this.ThrowExceptions) { logEvent.Continuation(new InvalidOperationException("Some problem!")); logEvent.Continuation(new InvalidOperationException("Some problem!")); } else { logEvent.Continuation(null); logEvent.Continuation(null); } }); } protected override void FlushAsync(AsyncContinuation asyncContinuation) { this.FlushCount++; ThreadPool.QueueUserWorkItem( s => asyncContinuation(null)); } public bool ThrowExceptions { get; set; } } public class MyTarget : Target { public MyTarget() { this.WrittenEvents = new List<LogEventInfo>(); } public MyTarget(string name) : this() { this.Name = name; } public int FlushCount { get; set; } public int WriteCount { get; set; } public int FailCounter { get; set; } public List<LogEventInfo> WrittenEvents { get; private set; } protected override void Write(LogEventInfo logEvent) { Assert.True(this.FlushCount <= this.WriteCount); lock (this) { this.WriteCount++; this.WrittenEvents.Add(logEvent); } if (this.FailCounter > 0) { this.FailCounter--; throw new InvalidOperationException("Some failure."); } } protected override void FlushAsync(AsyncContinuation asyncContinuation) { this.FlushCount++; asyncContinuation(null); } } } }
/** Copyright 2014-2021 Robert McNeel and Associates Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **/ using System; using System.Drawing; using ccl; using ccl.ShaderNodes; using Rhino.Render; using RhinoCyclesCore.Core; using RhinoCyclesCore.ExtensionMethods; using RhinoCyclesCore.Settings; using static Rhino.Render.RenderWindow; using Rhino.UI; using Eto.Forms; using Rhino.Runtime; namespace RhinoCyclesCore { partial class RenderEngine { public static ccl.PassType PassTypeForStandardChannel(StandardChannels channel) { switch(channel) { case StandardChannels.RGB: case StandardChannels.RGBA: return PassType.Combined; case StandardChannels.DistanceFromCamera: return PassType.Depth; case StandardChannels.NormalXYZ: return PassType.Normal; case StandardChannels.AlbedoRGB: return PassType.DiffuseColor; case StandardChannels.MaterialIds: return PassType.MaterialId; case StandardChannels.ObjectIds: return PassType.ObjectId; default: return PassType.Combined; } } public static StandardChannels StandardChannelForPassType(PassType pass) { switch(pass) { case PassType.Combined: return StandardChannels.RGBA; case PassType.Depth: return StandardChannels.DistanceFromCamera; case PassType.Normal: return StandardChannels.NormalXYZ; case PassType.DiffuseColor: return StandardChannels.AlbedoRGB; case PassType.MaterialId: return StandardChannels.MaterialIds; case PassType.ObjectId: return StandardChannels.ObjectIds; default: return StandardChannels.RGBA; } } /// <summary> /// Construct a full path name to the temp folder for /// McNeel/Rhino/VERSIONNR /// </summary> /// <returns>The full path.</returns> /// <param name="fileName">File name.</param> public static string TempPathForFile(string fileName) { var tmpfhdr = System.IO.Path.Combine( new [] { System.IO.Path.GetTempPath(), "McNeel", "Rhino", $"V{Rhino.RhinoApp.Version.Major}", fileName } ); return tmpfhdr; } public void SaveRenderedBuffer(int sample) { if (!RcCore.It.AllSettings.SaveDebugImages) return; Eto.Forms.Application.Instance.AsyncInvoke(() => { var tmpf = TempPathForFile($"RC_{ sample.ToString("D5")}.png"); RenderWindow.SaveDibAsBitmap(tmpf); }); } /// <summary> /// create a ccl.Scene /// </summary> /// <param name="client">Client to create scene for</param> /// <param name="session">Session this scene is created for</param> /// <param name="render_device">Render device this scene is created for</param> /// <param name="cycles_engine">Engine instance to create for</param> /// <returns></returns> protected static /*Scene*/ void CreateScene(Client client, Session session, Device render_device, RenderEngine cycles_engine, IAllSettings engineSettings) { #region set up scene parameters BvhLayout bvhLayout = BvhLayout.Default; if(render_device.IsOptix) { bvhLayout = BvhLayout.OptiX; } else if (render_device.IsCpu && HostUtils.RunningOnOSX) { bvhLayout = BvhLayout.Bvh2; } var scene_params = new SceneParameters(client, ShadingSystem.SVM, BvhType.Static, false, bvhLayout, false); #endregion #region create scene var scene = new Scene(client, scene_params, session) { #region integrator settings Integrator = { MaxBounce = engineSettings.MaxBounce, TransparentMaxBounce = engineSettings.TransparentMaxBounce, MaxDiffuseBounce = engineSettings.MaxDiffuseBounce, MaxGlossyBounce = engineSettings.MaxGlossyBounce, MaxTransmissionBounce = engineSettings.MaxTransmissionBounce, MaxVolumeBounce = engineSettings.MaxVolumeBounce, NoCaustics = engineSettings.NoCaustics, DiffuseSamples = engineSettings.DiffuseSamples, GlossySamples = engineSettings.GlossySamples, TransmissionSamples = engineSettings.TransmissionSamples, AoSamples = engineSettings.AoSamples, MeshLightSamples = engineSettings.MeshLightSamples, SubsurfaceSamples = engineSettings.SubsurfaceSamples, VolumeSamples = engineSettings.VolumeSamples, AaSamples = engineSettings.AaSamples, FilterGlossy = engineSettings.FilterGlossy, IntegratorMethod = engineSettings.IntegratorMethod, SampleAllLightsDirect = engineSettings.SampleAllLights, SampleAllLightsIndirect = engineSettings.SampleAllLightsIndirect, SampleClampDirect = engineSettings.SampleClampDirect, SampleClampIndirect = engineSettings.SampleClampIndirect, LightSamplingThreshold = engineSettings.LightSamplingThreshold, SamplingPattern = SamplingPattern.Sobol, Seed = engineSettings.Seed, NoShadows = engineSettings.NoShadows, } #endregion }; #endregion scene.Film.SetFilter(FilterType.Gaussian, 1.5f); scene.Film.Exposure = 1.0f; scene.Film.Update(); #region background shader // we add here a simple background shader. This will be repopulated with // other nodes whenever background changes are detected. var background_shader = new Shader(client, Shader.ShaderType.World) { Name = "Rhino Background" }; var bgnode = new BackgroundNode("orig bg"); bgnode.ins.Color.Value = new float4(1.0f); bgnode.ins.Strength.Value = 1.0f; background_shader.AddNode(bgnode); bgnode.outs.Background.Connect(background_shader.Output.ins.Surface); background_shader.FinalizeGraph(); scene.AddShader(background_shader); scene.Background.Shader = background_shader; scene.Background.AoDistance = 0.0f; scene.Background.AoFactor = 0.0f; scene.Background.Visibility = PathRay.AllVisibility; scene.Background.Transparent = false; #endregion session.Scene = scene; } static public float4 CreateFloat4(double x, double y, double z) { return new float4((float)x, (float)y, (float)z, 0.0f); } static public float4 CreateFloat4(byte x, byte y, byte z, byte w) { return new float4(x / 255.0f, y / 255.0f, z / 255.0f, w / 255.0f); } static public float4 CreateFloat4(Color color) { return CreateFloat4(color.R, color.G, color.B, color.A); } /// <summary> /// Pixel count provided by the main monitor where Rhino resides. /// /// Note: on MacOS we are always looking at the primary screen, regardless of where Rhino is opened. /// </summary> static public int _MonitorPixelCount { get; set; } /// <summary> /// Default pixel size based on monitor resolution. /// The screen resolution the Rhino main window is mostly on is used. The width /// and height are multiplied, that is used to determine pixel size. Currently: /// 8K (7680x4320) and larger: 4 /// 4K (3840x2160) and larger: 2 /// Anything lower than Full HD: 1 /// </summary> static public int DefaultPixelSizeBasedOnMonitorResolution { get { int pixelSize = 1; int pixelCount = _MonitorPixelCount; if(pixelCount >= 7_680*4_320) { pixelSize = 4; } else if (pixelCount >= 3_840*2_160) { pixelSize = 2; } return pixelSize; } } public static float DegToRad(float ang) { return ang * (float)Math.PI / 180.0f; } public static Size TileSize(ccl.Device device) { var tilex = RcCore.It.AllSettings.TileX; var tiley = RcCore.It.AllSettings.TileY; if (!RcCore.It.AllSettings.DebugNoOverrideTileSize) { if (device.IsOpenCl) { tilex = tiley = 1024; } else if (device.IsCuda) { tilex = tiley = 512; } else if (device.IsCpu) { tilex = tiley = 32; } } return new Size(tilex, tiley); } /// <summary> /// Set image texture node and link up with correct TextureCoordinateNode output based on /// texture ProjectionMode. /// /// This may add new nodes to the shader! /// </summary> /// <param name="shader"></param> /// <param name="texture"></param> /// <param name="image_node"></param> /// <param name="texture_coordinates"></param> public static void SetProjectionMode(Shader shader, CyclesTextureImage texture, ImageTextureNode image_node, TextureCoordinateNode texture_coordinates) { if (!texture.HasTextureImage) return; Guid g = Guid.NewGuid(); texture_coordinates.UseTransform = false; float4 t = texture.Transform.x; image_node.Translation = t; image_node.Translation.z = 0; image_node.Translation.w = 1; image_node.Scale.x = 1.0f / texture.Transform.y.x; image_node.Scale.y = 1.0f / texture.Transform.y.y; image_node.Rotation.z = -1.0f * DegToRad(texture.Transform.z.z); image_node.Projection = TextureNode.TextureProjection.Flat; image_node.Interpolation = InterpolationType.Cubic; if (texture.ProjectionMode == TextureProjectionMode.WcsBox) { texture_coordinates.UseTransform = true; texture_coordinates.outs.WcsBox.Connect(image_node.ins.Vector); } else if (texture.ProjectionMode == TextureProjectionMode.Wcs) { texture_coordinates.UseTransform = true; texture_coordinates.outs.Object.Connect(image_node.ins.Vector); } else if (texture.ProjectionMode == TextureProjectionMode.Screen) { texture_coordinates.outs.Window.Connect(image_node.ins.Vector); } else if (texture.ProjectionMode == TextureProjectionMode.View) { texture_coordinates.outs.Camera.Connect(image_node.ins.Vector); } else if (texture.ProjectionMode == TextureProjectionMode.EnvironmentMap) { texture_coordinates.UseTransform = false; switch (texture.EnvProjectionMode) { case TextureEnvironmentMappingMode.Spherical: texture_coordinates.outs.EnvSpherical.Connect(image_node.ins.Vector); break; case TextureEnvironmentMappingMode.EnvironmentMap: texture_coordinates.outs.EnvEmap.Connect(image_node.ins.Vector); break; case TextureEnvironmentMappingMode.Box: texture_coordinates.outs.EnvBox.Connect(image_node.ins.Vector); break; case TextureEnvironmentMappingMode.LightProbe: texture_coordinates.outs.EnvLightProbe.Connect(image_node.ins.Vector); break; case TextureEnvironmentMappingMode.Cube: texture_coordinates.outs.EnvCubemap.Connect(image_node.ins.Vector); break; case TextureEnvironmentMappingMode.VerticalCrossCube: texture_coordinates.outs.EnvCubemapVerticalCross.Connect(image_node.ins.Vector); break; case TextureEnvironmentMappingMode.HorizontalCrossCube: texture_coordinates.outs.EnvCubemapHorizontalCross.Connect(image_node.ins.Vector); break; case TextureEnvironmentMappingMode.Hemispherical: texture_coordinates.outs.EnvHemispherical.Connect(image_node.ins.Vector); break; default: texture_coordinates.outs.EnvEmap.Connect(image_node.ins.Vector); break; } } else { texture_coordinates.outs.UV.Connect(image_node.ins.Vector); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using EventManager.Server.WepApi.Areas.HelpPage.ModelDescriptions; using EventManager.Server.WepApi.Areas.HelpPage.Models; namespace EventManager.Server.WepApi.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //------------------------------------------------------------------------------ using System.Data.Common; using System.Diagnostics; using System.Threading; namespace System.Data.SqlClient { internal enum TransactionState { Pending = 0, Active = 1, Aborted = 2, Committed = 3, Unknown = 4, } internal enum TransactionType { LocalFromTSQL = 1, LocalFromAPI = 2, }; sealed internal class SqlInternalTransaction { internal const long NullTransactionId = 0; private TransactionState _transactionState; private TransactionType _transactionType; private long _transactionId; // passed in the MARS headers private int _openResultCount; // passed in the MARS headers private SqlInternalConnection _innerConnection; private bool _disposing; // used to prevent us from throwing exceptions while we're disposing private WeakReference _parent; // weak ref to the outer transaction object; needs to be weak to allow GC to occur. internal bool RestoreBrokenConnection { get; set; } internal bool ConnectionHasBeenRestored { get; set; } internal SqlInternalTransaction(SqlInternalConnection innerConnection, TransactionType type, SqlTransaction outerTransaction) : this(innerConnection, type, outerTransaction, NullTransactionId) { } internal SqlInternalTransaction(SqlInternalConnection innerConnection, TransactionType type, SqlTransaction outerTransaction, long transactionId) { _innerConnection = innerConnection; _transactionType = type; if (null != outerTransaction) { _parent = new WeakReference(outerTransaction); } _transactionId = transactionId; RestoreBrokenConnection = false; ConnectionHasBeenRestored = false; } internal bool HasParentTransaction { get { // Return true if we are an API started local transaction, or if we were a TSQL // started local transaction and were then wrapped with a parent transaction as // a result of a later API begin transaction. bool result = ((TransactionType.LocalFromAPI == _transactionType) || (TransactionType.LocalFromTSQL == _transactionType && _parent != null)); return result; } } internal bool IsAborted { get { return (TransactionState.Aborted == _transactionState); } } internal bool IsActive { get { return (TransactionState.Active == _transactionState); } } internal bool IsCommitted { get { return (TransactionState.Committed == _transactionState); } } internal bool IsCompleted { get { return (TransactionState.Aborted == _transactionState || TransactionState.Committed == _transactionState || TransactionState.Unknown == _transactionState); } } internal bool IsLocal { get { bool result = (TransactionType.LocalFromTSQL == _transactionType || TransactionType.LocalFromAPI == _transactionType ); return result; } } internal bool IsOrphaned { get { // An internal transaction is orphaned when its parent has been // reclaimed by GC. bool result; if (null == _parent) { // No parent, so we better be LocalFromTSQL. Should we even return in this case - // since it could be argued this is invalid? Debug.Assert(false, "Why are we calling IsOrphaned with no parent?"); Debug.Assert(_transactionType == TransactionType.LocalFromTSQL, "invalid state"); result = false; } else if (null == _parent.Target) { // We have an parent, but parent was GC'ed. result = true; } else { // We have an parent, and parent is alive. result = false; } return result; } } internal bool IsZombied { get { return (null == _innerConnection); } } internal int OpenResultsCount { get { return _openResultCount; } } internal SqlTransaction Parent { get { SqlTransaction result = null; // Should we protect against this, since this probably is an invalid state? Debug.Assert(null != _parent, "Why are we calling Parent with no parent?"); if (null != _parent) { result = (SqlTransaction)_parent.Target; } return result; } } internal long TransactionId { get { return _transactionId; } set { Debug.Assert(NullTransactionId == _transactionId, "setting transaction cookie while one is active?"); _transactionId = value; } } internal void Activate() { _transactionState = TransactionState.Active; } private void CheckTransactionLevelAndZombie() { try { if (!IsZombied && GetServerTransactionLevel() == 0) { // If not zombied, not closed, and not in transaction, zombie. Zombie(); } } catch (Exception e) { if (!ADP.IsCatchableExceptionType(e)) { throw; } Zombie(); // If exception caught when trying to check level, zombie. } } internal void CloseFromConnection() { SqlInternalConnection innerConnection = _innerConnection; Debug.Assert(innerConnection != null, "How can we be here if the connection is null?"); bool processFinallyBlock = true; try { innerConnection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.IfRollback, null, IsolationLevel.Unspecified, null); } catch (Exception e) { processFinallyBlock = ADP.IsCatchableExceptionType(e); throw; } finally { if (processFinallyBlock) { // Always ensure we're zombied; Yukon will send an EnvChange that // will cause the zombie, but only if we actually go to the wire; // Sphinx and Shiloh won't send the env change, so we have to handle // them ourselves. Zombie(); } } } internal void Commit() { if (_innerConnection.IsLockedForBulkCopy) { throw SQL.ConnectionLockedForBcpEvent(); } _innerConnection.ValidateConnectionForExecute(null); // If this transaction has been completed, throw exception since it is unusable. try { // COMMIT ignores transaction names, and so there is no reason to pass it anything. COMMIT // simply commits the transaction from the most recent BEGIN, nested or otherwise. _innerConnection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Commit, null, IsolationLevel.Unspecified, null); { ZombieParent(); } } catch (Exception e) { if (ADP.IsCatchableExceptionType(e)) { CheckTransactionLevelAndZombie(); } throw; } } internal void Completed(TransactionState transactionState) { Debug.Assert(TransactionState.Active < transactionState, "invalid transaction completion state?"); _transactionState = transactionState; Zombie(); } internal Int32 DecrementAndObtainOpenResultCount() { Int32 openResultCount = Interlocked.Decrement(ref _openResultCount); if (openResultCount < 0) { throw SQL.OpenResultCountExceeded(); } return openResultCount; } internal void Dispose() { this.Dispose(true); System.GC.SuppressFinalize(this); } private /*protected override*/ void Dispose(bool disposing) { if (disposing) { if (null != _innerConnection) { // implicitly rollback if transaction still valid _disposing = true; this.Rollback(); } } } private int GetServerTransactionLevel() { // This function is needed for those times when it is impossible to determine the server's // transaction level, unless the user's arguments were parsed - which is something we don't want // to do. An example when it is impossible to determine the level is after a rollback. using (SqlCommand transactionLevelCommand = new SqlCommand("set @out = @@trancount", (SqlConnection)(_innerConnection.Owner))) { transactionLevelCommand.Transaction = Parent; SqlParameter parameter = new SqlParameter("@out", SqlDbType.Int); parameter.Direction = ParameterDirection.Output; transactionLevelCommand.Parameters.Add(parameter); transactionLevelCommand.RunExecuteReader(CommandBehavior.Default, RunBehavior.UntilDone, returnStream: false); return (int)parameter.Value; } } internal Int32 IncrementAndObtainOpenResultCount() { Int32 openResultCount = Interlocked.Increment(ref _openResultCount); if (openResultCount < 0) { throw SQL.OpenResultCountExceeded(); } return openResultCount; } internal void InitParent(SqlTransaction transaction) { Debug.Assert(_parent == null, "Why do we have a parent on InitParent?"); _parent = new WeakReference(transaction); } internal void Rollback() { if (_innerConnection.IsLockedForBulkCopy) { throw SQL.ConnectionLockedForBcpEvent(); } _innerConnection.ValidateConnectionForExecute(null); try { // If no arg is given to ROLLBACK it will rollback to the outermost begin - rolling back // all nested transactions as well as the outermost transaction. _innerConnection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.IfRollback, null, IsolationLevel.Unspecified, null); // Since Rollback will rollback to outermost begin, no need to check // server transaction level. This transaction has been completed. Zombie(); } catch (Exception e) { if (ADP.IsCatchableExceptionType(e)) { CheckTransactionLevelAndZombie(); if (!_disposing) { throw; } } else { throw; } } } internal void Rollback(string transactionName) { if (_innerConnection.IsLockedForBulkCopy) { throw SQL.ConnectionLockedForBcpEvent(); } _innerConnection.ValidateConnectionForExecute(null); // ROLLBACK takes either a save point name or a transaction name. It will rollback the // transaction to either the save point with the save point name or begin with the // transaction name. NOTE: for simplicity it is possible to give all save point names // the same name, and ROLLBACK will simply rollback to the most recent save point with the // save point name. if (string.IsNullOrEmpty(transactionName)) throw SQL.NullEmptyTransactionName(); try { _innerConnection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Rollback, transactionName, IsolationLevel.Unspecified, null); } catch (Exception e) { if (ADP.IsCatchableExceptionType(e)) { CheckTransactionLevelAndZombie(); } throw; } } internal void Save(string savePointName) { _innerConnection.ValidateConnectionForExecute(null); // ROLLBACK takes either a save point name or a transaction name. It will rollback the // transaction to either the save point with the save point name or begin with the // transaction name. So, to rollback a nested transaction you must have a save point. // SAVE TRANSACTION MUST HAVE AN ARGUMENT!!! Save Transaction without an arg throws an // exception from the server. So, an overload for SaveTransaction without an arg doesn't make // sense to have. Save Transaction does not affect the transaction level. if (string.IsNullOrEmpty(savePointName)) throw SQL.NullEmptyTransactionName(); try { _innerConnection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Save, savePointName, IsolationLevel.Unspecified, null); } catch (Exception e) { if (ADP.IsCatchableExceptionType(e)) { CheckTransactionLevelAndZombie(); } throw; } } internal void Zombie() { // Called by several places in the code to ensure that the outer // transaction object has been zombied and the parser has broken // it's reference to us. // NOTE: we'll be called from the TdsParser when it gets appropriate // ENVCHANGE events that indicate the transaction has completed, however // we cannot rely upon those events occurring in the case of pre-Yukon // servers (and when we don't go to the wire because the connection // is broken) so we can also be called from the Commit/Rollback/Save // methods to handle that case as well. // There are two parts to a full zombie: // 1) Zombie parent and disconnect outer transaction from internal transaction // 2) Disconnect internal transaction from connection and parser // Number 1 needs to be done whenever a SqlTransaction object is completed. Number // 2 is only done when a transaction is actually completed. Since users can begin // transactions both in and outside of the API, and since nested begins are not actual // transactions we need to distinguish between #1 and #2. ZombieParent(); SqlInternalConnection innerConnection = _innerConnection; _innerConnection = null; if (null != innerConnection) { innerConnection.DisconnectTransaction(this); } } private void ZombieParent() { if (null != _parent) { SqlTransaction parent = (SqlTransaction)_parent.Target; if (null != parent) { parent.Zombie(); } _parent = null; } } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using SDKTemplate; using System; using System.Collections.Generic; using System.Threading.Tasks; using Windows.Devices.Enumeration; using Windows.Media.Audio; using Windows.Media.Capture; using Windows.Media.Devices; using Windows.Media.MediaProperties; using Windows.Media.Render; using Windows.Media.Transcoding; using Windows.Storage; using Windows.Storage.Pickers; using Windows.UI; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace AudioCreation { /// <summary> /// This scenario shows using AudioGraph for audio capture from a microphone with low latency. /// </summary> public sealed partial class Scenario2_DeviceCapture : Page { private MainPage rootPage; private AudioGraph graph; private AudioFileOutputNode fileOutputNode; private AudioDeviceOutputNode deviceOutputNode; private AudioDeviceInputNode deviceInputNode; private DeviceInformationCollection outputDevices; private DeviceInformationCollection inputDevices; public Scenario2_DeviceCapture() { this.InitializeComponent(); } protected override async void OnNavigatedTo(NavigationEventArgs e) { rootPage = MainPage.Current; await PopulateOutputDeviceList(); await PopulateInputDeviceList(); } protected override void OnNavigatedFrom(NavigationEventArgs e) { if (graph != null) { graph.Dispose(); } } private async void FileButton_Click(object sender, RoutedEventArgs e) { await SelectOutputFile(); } private async void RecordStopButton_Click(object sender, RoutedEventArgs e) { await ToggleRecordStop(); } private async void CreateGraphButton_Click(object sender, RoutedEventArgs e) { await CreateAudioGraph(); } private async Task SelectOutputFile() { FileSavePicker saveFilePicker = new FileSavePicker(); saveFilePicker.FileTypeChoices.Add("Pulse Code Modulation", new List<string>() { ".wav" }); saveFilePicker.FileTypeChoices.Add("Windows Media Audio", new List<string>() { ".wma" }); saveFilePicker.FileTypeChoices.Add("MPEG Audio Layer-3", new List<string>() { ".mp3" }); saveFilePicker.SuggestedFileName = "New Audio Track"; StorageFile file = await saveFilePicker.PickSaveFileAsync(); // File can be null if cancel is hit in the file picker if (file == null) { return; } rootPage.NotifyUser(String.Format("Recording to {0}", file.Name.ToString()), NotifyType.StatusMessage); MediaEncodingProfile fileProfile = CreateMediaEncodingProfile(file); // Operate node at the graph format, but save file at the specified format CreateAudioFileOutputNodeResult fileOutputNodeResult = await graph.CreateFileOutputNodeAsync(file, fileProfile); if (fileOutputNodeResult.Status != AudioFileNodeCreationStatus.Success) { // FileOutputNode creation failed rootPage.NotifyUser(String.Format("Cannot create output file because {0}", fileOutputNodeResult.Status.ToString()), NotifyType.ErrorMessage); fileButton.Background = new SolidColorBrush(Colors.Red); return; } fileOutputNode = fileOutputNodeResult.FileOutputNode; fileButton.Background = new SolidColorBrush(Colors.YellowGreen); // Connect the input node to both output nodes deviceInputNode.AddOutgoingConnection(fileOutputNode); deviceInputNode.AddOutgoingConnection(deviceOutputNode); recordStopButton.IsEnabled = true; } private MediaEncodingProfile CreateMediaEncodingProfile(StorageFile file) { switch(file.FileType.ToString().ToLowerInvariant()) { case ".wma": return MediaEncodingProfile.CreateWma(AudioEncodingQuality.High); case ".mp3": return MediaEncodingProfile.CreateMp3(AudioEncodingQuality.High); case ".wav": return MediaEncodingProfile.CreateWav(AudioEncodingQuality.High); default: throw new ArgumentException(); } } private async Task ToggleRecordStop() { if (recordStopButton.Content.Equals("Record")) { graph.Start(); recordStopButton.Content = "Stop"; audioPipe1.Fill = new SolidColorBrush(Colors.Blue); audioPipe2.Fill = new SolidColorBrush(Colors.Blue); } else if (recordStopButton.Content.Equals("Stop")) { // Good idea to stop the graph to avoid data loss graph.Stop(); audioPipe1.Fill = new SolidColorBrush(Color.FromArgb(255, 49, 49, 49)); audioPipe2.Fill = new SolidColorBrush(Color.FromArgb(255, 49, 49, 49)); TranscodeFailureReason finalizeResult = await fileOutputNode.FinalizeAsync(); if (finalizeResult != TranscodeFailureReason.None) { // Finalization of file failed. Check result code to see why rootPage.NotifyUser(String.Format("Finalization of file failed because {0}", finalizeResult.ToString()), NotifyType.ErrorMessage); fileButton.Background = new SolidColorBrush(Colors.Red); return; } recordStopButton.Content = "Record"; rootPage.NotifyUser("Recording to file completed successfully!", NotifyType.StatusMessage); fileButton.Background = new SolidColorBrush(Colors.Green); recordStopButton.IsEnabled = false; createGraphButton.IsEnabled = false; } } private async Task PopulateOutputDeviceList() { outputDevicesListBox.Items.Clear(); outputDevices = await DeviceInformation.FindAllAsync(MediaDevice.GetAudioRenderSelector()); outputDevicesListBox.Items.Add("-- Pick output device --"); foreach (var device in outputDevices) { outputDevicesListBox.Items.Add(device.Name); } } private async Task PopulateInputDeviceList() { inputDevicesListBox.Items.Clear(); inputDevices = await DeviceInformation.FindAllAsync(MediaDevice.GetAudioCaptureSelector()); inputDevicesListBox.Items.Add("-- Pick input device --"); foreach (var device in inputDevices) { inputDevicesListBox.Items.Add(device.Name); } } private async Task CreateAudioGraph() { AudioGraphSettings settings = new AudioGraphSettings(AudioRenderCategory.Media); settings.QuantumSizeSelectionMode = QuantumSizeSelectionMode.LowestLatency; settings.PrimaryRenderDevice = outputDevices[outputDevicesListBox.SelectedIndex - 1]; CreateAudioGraphResult result = await AudioGraph.CreateAsync(settings); if (result.Status != AudioGraphCreationStatus.Success) { // Cannot create graph rootPage.NotifyUser(String.Format("AudioGraph Creation Error because {0}", result.Status.ToString()), NotifyType.ErrorMessage); return; } graph = result.Graph; rootPage.NotifyUser("Graph successfully created!", NotifyType.StatusMessage); // Create a device output node CreateAudioDeviceOutputNodeResult deviceOutputNodeResult = await graph.CreateDeviceOutputNodeAsync(); if (deviceOutputNodeResult.Status != AudioDeviceNodeCreationStatus.Success) { // Cannot create device output node rootPage.NotifyUser(String.Format("Audio Device Output unavailable because {0}", deviceOutputNodeResult.Status.ToString()), NotifyType.ErrorMessage); outputDeviceContainer.Background = new SolidColorBrush(Colors.Red); return; } deviceOutputNode = deviceOutputNodeResult.DeviceOutputNode; rootPage.NotifyUser("Device Output connection successfully created", NotifyType.StatusMessage); outputDeviceContainer.Background = new SolidColorBrush(Colors.Green); // Create a device input node using the default audio input device CreateAudioDeviceInputNodeResult deviceInputNodeResult = await graph.CreateDeviceInputNodeAsync(MediaCategory.Other, graph.EncodingProperties, inputDevices[inputDevicesListBox.SelectedIndex - 1]); if (deviceInputNodeResult.Status != AudioDeviceNodeCreationStatus.Success) { // Cannot create device input node rootPage.NotifyUser(String.Format("Audio Device Input unavailable because {0}", deviceInputNodeResult.Status.ToString()), NotifyType.ErrorMessage); inputDeviceContainer.Background = new SolidColorBrush(Colors.Red); return; } deviceInputNode = deviceInputNodeResult.DeviceInputNode; rootPage.NotifyUser("Device Input connection successfully created", NotifyType.StatusMessage); inputDeviceContainer.Background = new SolidColorBrush(Colors.Green); // Since graph is successfully created, enable the button to select a file output fileButton.IsEnabled = true; // Disable the graph button to prevent accidental click createGraphButton.IsEnabled = false; // Because we are using lowest latency setting, we need to handle device disconnection errors graph.UnrecoverableErrorOccurred += Graph_UnrecoverableErrorOccurred; } private async void Graph_UnrecoverableErrorOccurred(AudioGraph sender, AudioGraphUnrecoverableErrorOccurredEventArgs args) { // Recreate the graph and all nodes when this happens await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () => { sender.Dispose(); // Re-query for devices await PopulateOutputDeviceList(); await PopulateInputDeviceList(); // Reset UI fileButton.IsEnabled = false; recordStopButton.IsEnabled = false; recordStopButton.Content = "Record"; outputDeviceContainer.Background = new SolidColorBrush(Color.FromArgb(255, 74, 74, 74)); audioPipe1.Fill = new SolidColorBrush(Color.FromArgb(255, 49, 49, 49)); audioPipe2.Fill = new SolidColorBrush(Color.FromArgb(255, 49, 49, 49)); }); } private void outputDevicesListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (outputDevicesListBox.SelectedIndex == 0) { createGraphButton.IsEnabled = false; outputDevice.Foreground = new SolidColorBrush(Color.FromArgb(255, 110, 110, 110)); outputDeviceContainer.Background = new SolidColorBrush(Color.FromArgb(255, 74, 74, 74)); fileButton.IsEnabled = false; fileButton.Background = new SolidColorBrush(Color.FromArgb(255, 74, 74, 74)); inputDeviceContainer.Background = new SolidColorBrush(Color.FromArgb(255, 74, 74, 74)); // Destroy graph if (graph != null) { graph.Dispose(); graph = null; } } else { createGraphButton.IsEnabled = true; outputDevice.Foreground = new SolidColorBrush(Colors.White); } } private void inputDevicesListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (inputDevicesListBox.SelectedIndex == 0) { createGraphButton.IsEnabled = false; fileButton.IsEnabled = false; fileButton.Background = new SolidColorBrush(Color.FromArgb(255, 74, 74, 74)); inputDeviceContainer.Background = new SolidColorBrush(Color.FromArgb(255, 74, 74, 74)); // Destroy graph if (graph != null) { graph.Dispose(); graph = null; } } else { createGraphButton.IsEnabled = true; } } } }
namespace MuteFm.UiPackage { partial class PlayerForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PlayerForm)); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.alwaysOnTopToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem4 = new System.Windows.Forms.ToolStripSeparator(); this.runOnStartupToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.playMusicOnStartupToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem7 = new System.Windows.Forms.ToolStripSeparator(); this.timeoutsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.hotkeysToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.notificationsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.growlToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.systrayBalloonsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.noneToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem9 = new System.Windows.Forms.ToolStripSeparator(); this.notifyWhenNoMusicToPlayToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.notifyAboutProgramUpdatesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem6 = new System.Windows.Forms.ToolStripSeparator(); this.mResetSettingsMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.reloadIconsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator(); this.exitToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.documentationToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.gettingStartedToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator(); this.checkForUpdatesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.giveFeedbackToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem5 = new System.Windows.Forms.ToolStripSeparator(); this.showLogToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripSeparator(); this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.panel2 = new System.Windows.Forms.Panel(); this.mBgMusicNameLabel = new System.Windows.Forms.Label(); this.panel1 = new System.Windows.Forms.Panel(); this.mBgMusicToolStrip = new System.Windows.Forms.ToolStrip(); this.mMuteDuringVideosCheckbox = new System.Windows.Forms.CheckBox(); this.mChangeBgMusicButton = new System.Windows.Forms.Button(); this.mBgMusicIcon = new System.Windows.Forms.PictureBox(); this.mFgMusicSoundsGroupBox = new System.Windows.Forms.GroupBox(); this.timer1 = new System.Windows.Forms.Timer(this.components); this.toolStripMenuItem8 = new System.Windows.Forms.ToolStripSeparator(); this.mDonateToolStripButton = new System.Windows.Forms.ToolStripMenuItem(); this.menuStrip1.SuspendLayout(); this.groupBox1.SuspendLayout(); this.panel2.SuspendLayout(); this.panel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.mBgMusicIcon)).BeginInit(); this.SuspendLayout(); // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.optionsToolStripMenuItem, this.helpToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(430, 24); this.menuStrip1.TabIndex = 5; this.menuStrip1.Text = "menuStrip1"; // // optionsToolStripMenuItem // this.optionsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.alwaysOnTopToolStripMenuItem, this.toolStripMenuItem4, this.runOnStartupToolStripMenuItem, this.playMusicOnStartupToolStripMenuItem, this.toolStripMenuItem7, this.timeoutsToolStripMenuItem, this.hotkeysToolStripMenuItem, this.notificationsToolStripMenuItem, this.toolStripMenuItem6, this.mResetSettingsMenuItem, this.reloadIconsToolStripMenuItem, this.toolStripMenuItem2, this.exitToolStripMenuItem1}); this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem"; this.optionsToolStripMenuItem.Size = new System.Drawing.Size(61, 20); this.optionsToolStripMenuItem.Text = "&Options"; // // alwaysOnTopToolStripMenuItem // this.alwaysOnTopToolStripMenuItem.Name = "alwaysOnTopToolStripMenuItem"; this.alwaysOnTopToolStripMenuItem.Size = new System.Drawing.Size(188, 22); this.alwaysOnTopToolStripMenuItem.Text = "Always On Top"; this.alwaysOnTopToolStripMenuItem.Visible = false; this.alwaysOnTopToolStripMenuItem.Click += new System.EventHandler(this.alwaysOnTopToolStripMenuItem_Click); // // toolStripMenuItem4 // this.toolStripMenuItem4.Name = "toolStripMenuItem4"; this.toolStripMenuItem4.Size = new System.Drawing.Size(185, 6); this.toolStripMenuItem4.Visible = false; // // runOnStartupToolStripMenuItem // this.runOnStartupToolStripMenuItem.Name = "runOnStartupToolStripMenuItem"; this.runOnStartupToolStripMenuItem.Size = new System.Drawing.Size(188, 22); this.runOnStartupToolStripMenuItem.Text = "Run on startup"; this.runOnStartupToolStripMenuItem.Click += new System.EventHandler(this.runOnStartupToolStripMenuItem_Click); // // playMusicOnStartupToolStripMenuItem // this.playMusicOnStartupToolStripMenuItem.Name = "playMusicOnStartupToolStripMenuItem"; this.playMusicOnStartupToolStripMenuItem.Size = new System.Drawing.Size(188, 22); this.playMusicOnStartupToolStripMenuItem.Text = "Play music on startup"; this.playMusicOnStartupToolStripMenuItem.Click += new System.EventHandler(this.playMusicOnStartupToolStripMenuItem_Click); // // toolStripMenuItem7 // this.toolStripMenuItem7.Name = "toolStripMenuItem7"; this.toolStripMenuItem7.Size = new System.Drawing.Size(185, 6); // // timeoutsToolStripMenuItem // this.timeoutsToolStripMenuItem.Name = "timeoutsToolStripMenuItem"; this.timeoutsToolStripMenuItem.Size = new System.Drawing.Size(188, 22); this.timeoutsToolStripMenuItem.Text = "&Timeouts..."; this.timeoutsToolStripMenuItem.Click += new System.EventHandler(this.timeoutsToolStripMenuItem_Click); // // hotkeysToolStripMenuItem // this.hotkeysToolStripMenuItem.Name = "hotkeysToolStripMenuItem"; this.hotkeysToolStripMenuItem.Size = new System.Drawing.Size(188, 22); this.hotkeysToolStripMenuItem.Text = "&Hotkeys..."; this.hotkeysToolStripMenuItem.Click += new System.EventHandler(this.hotkeysToolStripMenuItem_Click); // // notificationsToolStripMenuItem // this.notificationsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.growlToolStripMenuItem, this.systrayBalloonsToolStripMenuItem, this.noneToolStripMenuItem, this.toolStripMenuItem9, this.notifyWhenNoMusicToPlayToolStripMenuItem, this.notifyAboutProgramUpdatesToolStripMenuItem}); this.notificationsToolStripMenuItem.Name = "notificationsToolStripMenuItem"; this.notificationsToolStripMenuItem.Size = new System.Drawing.Size(188, 22); this.notificationsToolStripMenuItem.Text = "&Notifications"; // // growlToolStripMenuItem // this.growlToolStripMenuItem.Name = "growlToolStripMenuItem"; this.growlToolStripMenuItem.Size = new System.Drawing.Size(235, 22); this.growlToolStripMenuItem.Text = "Growl"; this.growlToolStripMenuItem.Click += new System.EventHandler(this.growlToolStripMenuItem_Click); // // systrayBalloonsToolStripMenuItem // this.systrayBalloonsToolStripMenuItem.Name = "systrayBalloonsToolStripMenuItem"; this.systrayBalloonsToolStripMenuItem.Size = new System.Drawing.Size(235, 22); this.systrayBalloonsToolStripMenuItem.Text = "Systray balloons"; this.systrayBalloonsToolStripMenuItem.Click += new System.EventHandler(this.systrayBalloonsToolStripMenuItem_Click); // // noneToolStripMenuItem // this.noneToolStripMenuItem.Name = "noneToolStripMenuItem"; this.noneToolStripMenuItem.Size = new System.Drawing.Size(235, 22); this.noneToolStripMenuItem.Text = "None"; this.noneToolStripMenuItem.Click += new System.EventHandler(this.noneToolStripMenuItem_Click); // // toolStripMenuItem9 // this.toolStripMenuItem9.Name = "toolStripMenuItem9"; this.toolStripMenuItem9.Size = new System.Drawing.Size(232, 6); // // notifyWhenNoMusicToPlayToolStripMenuItem // this.notifyWhenNoMusicToPlayToolStripMenuItem.Name = "notifyWhenNoMusicToPlayToolStripMenuItem"; this.notifyWhenNoMusicToPlayToolStripMenuItem.Size = new System.Drawing.Size(235, 22); this.notifyWhenNoMusicToPlayToolStripMenuItem.Text = "Notify when no music to play"; this.notifyWhenNoMusicToPlayToolStripMenuItem.Click += new System.EventHandler(this.notifyWhenNoMusicToPlayToolStripMenuItem_Click); // // notifyAboutProgramUpdatesToolStripMenuItem // this.notifyAboutProgramUpdatesToolStripMenuItem.Name = "notifyAboutProgramUpdatesToolStripMenuItem"; this.notifyAboutProgramUpdatesToolStripMenuItem.Size = new System.Drawing.Size(235, 22); this.notifyAboutProgramUpdatesToolStripMenuItem.Text = "Notify about program updates"; // // toolStripMenuItem6 // this.toolStripMenuItem6.Name = "toolStripMenuItem6"; this.toolStripMenuItem6.Size = new System.Drawing.Size(185, 6); // // mResetSettingsMenuItem // this.mResetSettingsMenuItem.Name = "mResetSettingsMenuItem"; this.mResetSettingsMenuItem.Size = new System.Drawing.Size(188, 22); this.mResetSettingsMenuItem.Text = "Reset Settings..."; this.mResetSettingsMenuItem.Click += new System.EventHandler(this.mResetSettingsMenuItem_Click); // // reloadIconsToolStripMenuItem // this.reloadIconsToolStripMenuItem.Name = "reloadIconsToolStripMenuItem"; this.reloadIconsToolStripMenuItem.Size = new System.Drawing.Size(188, 22); this.reloadIconsToolStripMenuItem.Text = "Reload Icons..."; this.reloadIconsToolStripMenuItem.Click += new System.EventHandler(this.reloadIconsToolStripMenuItem_Click); // // toolStripMenuItem2 // this.toolStripMenuItem2.Name = "toolStripMenuItem2"; this.toolStripMenuItem2.Size = new System.Drawing.Size(185, 6); // // exitToolStripMenuItem1 // this.exitToolStripMenuItem1.Name = "exitToolStripMenuItem1"; this.exitToolStripMenuItem1.Size = new System.Drawing.Size(188, 22); this.exitToolStripMenuItem1.Text = "E&xit"; this.exitToolStripMenuItem1.Click += new System.EventHandler(this.exitToolStripMenuItem1_Click); // // helpToolStripMenuItem // this.helpToolStripMenuItem.Checked = true; this.helpToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked; this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.documentationToolStripMenuItem, this.gettingStartedToolStripMenuItem, this.toolStripMenuItem1, this.checkForUpdatesToolStripMenuItem, this.giveFeedbackToolStripMenuItem, this.toolStripMenuItem5, this.showLogToolStripMenuItem1, this.toolStripMenuItem3, this.mDonateToolStripButton, this.toolStripMenuItem8, this.aboutToolStripMenuItem}); this.helpToolStripMenuItem.Name = "helpToolStripMenuItem"; this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 20); this.helpToolStripMenuItem.Text = "&Help"; // // documentationToolStripMenuItem // this.documentationToolStripMenuItem.Name = "documentationToolStripMenuItem"; this.documentationToolStripMenuItem.Size = new System.Drawing.Size(171, 22); this.documentationToolStripMenuItem.Text = "Documentation"; this.documentationToolStripMenuItem.Click += new System.EventHandler(this.documentationMenuItem_Click); // // gettingStartedToolStripMenuItem // this.gettingStartedToolStripMenuItem.Name = "gettingStartedToolStripMenuItem"; this.gettingStartedToolStripMenuItem.Size = new System.Drawing.Size(171, 22); this.gettingStartedToolStripMenuItem.Text = "Getting Started"; this.gettingStartedToolStripMenuItem.Click += new System.EventHandler(this.gettingStartedToolStripMenuItem_Click); // // toolStripMenuItem1 // this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(168, 6); // // checkForUpdatesToolStripMenuItem // this.checkForUpdatesToolStripMenuItem.Name = "checkForUpdatesToolStripMenuItem"; this.checkForUpdatesToolStripMenuItem.Size = new System.Drawing.Size(171, 22); this.checkForUpdatesToolStripMenuItem.Text = "Check for Updates"; this.checkForUpdatesToolStripMenuItem.Click += new System.EventHandler(this.checkForUpdatesToolStripMenuItem_Click); // // giveFeedbackToolStripMenuItem // this.giveFeedbackToolStripMenuItem.Name = "giveFeedbackToolStripMenuItem"; this.giveFeedbackToolStripMenuItem.Size = new System.Drawing.Size(171, 22); this.giveFeedbackToolStripMenuItem.Text = "Give Feedback"; this.giveFeedbackToolStripMenuItem.Visible = false; this.giveFeedbackToolStripMenuItem.Click += new System.EventHandler(this.giveFeedbackToolStripMenuItem_Click); // // toolStripMenuItem5 // this.toolStripMenuItem5.Name = "toolStripMenuItem5"; this.toolStripMenuItem5.Size = new System.Drawing.Size(168, 6); // // showLogToolStripMenuItem1 // this.showLogToolStripMenuItem1.Name = "showLogToolStripMenuItem1"; this.showLogToolStripMenuItem1.Size = new System.Drawing.Size(171, 22); this.showLogToolStripMenuItem1.Text = "Show &Log"; this.showLogToolStripMenuItem1.Click += new System.EventHandler(this.showLogToolStripMenuItem1_Click); // // toolStripMenuItem3 // this.toolStripMenuItem3.Name = "toolStripMenuItem3"; this.toolStripMenuItem3.Size = new System.Drawing.Size(168, 6); // // aboutToolStripMenuItem // this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem"; this.aboutToolStripMenuItem.Size = new System.Drawing.Size(171, 22); this.aboutToolStripMenuItem.Text = "About mute.fm"; this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click); // // groupBox1 // this.groupBox1.Controls.Add(this.panel2); this.groupBox1.Controls.Add(this.panel1); this.groupBox1.Controls.Add(this.mMuteDuringVideosCheckbox); this.groupBox1.Controls.Add(this.mChangeBgMusicButton); this.groupBox1.Controls.Add(this.mBgMusicIcon); this.groupBox1.Dock = System.Windows.Forms.DockStyle.Top; this.groupBox1.Location = new System.Drawing.Point(0, 24); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(430, 107); this.groupBox1.TabIndex = 6; this.groupBox1.TabStop = false; this.groupBox1.Text = "Background music"; // // panel2 // this.panel2.Controls.Add(this.mBgMusicNameLabel); this.panel2.Location = new System.Drawing.Point(83, 23); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(238, 27); this.panel2.TabIndex = 10; // // mBgMusicNameLabel // this.mBgMusicNameLabel.AutoSize = true; this.mBgMusicNameLabel.Location = new System.Drawing.Point(3, 10); this.mBgMusicNameLabel.Name = "mBgMusicNameLabel"; this.mBgMusicNameLabel.Size = new System.Drawing.Size(39, 13); this.mBgMusicNameLabel.TabIndex = 2; this.mBgMusicNameLabel.Text = "[name]"; // // panel1 // this.panel1.Controls.Add(this.mBgMusicToolStrip); this.panel1.Location = new System.Drawing.Point(86, 48); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(200, 25); this.panel1.TabIndex = 7; // // mBgMusicToolStrip // this.mBgMusicToolStrip.BackColor = System.Drawing.Color.Transparent; this.mBgMusicToolStrip.CanOverflow = false; this.mBgMusicToolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.mBgMusicToolStrip.Location = new System.Drawing.Point(0, 0); this.mBgMusicToolStrip.Name = "mBgMusicToolStrip"; this.mBgMusicToolStrip.RenderMode = System.Windows.Forms.ToolStripRenderMode.Professional; this.mBgMusicToolStrip.Size = new System.Drawing.Size(200, 25); this.mBgMusicToolStrip.TabIndex = 7; this.mBgMusicToolStrip.Text = "toolStrip1"; // // mMuteDuringVideosCheckbox // this.mMuteDuringVideosCheckbox.AutoSize = true; this.mMuteDuringVideosCheckbox.Location = new System.Drawing.Point(86, 82); this.mMuteDuringVideosCheckbox.Name = "mMuteDuringVideosCheckbox"; this.mMuteDuringVideosCheckbox.Size = new System.Drawing.Size(116, 17); this.mMuteDuringVideosCheckbox.TabIndex = 3; this.mMuteDuringVideosCheckbox.Text = "Mute during videos"; this.mMuteDuringVideosCheckbox.UseVisualStyleBackColor = true; this.mMuteDuringVideosCheckbox.CheckedChanged += new System.EventHandler(this.mMuteDuringVideosCheckbox_CheckedChanged); // // mChangeBgMusicButton // this.mChangeBgMusicButton.Location = new System.Drawing.Point(334, 23); this.mChangeBgMusicButton.Name = "mChangeBgMusicButton"; this.mChangeBgMusicButton.Size = new System.Drawing.Size(75, 23); this.mChangeBgMusicButton.TabIndex = 9; this.mChangeBgMusicButton.Text = "Change..."; this.mChangeBgMusicButton.Click += new System.EventHandler(this.mChangeBgMusicButton_Click); // // mBgMusicIcon // this.mBgMusicIcon.Cursor = System.Windows.Forms.Cursors.Hand; this.mBgMusicIcon.Location = new System.Drawing.Point(45, 28); this.mBgMusicIcon.Name = "mBgMusicIcon"; this.mBgMusicIcon.Size = new System.Drawing.Size(32, 32); this.mBgMusicIcon.TabIndex = 0; this.mBgMusicIcon.TabStop = false; this.mBgMusicIcon.Click += new System.EventHandler(this.mBgMusicIcon_Click); // // mFgMusicSoundsGroupBox // this.mFgMusicSoundsGroupBox.Dock = System.Windows.Forms.DockStyle.Fill; this.mFgMusicSoundsGroupBox.Location = new System.Drawing.Point(0, 131); this.mFgMusicSoundsGroupBox.Name = "mFgMusicSoundsGroupBox"; this.mFgMusicSoundsGroupBox.Size = new System.Drawing.Size(430, 133); this.mFgMusicSoundsGroupBox.TabIndex = 7; this.mFgMusicSoundsGroupBox.TabStop = false; this.mFgMusicSoundsGroupBox.Text = "Active foreground sounds"; // // timer1 // this.timer1.Enabled = true; this.timer1.Interval = 500; this.timer1.Tick += new System.EventHandler(this.timer1_Tick); // // toolStripMenuItem8 // this.toolStripMenuItem8.Name = "toolStripMenuItem8"; this.toolStripMenuItem8.Size = new System.Drawing.Size(168, 6); // // mDonateToolStripButton // this.mDonateToolStripButton.Name = "mDonateToolStripButton"; this.mDonateToolStripButton.Size = new System.Drawing.Size(171, 22); this.mDonateToolStripButton.Text = "Donate"; this.mDonateToolStripButton.Click += new System.EventHandler(this.mDonateToolStripButton_Click); // // PlayerForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Control; this.ClientSize = new System.Drawing.Size(430, 264); this.Controls.Add(this.mFgMusicSoundsGroupBox); this.Controls.Add(this.groupBox1); this.Controls.Add(this.menuStrip1); this.DoubleBuffered = true; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Location = new System.Drawing.Point(9999, 9999); this.MainMenuStrip = this.menuStrip1; this.MaximizeBox = false; this.Name = "PlayerForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Activated += new System.EventHandler(this.PlayerForm_Activated); this.Deactivate += new System.EventHandler(this.PlayerForm_Deactivate); this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.PlayerForm_FormClosing); this.Load += new System.EventHandler(this.PlayerForm_Load); this.Shown += new System.EventHandler(this.PlayerForm_Shown); this.SizeChanged += new System.EventHandler(this.PlayerForm_SizeChanged); this.Resize += new System.EventHandler(this.PlayerForm_Resize); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.panel2.ResumeLayout(false); this.panel2.PerformLayout(); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.mBgMusicIcon)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem alwaysOnTopToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem documentationToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem gettingStartedToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem checkForUpdatesToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem giveFeedbackToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem3; private System.Windows.Forms.ToolStripMenuItem mResetSettingsMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem4; private System.Windows.Forms.ToolStripMenuItem optionsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem runOnStartupToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem playMusicOnStartupToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem5; private System.Windows.Forms.ToolStripMenuItem showLogToolStripMenuItem1; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.CheckBox mMuteDuringVideosCheckbox; private System.Windows.Forms.Button mChangeBgMusicButton; private System.Windows.Forms.PictureBox mBgMusicIcon; private System.Windows.Forms.GroupBox mFgMusicSoundsGroupBox; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.ToolStrip mBgMusicToolStrip; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem6; private System.Windows.Forms.ToolStripMenuItem timeoutsToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem7; private System.Windows.Forms.ToolStripMenuItem reloadIconsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem hotkeysToolStripMenuItem; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.Label mBgMusicNameLabel; private System.Windows.Forms.Timer timer1; private System.Windows.Forms.ToolStripMenuItem notificationsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem growlToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem systrayBalloonsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem noneToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem9; private System.Windows.Forms.ToolStripMenuItem notifyWhenNoMusicToPlayToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem notifyAboutProgramUpdatesToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem mDonateToolStripButton; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem8; } }
// // This file is part of the game Voxalia, created by FreneticXYZ. // This code is Copyright (C) 2016 FreneticXYZ under the terms of the MIT license. // See README.md or LICENSE.txt for contents of the MIT license. // If these are not available, see https://opensource.org/licenses/MIT // using System.Collections.Generic; using BEPUutilities; namespace Voxalia.Shared.BlockShapes { public class BSD26_30: BlockShapeDetails { public double Percent; public BSD26_30(double perc) { Percent = 1 - perc; } public override List<Vector3> GetVertices(Vector3 pos, bool XP, bool XM, bool YP, bool YM, bool TOP, bool BOTTOM) { List<Vector3> Vertices = new List<Vector3>(); if (!TOP) { Vertices.Add(new Vector3(pos.X, pos.Y + 1, pos.Z + 1)); Vertices.Add(new Vector3(pos.X + 1, pos.Y + 1, pos.Z + 1)); Vertices.Add(new Vector3(pos.X, pos.Y + Percent, pos.Z + 1)); Vertices.Add(new Vector3(pos.X + 1, pos.Y + 1, pos.Z + 1)); Vertices.Add(new Vector3(pos.X + 1, pos.Y + Percent, pos.Z + 1)); Vertices.Add(new Vector3(pos.X, pos.Y + Percent, pos.Z + 1)); } if (!BOTTOM) { Vertices.Add(new Vector3(pos.X, pos.Y + Percent, pos.Z + 1)); Vertices.Add(new Vector3(pos.X + 1, pos.Y + 1, pos.Z)); Vertices.Add(new Vector3(pos.X, pos.Y + 1, pos.Z)); Vertices.Add(new Vector3(pos.X, pos.Y + Percent, pos.Z)); Vertices.Add(new Vector3(pos.X + 1, pos.Y + Percent, pos.Z)); Vertices.Add(new Vector3(pos.X + 1, pos.Y + 1, pos.Z)); } if (!XP) { Vertices.Add(new Vector3(pos.X + 1, pos.Y + 1, pos.Z + 1)); Vertices.Add(new Vector3(pos.X + 1, pos.Y + 1, pos.Z)); Vertices.Add(new Vector3(pos.X + 1, pos.Y + Percent, pos.Z)); Vertices.Add(new Vector3(pos.X + 1, pos.Y + Percent, pos.Z + 1)); Vertices.Add(new Vector3(pos.X + 1, pos.Y + 1, pos.Z + 1)); Vertices.Add(new Vector3(pos.X + 1, pos.Y + Percent, pos.Z)); } if (!XM) { Vertices.Add(new Vector3(pos.X, pos.Y + Percent, pos.Z)); Vertices.Add(new Vector3(pos.X, pos.Y + 1, pos.Z)); Vertices.Add(new Vector3(pos.X, pos.Y + 1, pos.Z + 1)); Vertices.Add(new Vector3(pos.X, pos.Y + Percent, pos.Z)); Vertices.Add(new Vector3(pos.X, pos.Y + 1, pos.Z + 1)); Vertices.Add(new Vector3(pos.X, pos.Y + Percent, pos.Z + 1)); } if (!YP) { Vertices.Add(new Vector3(pos.X, pos.Y + 1, pos.Z)); Vertices.Add(new Vector3(pos.X + 1, pos.Y + 1, pos.Z)); Vertices.Add(new Vector3(pos.X + 1, pos.Y + 1, pos.Z + 1)); Vertices.Add(new Vector3(pos.X, pos.Y + 1, pos.Z)); Vertices.Add(new Vector3(pos.X + 1, pos.Y + 1, pos.Z + 1)); Vertices.Add(new Vector3(pos.X, pos.Y + 1, pos.Z + 1)); } Vertices.Add(new Vector3(pos.X + 1, pos.Y + Percent, pos.Z + 1)); Vertices.Add(new Vector3(pos.X + 1, pos.Y + Percent, pos.Z)); Vertices.Add(new Vector3(pos.X, pos.Y + Percent, pos.Z)); Vertices.Add(new Vector3(pos.X, pos.Y + Percent, pos.Z + 1)); Vertices.Add(new Vector3(pos.X + 1, pos.Y + Percent, pos.Z + 1)); Vertices.Add(new Vector3(pos.X, pos.Y + Percent, pos.Z)); return Vertices; } public override List<BEPUutilities.Vector3> GetNormals(Vector3 blockPos, bool XP, bool XM, bool YP, bool YM, bool TOP, bool BOTTOM) { List<Vector3> Norms = new List<Vector3>(); if (!TOP) { for (int i = 0; i < 6; i++) { Norms.Add(new Vector3(0, 0, 1)); } } if (!BOTTOM) { for (int i = 0; i < 6; i++) { Norms.Add(new Vector3(0, 0, -1)); } } if (!XP) { for (int i = 0; i < 6; i++) { Norms.Add(new Vector3(1, 0, 0)); } } if (!XM) { for (int i = 0; i < 6; i++) { Norms.Add(new Vector3(-1, 0, 0)); } } if (!YP) { for (int i = 0; i < 6; i++) { Norms.Add(new Vector3(0, 1, 0)); } } for (int i = 0; i < 6; i++) { Norms.Add(new Vector3(0, -1, 0)); } return Norms; } public override List<Vector3> GetTCoords(Vector3 blockPos, Material mat, bool XP, bool XM, bool YP, bool YM, bool TOP, bool BOTTOM) { List<Vector3> TCoords = new List<Vector3>(); int tID_TOP = mat.TextureID(MaterialSide.TOP); if (!TOP) { TCoords.Add(new Vector3(0, 1, tID_TOP)); TCoords.Add(new Vector3(1, 1, tID_TOP)); TCoords.Add(new Vector3(0, 0, tID_TOP)); TCoords.Add(new Vector3(1, 1, tID_TOP)); TCoords.Add(new Vector3(1, 0, tID_TOP)); TCoords.Add(new Vector3(0, 0, tID_TOP)); } if (!BOTTOM) { int tID_BOTTOM = mat.TextureID(MaterialSide.BOTTOM); TCoords.Add(new Vector3(0, 0, tID_BOTTOM)); TCoords.Add(new Vector3(1, 1, tID_BOTTOM)); TCoords.Add(new Vector3(0, 1, tID_BOTTOM)); TCoords.Add(new Vector3(0, 0, tID_BOTTOM)); TCoords.Add(new Vector3(1, 0, tID_BOTTOM)); TCoords.Add(new Vector3(1, 1, tID_BOTTOM)); } if (!XP) { int tID_XP = mat.TextureID(MaterialSide.XP); TCoords.Add(new Vector3(1, 0, tID_XP)); TCoords.Add(new Vector3(1, 1, tID_XP)); TCoords.Add(new Vector3(0, 1, tID_XP)); TCoords.Add(new Vector3(0, 0, tID_XP)); TCoords.Add(new Vector3(1, 0, tID_XP)); TCoords.Add(new Vector3(0, 1, tID_XP)); } if (!XM) { int tID_XM = mat.TextureID(MaterialSide.XM); TCoords.Add(new Vector3(1, 1, tID_XM)); TCoords.Add(new Vector3(0, 1, tID_XM)); TCoords.Add(new Vector3(0, 0, tID_XM)); TCoords.Add(new Vector3(1, 1, tID_XM)); TCoords.Add(new Vector3(0, 0, tID_XM)); TCoords.Add(new Vector3(1, 0, tID_XM)); } if (!YP) { int tID_YP = mat.TextureID(MaterialSide.YP); TCoords.Add(new Vector3(1, 1, tID_YP)); TCoords.Add(new Vector3(0, 1, tID_YP)); TCoords.Add(new Vector3(0, 0, tID_YP)); TCoords.Add(new Vector3(1, 1, tID_YP)); TCoords.Add(new Vector3(0, 0, tID_YP)); TCoords.Add(new Vector3(1, 0, tID_YP)); } int tID_YM = mat.TextureID(MaterialSide.YM); TCoords.Add(new Vector3(1, 0, tID_YM)); TCoords.Add(new Vector3(1, 1, tID_YM)); TCoords.Add(new Vector3(0, 1, tID_YM)); TCoords.Add(new Vector3(0, 0, tID_YM)); TCoords.Add(new Vector3(1, 0, tID_YM)); TCoords.Add(new Vector3(0, 1, tID_YM)); return TCoords; } public override bool OccupiesXP() { return false; } public override bool OccupiesYP() { return true; } public override bool OccupiesXM() { return false; } public override bool OccupiesYM() { return false; } public override bool OccupiesTOP() { return false; } public override bool OccupiesBOTTOM() { return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Reflection; using Xunit; namespace System.Globalization.Tests { public class StringInfoMiscTests { [Fact] public void Ctor_Default() { StringInfo stringInfo = new StringInfo(); Assert.Equal(string.Empty, stringInfo.String); Assert.Equal(0, stringInfo.LengthInTextElements); } public static IEnumerable<object[]> Ctor_String_TestData() { yield return new object[] { new string('a', 256), 256 }; yield return new object[] { "\u4f00\u302a\ud800\udc00\u4f01", 3 }; yield return new object[] { "abcdefgh", 8 }; yield return new object[] { "zj\uDBFF\uDFFFlk", 5 }; yield return new object[] { "!@#$%^&", 7 }; yield return new object[] { "!\u20D1bo\uFE22\u20D1\u20EB|", 4 }; yield return new object[] { "1\uDBFF\uDFFF@\uFE22\u20D1\u20EB9", 4 }; yield return new object[] { "a\u0300", 1 }; yield return new object[] { " ", 3 }; yield return new object[] { "", 0 }; } [Theory] [MemberData(nameof(Ctor_String_TestData))] public void Ctor_String(string value, int lengthInTextElements) { var stringInfo = new StringInfo(value); Assert.Same(value, stringInfo.String); Assert.Equal(lengthInTextElements, stringInfo.LengthInTextElements); } [Fact] public void Ctor_NullValue_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("value", "String", () => new StringInfo(null)); } [Theory] [InlineData("")] [InlineData("abc")] [InlineData("\uD800\uDC00")] public void String_Set_GetReturnsExpected(string value) { StringInfo stringInfo = new StringInfo(); stringInfo.String = value; Assert.Same(value, stringInfo.String); } [Fact] public void String_SetNull_ThrowsArgumentNullException() { var stringInfo = new StringInfo(); AssertExtensions.Throws<ArgumentNullException>("value", "String", () => stringInfo.String = null); } public static IEnumerable<object[]> StringInfo_TestData() { yield return new object[] { "Simple Text", 7, "Text", 4, "Text" }; yield return new object[] { "Simple Text", 0, "Simple Text", 6, "Simple" }; yield return new object[] { "\uD800\uDC00\uD801\uDC01Left", 2, "Left", 2, "Le" }; yield return new object[] { "\uD800\uDC00\uD801\uDC01Left", 1, "\uD801\uDC01Left", 2, "\uD801\uDC01L" }; yield return new object[] { "Start\uD800\uDC00\uD801\uDC01Left", 5, "\uD800\uDC00\uD801\uDC01Left", 1, "\uD800\uDC00" }; } [Theory] [MemberData(nameof(StringInfo_TestData))] public void SubstringTest(string source, int index, string expected, int length, string expectedWithLength) { StringInfo si = new StringInfo(source); Assert.Equal(expected, si.SubstringByTextElements(index)); Assert.Equal(expectedWithLength, si.SubstringByTextElements(index, length)); } [Fact] public void NegativeTest() { string s = "Some String"; StringInfo si = new StringInfo(s); StringInfo siEmpty = new StringInfo(""); Assert.Throws<ArgumentOutOfRangeException>(() => si.SubstringByTextElements(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => si.SubstringByTextElements(s.Length + 1)); Assert.Throws<ArgumentOutOfRangeException>(() => siEmpty.SubstringByTextElements(0)); Assert.Throws<ArgumentOutOfRangeException>(() => si.SubstringByTextElements(-1, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => si.SubstringByTextElements(s.Length + 1, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => siEmpty.SubstringByTextElements(0, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => si.SubstringByTextElements(0, s.Length + 1)); } public static IEnumerable<object[]> Equals_TestData() { yield return new object[] { new StringInfo(), new StringInfo(), true }; yield return new object[] { new StringInfo("stringinfo1"), new StringInfo("stringinfo1"), true }; yield return new object[] { new StringInfo("stringinfo1"), new StringInfo("stringinfo2"), false }; yield return new object[] { new StringInfo("stringinfo1"), "stringinfo1", false }; yield return new object[] { new StringInfo("stringinfo1"), 123, false }; yield return new object[] { new StringInfo("stringinfo1"), null, false }; } [Theory] [MemberData(nameof(Equals_TestData))] public void Equals(StringInfo stringInfo, object value, bool expected) { Assert.Equal(expected, stringInfo.Equals(value)); if (value is StringInfo) { Assert.Equal(expected, stringInfo.GetHashCode().Equals(value.GetHashCode())); } } public static IEnumerable<object[]> GetNextTextElement_TestData() { yield return new object[] { "", 0, "" }; // Empty string yield return new object[] { "Hello", 5, "" }; // Index = string.Length // Surrogate pair yield return new object[] { "\uDBFF\uDFFFabcde", 0, "\uDBFF\uDFFF" }; yield return new object[] { "ef45-;\uDBFF\uDFFFabcde", 6, "\uDBFF\uDFFF" }; yield return new object[] { "a\u20D1abcde", 0, "a\u20D1" }; // Combining character or non spacing mark // Base character with several combining characters yield return new object[] { "z\uFE22\u20D1\u20EBabcde", 0, "z\uFE22\u20D1\u20EB" }; yield return new object[] { "az\uFE22\u20D1\u20EBabcde", 1, "z\uFE22\u20D1\u20EB" }; yield return new object[] { "13229^a\u20D1abcde", 6, "a\u20D1" }; // Combining characters // Single base and combining character yield return new object[] { "a\u0300", 0, "a\u0300" }; yield return new object[] { "a\u0300", 1, "\u0300" }; // Lone combining character yield return new object[] { "\u0300\u0300", 0, "\u0300" }; yield return new object[] { "\u0300\u0300", 1, "\u0300" }; } [Theory] [MemberData(nameof(GetNextTextElement_TestData))] public void GetNextTextElement(string str, int index, string expected) { if (index == 0) { Assert.Equal(expected, StringInfo.GetNextTextElement(str)); } Assert.Equal(expected, StringInfo.GetNextTextElement(str, index)); } [Fact] public void GetNextTextElement_Invalid() { AssertExtensions.Throws<ArgumentNullException>("str", () => StringInfo.GetNextTextElement(null)); // Str is null AssertExtensions.Throws<ArgumentNullException>("str", () => StringInfo.GetNextTextElement(null, 0)); // Str is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => StringInfo.GetNextTextElement("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => StringInfo.GetNextTextElement("abc", 4)); // Index > str.Length } public static IEnumerable<object[]> GetTextElementEnumerator_TestData() { yield return new object[] { "", 0, new string[0] }; // Empty string yield return new object[] { "Hello", 5, new string[0] }; // Index = string.Length // Surrogate pair yield return new object[] { "s\uDBFF\uDFFF$", 0, new string[] { "s", "\uDBFF\uDFFF", "$" } }; yield return new object[] { "s\uDBFF\uDFFF$", 1, new string[] { "\uDBFF\uDFFF", "$" } }; // Combining characters yield return new object[] { "13229^a\u20D1a", 6, new string[] { "a\u20D1", "a" } }; yield return new object[] { "13229^a\u20D1a", 0, new string[] { "1", "3", "2", "2", "9", "^", "a\u20D1", "a" } }; // Single base and combining character yield return new object[] { "a\u0300", 0, new string[] { "a\u0300" } }; yield return new object[] { "a\u0300", 1, new string[] { "\u0300" } }; // Lone combining character yield return new object[] { "\u0300\u0300", 0, new string[] { "\u0300", "\u0300" } }; } [Theory] [MemberData(nameof(GetTextElementEnumerator_TestData))] public void GetTextElementEnumerator(string str, int index, string[] expected) { if (index == 0) { TextElementEnumerator basicEnumerator = StringInfo.GetTextElementEnumerator(str); int basicCounter = 0; while (basicEnumerator.MoveNext()) { Assert.Equal(expected[basicCounter], basicEnumerator.Current.ToString()); basicCounter++; } Assert.Equal(expected.Length, basicCounter); } TextElementEnumerator indexedEnumerator = StringInfo.GetTextElementEnumerator(str, index); int indexedCounter = 0; while (indexedEnumerator.MoveNext()) { Assert.Equal(expected[indexedCounter], indexedEnumerator.Current.ToString()); indexedCounter++; } Assert.Equal(expected.Length, indexedCounter); } [Fact] public void GetTextElementEnumerator_Invalid() { AssertExtensions.Throws<ArgumentNullException>("str", () => StringInfo.GetTextElementEnumerator(null)); // Str is null AssertExtensions.Throws<ArgumentNullException>("str", () => StringInfo.GetTextElementEnumerator(null, 0)); // Str is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => StringInfo.GetTextElementEnumerator("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => StringInfo.GetTextElementEnumerator("abc", 4)); // Index > str.Length } public static IEnumerable<object[]> ParseCombiningCharacters_TestData() { yield return new object[] { "\u4f00\u302a\ud800\udc00\u4f01", new int[] { 0, 2, 4 } }; yield return new object[] { "abcdefgh", new int[] { 0, 1, 2, 3, 4, 5, 6, 7 } }; yield return new object[] { "!@#$%^&", new int[] { 0, 1, 2, 3, 4, 5, 6 } }; yield return new object[] { "!\u20D1bo\uFE22\u20D1\u20EB|", new int[] { 0, 2, 3, 7 } }; yield return new object[] { "1\uDBFF\uDFFF@\uFE22\u20D1\u20EB9", new int[] { 0, 1, 3, 7 } }; yield return new object[] { "a\u0300", new int[] { 0 } }; yield return new object[] { "\u0300\u0300", new int[] { 0, 1 } }; yield return new object[] { " ", new int[] { 0, 1, 2 } }; yield return new object[] { "", new int[0] }; // Invalid Unicode yield return new object[] { "\u0000\uFFFFa", new int[] { 0, 1, 2 } }; // Control chars yield return new object[] { "\uD800a", new int[] { 0, 1 } }; // Unmatched high surrogate yield return new object[] { "\uDC00a", new int[] { 0, 1 } }; // Unmatched low surrogate yield return new object[] { "\u00ADa", new int[] { 0, 1 } }; // Format character yield return new object[] { "\u0000\u0300\uFFFF\u0300", new int[] { 0, 1, 2, 3 } }; // Control chars + combining char yield return new object[] { "\uD800\u0300", new int[] { 0, 1 } }; // Unmatched high surrogate + combining char yield return new object[] { "\uDC00\u0300", new int[] { 0, 1 } }; // Unmatched low surrogate + combing char yield return new object[] { "\u00AD\u0300", new int[] { 0, 1 } }; // Format character + combining char yield return new object[] { "\u0300\u0300", new int[] { 0, 1 } }; // Two combining chars } [Theory] [MemberData(nameof(ParseCombiningCharacters_TestData))] public void ParseCombiningCharacters(string str, int[] expected) { Assert.Equal(expected, StringInfo.ParseCombiningCharacters(str)); } [Fact] public void ParseCombiningCharacters_Null_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("str", () => StringInfo.ParseCombiningCharacters(null)); // Str is null } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; using System.Threading.Tasks; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.IO.Tests { public partial class StringWriterTests { static int[] iArrInvalidValues = new int[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, int.MinValue, short.MinValue }; static int[] iArrLargeValues = new int[] { int.MaxValue, int.MaxValue - 1, int.MaxValue / 2, int.MaxValue / 10, int.MaxValue / 100 }; static int[] iArrValidValues = new int[] { 10000, 100000, int.MaxValue / 2000, int.MaxValue / 5000, short.MaxValue }; private static StringBuilder getSb() { var chArr = TestDataProvider.CharData; var sb = new StringBuilder(40); for (int i = 0; i < chArr.Length; i++) sb.Append(chArr[i]); return sb; } [Fact] public static void Ctor() { StringWriter sw = new StringWriter(); Assert.NotNull(sw); } [Fact] public static void CtorWithStringBuilder() { var sb = getSb(); StringWriter sw = new StringWriter(getSb()); Assert.NotNull(sw); Assert.Equal(sb.Length, sw.GetStringBuilder().Length); } [Fact] public static void CtorWithCultureInfo() { StringWriter sw = new StringWriter(new CultureInfo("en-gb")); Assert.NotNull(sw); Assert.Equal(new CultureInfo("en-gb"), sw.FormatProvider); } [Fact] public static void SimpleWriter() { var sw = new StringWriter(); sw.Write(4); var sb = sw.GetStringBuilder(); Assert.Equal("4", sb.ToString()); } [Fact] public static void WriteArray() { var chArr = TestDataProvider.CharData; StringBuilder sb = getSb(); StringWriter sw = new StringWriter(sb); var sr = new StringReader(sw.GetStringBuilder().ToString()); for (int i = 0; i < chArr.Length; i++) { int tmp = sr.Read(); Assert.Equal((int)chArr[i], tmp); } } [Fact] public static void CantWriteNullArray() { var sw = new StringWriter(); Assert.Throws<ArgumentNullException>(() => sw.Write(null, 0, 0)); } [Fact] public static void CantWriteNegativeOffset() { var sw = new StringWriter(); Assert.Throws<ArgumentOutOfRangeException>(() => sw.Write(new char[0], -1, 0)); } [Fact] public static void CantWriteNegativeCount() { var sw = new StringWriter(); Assert.Throws<ArgumentOutOfRangeException>(() => sw.Write(new char[0], 0, -1)); } [Fact] public static void CantWriteIndexLargeValues() { var chArr = TestDataProvider.CharData; for (int i = 0; i < iArrLargeValues.Length; i++) { StringWriter sw = new StringWriter(); AssertExtensions.Throws<ArgumentException>(null, () => sw.Write(chArr, iArrLargeValues[i], chArr.Length)); } } [Fact] public static void CantWriteCountLargeValues() { var chArr = TestDataProvider.CharData; for (int i = 0; i < iArrLargeValues.Length; i++) { StringWriter sw = new StringWriter(); AssertExtensions.Throws<ArgumentException>(null, () => sw.Write(chArr, 0, iArrLargeValues[i])); } } [Fact] public static void WriteWithOffset() { StringWriter sw = new StringWriter(); StringReader sr; var chArr = TestDataProvider.CharData; sw.Write(chArr, 2, 5); sr = new StringReader(sw.ToString()); for (int i = 2; i < 7; i++) { int tmp = sr.Read(); Assert.Equal((int)chArr[i], tmp); } } [Fact] public static void WriteWithLargeIndex() { for (int i = 0; i < iArrValidValues.Length; i++) { StringBuilder sb = new StringBuilder(int.MaxValue / 2000); StringWriter sw = new StringWriter(sb); var chArr = new char[int.MaxValue / 2000]; for (int j = 0; j < chArr.Length; j++) chArr[j] = (char)(j % 256); sw.Write(chArr, iArrValidValues[i] - 1, 1); string strTemp = sw.GetStringBuilder().ToString(); Assert.Equal(1, strTemp.Length); } } [Fact] public static void WriteWithLargeCount() { for (int i = 0; i < iArrValidValues.Length; i++) { StringBuilder sb = new StringBuilder(int.MaxValue / 2000); StringWriter sw = new StringWriter(sb); var chArr = new char[int.MaxValue / 2000]; for (int j = 0; j < chArr.Length; j++) chArr[j] = (char)(j % 256); sw.Write(chArr, 0, iArrValidValues[i]); string strTemp = sw.GetStringBuilder().ToString(); Assert.Equal(iArrValidValues[i], strTemp.Length); } } [Fact] public static void NewStringWriterIsEmpty() { var sw = new StringWriter(); Assert.Equal(string.Empty, sw.ToString()); } [Fact] public static void NewStringWriterHasEmptyStringBuilder() { var sw = new StringWriter(); Assert.Equal(string.Empty, sw.GetStringBuilder().ToString()); } [Fact] public static void ToStringReturnsWrittenData() { StringBuilder sb = getSb(); StringWriter sw = new StringWriter(sb); sw.Write(sb.ToString()); Assert.Equal(sb.ToString(), sw.ToString()); } [Fact] public static void StringBuilderHasCorrectData() { StringBuilder sb = getSb(); StringWriter sw = new StringWriter(sb); sw.Write(sb.ToString()); Assert.Equal(sb.ToString(), sw.GetStringBuilder().ToString()); } [Fact] public static void Closed_DisposedExceptions() { StringWriter sw = new StringWriter(); sw.Close(); ValidateDisposedExceptions(sw); } [Fact] public static void Disposed_DisposedExceptions() { StringWriter sw = new StringWriter(); sw.Dispose(); ValidateDisposedExceptions(sw); } private static void ValidateDisposedExceptions(StringWriter sw) { Assert.Throws<ObjectDisposedException>(() => { sw.Write('a'); }); Assert.Throws<ObjectDisposedException>(() => { sw.Write(new char[10], 0, 1); }); Assert.Throws<ObjectDisposedException>(() => { sw.Write("abc"); }); } [Fact] public static async Task FlushAsyncWorks() { StringBuilder sb = getSb(); StringWriter sw = new StringWriter(sb); sw.Write(sb.ToString()); await sw.FlushAsync(); // I think this is a noop in this case Assert.Equal(sb.ToString(), sw.GetStringBuilder().ToString()); } [Fact] public static void MiscWrites() { var sw = new StringWriter(); sw.Write('H'); sw.Write("ello World!"); Assert.Equal("Hello World!", sw.ToString()); } [Fact] public static async Task MiscWritesAsync() { var sw = new StringWriter(); await sw.WriteAsync('H'); await sw.WriteAsync(new char[] { 'e', 'l', 'l', 'o', ' ' }); await sw.WriteAsync("World!"); Assert.Equal("Hello World!", sw.ToString()); } [Fact] public static async Task MiscWriteLineAsync() { var sw = new StringWriter(); await sw.WriteLineAsync('H'); await sw.WriteLineAsync(new char[] { 'e', 'l', 'l', 'o' }); await sw.WriteLineAsync("World!"); Assert.Equal( string.Format("H{0}ello{0}World!{0}", Environment.NewLine), sw.ToString()); } [Fact] public static void GetEncoding() { var sw = new StringWriter(); Assert.Equal(new UnicodeEncoding(false, false), sw.Encoding); Assert.Equal(Encoding.Unicode.WebName, sw.Encoding.WebName); } [Fact] public static void TestWriteMisc() { RemoteExecutor.Invoke(() => { CultureInfo.CurrentCulture = new CultureInfo("en-US"); // floating-point formatting comparison depends on culture var sw = new StringWriter(); sw.Write(true); sw.Write((char)'a'); sw.Write(new decimal(1234.01)); sw.Write((double)3452342.01); sw.Write((int)23456); sw.Write((long)long.MinValue); sw.Write((float)1234.50f); sw.Write((uint)uint.MaxValue); sw.Write((ulong)ulong.MaxValue); Assert.Equal("Truea1234.013452342.0123456-92233720368547758081234.5429496729518446744073709551615", sw.ToString()); }).Dispose(); } [Fact] public static void TestWriteObject() { var sw = new StringWriter(); sw.Write(new object()); Assert.Equal("System.Object", sw.ToString()); } [Fact] public static void TestWriteLineMisc() { RemoteExecutor.Invoke(() => { CultureInfo.CurrentCulture = new CultureInfo("en-US"); // floating-point formatting comparison depends on culture var sw = new StringWriter(); sw.WriteLine((bool)false); sw.WriteLine((char)'B'); sw.WriteLine((int)987); sw.WriteLine((long)875634); sw.WriteLine((float)1.23457f); sw.WriteLine((uint)45634563); sw.WriteLine((ulong.MaxValue)); Assert.Equal( string.Format("False{0}B{0}987{0}875634{0}1.23457{0}45634563{0}18446744073709551615{0}", Environment.NewLine), sw.ToString()); }).Dispose(); } [Fact] public static void TestWriteLineObject() { var sw = new StringWriter(); sw.WriteLine(new object()); Assert.Equal("System.Object" + Environment.NewLine, sw.ToString()); } [Fact] public static void TestWriteLineAsyncCharArray() { StringWriter sw = new StringWriter(); sw.WriteLineAsync(new char[] { 'H', 'e', 'l', 'l', 'o' }); Assert.Equal("Hello" + Environment.NewLine, sw.ToString()); } [Fact] public async Task NullNewLineAsync() { using (MemoryStream ms = new MemoryStream()) { string newLine; using (StreamWriter sw = new StreamWriter(ms, Encoding.UTF8, 16, true)) { newLine = sw.NewLine; await sw.WriteLineAsync(default(string)); await sw.WriteLineAsync(default(string)); } ms.Seek(0, SeekOrigin.Begin); using (StreamReader sr = new StreamReader(ms)) { Assert.Equal(newLine + newLine, await sr.ReadToEndAsync()); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // System.Drawing.carbonFunctions.cs // // Authors: // Geoff Norton ([email protected]> // // Copyright (C) 2007 Novell, Inc. (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #undef DEBUG_CLIPPING using System.Collections; using System.Reflection; using System.Runtime.InteropServices; namespace System.Drawing { internal static class MacSupport { internal static readonly Hashtable contextReference = new Hashtable(); internal static readonly object lockobj = new object(); internal static readonly Delegate hwnd_delegate = GetHwndDelegate(); #if DEBUG_CLIPPING internal static float red = 1.0f; internal static float green = 0.0f; internal static float blue = 0.0f; internal static int debug_threshold = 1; #endif private static Delegate GetHwndDelegate() { #if !NETSTANDARD1_6 foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) { if (string.Equals(asm.GetName().Name, "System.Windows.Forms")) { Type driver_type = asm.GetType("System.Windows.Forms.XplatUICarbon"); if (driver_type != null) { return (Delegate)driver_type.GetTypeInfo().GetField("HwndDelegate", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null); } } } #endif return null; } internal static CocoaContext GetCGContextForNSView(IntPtr handle) { IntPtr graphicsContext = objc_msgSend(objc_getClass("NSGraphicsContext"), sel_registerName("currentContext")); IntPtr ctx = objc_msgSend(graphicsContext, sel_registerName("graphicsPort")); Rect bounds = new Rect(); CGContextSaveGState(ctx); objc_msgSend_stret(ref bounds, handle, sel_registerName("bounds")); var isFlipped = bool_objc_msgSend(handle, sel_registerName("isFlipped")); if (isFlipped) { CGContextTranslateCTM(ctx, bounds.origin.x, bounds.size.height); CGContextScaleCTM(ctx, 1.0f, -1.0f); } return new CocoaContext(ctx, (int)bounds.size.width, (int)bounds.size.height); } internal static CarbonContext GetCGContextForView(IntPtr handle) { IntPtr context = IntPtr.Zero; IntPtr port = IntPtr.Zero; IntPtr window = IntPtr.Zero; window = GetControlOwner(handle); if (handle == IntPtr.Zero || window == IntPtr.Zero) { // FIXME: Can we actually get a CGContextRef for the desktop? this makes context IntPtr.Zero port = GetQDGlobalsThePort(); CreateCGContextForPort(port, ref context); Rect desktop_bounds = CGDisplayBounds(CGMainDisplayID()); return new CarbonContext(port, context, (int)desktop_bounds.size.width, (int)desktop_bounds.size.height); } QDRect window_bounds = new QDRect(); Rect view_bounds = new Rect(); port = GetWindowPort(window); context = GetContext(port); GetWindowBounds(window, 32, ref window_bounds); HIViewGetBounds(handle, ref view_bounds); HIViewConvertRect(ref view_bounds, handle, IntPtr.Zero); if (view_bounds.size.height < 0) view_bounds.size.height = 0; if (view_bounds.size.width < 0) view_bounds.size.width = 0; CGContextTranslateCTM(context, view_bounds.origin.x, (window_bounds.bottom - window_bounds.top) - (view_bounds.origin.y + view_bounds.size.height)); // Create the original rect path and clip to it Rect rc_clip = new Rect(0, 0, view_bounds.size.width, view_bounds.size.height); CGContextSaveGState(context); Rectangle[] clip_rectangles = (Rectangle[])hwnd_delegate.DynamicInvoke(new object[] { handle }); if (clip_rectangles != null && clip_rectangles.Length > 0) { int length = clip_rectangles.Length; CGContextBeginPath(context); CGContextAddRect(context, rc_clip); for (int i = 0; i < length; i++) { CGContextAddRect(context, new Rect(clip_rectangles[i].X, view_bounds.size.height - clip_rectangles[i].Y - clip_rectangles[i].Height, clip_rectangles[i].Width, clip_rectangles[i].Height)); } CGContextClosePath(context); CGContextEOClip(context); #if DEBUG_CLIPPING if (clip_rectangles.Length >= debug_threshold) { CGContextSetRGBFillColor (context, red, green, blue, 0.5f); CGContextFillRect (context, rc_clip); CGContextFlush (context); System.Threading.Thread.Sleep (500); if (red == 1.0f) { red = 0.0f; blue = 1.0f; } else if (blue == 1.0f) { blue = 0.0f; green = 1.0f; } else if (green == 1.0f) { green = 0.0f; red = 1.0f; } } #endif } else { CGContextBeginPath(context); CGContextAddRect(context, rc_clip); CGContextClosePath(context); CGContextClip(context); } return new CarbonContext(port, context, (int)view_bounds.size.width, (int)view_bounds.size.height); } internal static IntPtr GetContext(IntPtr port) { IntPtr context = IntPtr.Zero; lock (lockobj) { #if FALSE if (contextReference [port] != null) { CreateCGContextForPort (port, ref context); } else { QDBeginCGContext (port, ref context); contextReference [port] = context; } #else CreateCGContextForPort(port, ref context); #endif } return context; } internal static void ReleaseContext(IntPtr port, IntPtr context) { CGContextRestoreGState(context); lock (lockobj) { #if FALSE if (contextReference [port] != null && context == (IntPtr) contextReference [port]) { QDEndCGContext (port, ref context); contextReference [port] = null; } else { CFRelease (context); } #else CFRelease(context); #endif } } #region Cocoa Methods [DllImport("libobjc.dylib")] public static extern IntPtr objc_getClass(string className); [DllImport("libobjc.dylib")] public static extern IntPtr objc_msgSend(IntPtr basePtr, IntPtr selector, string argument); [DllImport("libobjc.dylib")] public static extern IntPtr objc_msgSend(IntPtr basePtr, IntPtr selector); [DllImport("libobjc.dylib")] public static extern void objc_msgSend_stret(ref Rect arect, IntPtr basePtr, IntPtr selector); [DllImport("libobjc.dylib", EntryPoint = "objc_msgSend")] public static extern bool bool_objc_msgSend(IntPtr handle, IntPtr selector); [DllImport("libobjc.dylib")] public static extern IntPtr sel_registerName(string selectorName); #endregion [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern IntPtr CGMainDisplayID(); [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern Rect CGDisplayBounds(IntPtr display); [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern int HIViewGetBounds(IntPtr vHnd, ref Rect r); [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern int HIViewConvertRect(ref Rect r, IntPtr a, IntPtr b); [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern IntPtr GetControlOwner(IntPtr aView); [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern int GetWindowBounds(IntPtr wHnd, uint reg, ref QDRect rect); [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern IntPtr GetWindowPort(IntPtr hWnd); [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern IntPtr GetQDGlobalsThePort(); [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern void CreateCGContextForPort(IntPtr port, ref IntPtr context); [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern void CFRelease(IntPtr context); [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern void QDBeginCGContext(IntPtr port, ref IntPtr context); [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern void QDEndCGContext(IntPtr port, ref IntPtr context); [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern int CGContextClipToRect(IntPtr context, Rect clip); [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern int CGContextClipToRects(IntPtr context, Rect[] clip_rects, int count); [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern void CGContextTranslateCTM(IntPtr context, float tx, float ty); [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern void CGContextScaleCTM(IntPtr context, float x, float y); [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern void CGContextFlush(IntPtr context); [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern void CGContextSynchronize(IntPtr context); [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern IntPtr CGPathCreateMutable(); [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern void CGPathAddRects(IntPtr path, IntPtr _void, Rect[] rects, int count); [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern void CGPathAddRect(IntPtr path, IntPtr _void, Rect rect); [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern void CGContextAddRects(IntPtr context, Rect[] rects, int count); [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern void CGContextAddRect(IntPtr context, Rect rect); [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern void CGContextBeginPath(IntPtr context); [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern void CGContextClosePath(IntPtr context); [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern void CGContextAddPath(IntPtr context, IntPtr path); [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern void CGContextClip(IntPtr context); [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern void CGContextEOClip(IntPtr context); [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern void CGContextEOFillPath(IntPtr context); [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern void CGContextSaveGState(IntPtr context); [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern void CGContextRestoreGState(IntPtr context); #if DEBUG_CLIPPING [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern void CGContextSetRGBFillColor (IntPtr context, float red, float green, float blue, float alpha); [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static extern void CGContextFillRect (IntPtr context, Rect rect); #endif } internal struct CGSize { public float width; public float height; } internal struct CGPoint { public float x; public float y; } internal struct Rect { public Rect(float x, float y, float width, float height) { this.origin.x = x; this.origin.y = y; this.size.width = width; this.size.height = height; } public CGPoint origin; public CGSize size; } internal struct QDRect { public short top; public short left; public short bottom; public short right; } internal struct CarbonContext : IMacContext { public IntPtr port; public IntPtr ctx; public int width; public int height; public CarbonContext(IntPtr port, IntPtr ctx, int width, int height) { this.port = port; this.ctx = ctx; this.width = width; this.height = height; } public void Synchronize() { MacSupport.CGContextSynchronize(ctx); } public void Release() { MacSupport.ReleaseContext(port, ctx); } } internal struct CocoaContext : IMacContext { public IntPtr ctx; public int width; public int height; public CocoaContext(IntPtr ctx, int width, int height) { this.ctx = ctx; this.width = width; this.height = height; } public void Synchronize() { MacSupport.CGContextSynchronize(ctx); } public void Release() { MacSupport.CGContextRestoreGState(ctx); } } internal interface IMacContext { void Synchronize(); void Release(); } }
// 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.AcceptanceTestsReport { using Microsoft.Rest; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// Test Infrastructure for AutoRest /// </summary> public partial class AutoRestReportService : ServiceClient<AutoRestReportService>, IAutoRestReportService { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Initializes a new instance of the AutoRestReportService class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestReportService(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestReportService class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestReportService(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestReportService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestReportService(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestReportService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestReportService(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// An optional partial-method to perform custom initialization. ///</summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { BaseUri = new System.Uri("http://localhost"); SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); } /// <summary> /// Get test coverage report /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<IDictionary<string, int?>>> GetReportWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetReport", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "report").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<IDictionary<string, int?>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<IDictionary<string, int?>>(_responseContent, DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGeneration { /// <summary> /// Generates symbols that describe declarations to be generated. /// </summary> internal static class CodeGenerationSymbolFactory { /// <summary> /// Determines if the symbol is purely a code generation symbol. /// </summary> public static bool IsCodeGenerationSymbol(this ISymbol symbol) { return symbol is CodeGenerationSymbol; } /// <summary> /// Creates an event symbol that can be used to describe an event declaration. /// </summary> public static IEventSymbol CreateEventSymbol(IList<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol type, IEventSymbol explicitInterfaceSymbol, string name, IMethodSymbol addMethod = null, IMethodSymbol removeMethod = null, IMethodSymbol raiseMethod = null, IList<IParameterSymbol> parameterList = null) { var result = new CodeGenerationEventSymbol(null, attributes, accessibility, modifiers, type, explicitInterfaceSymbol, name, addMethod, removeMethod, raiseMethod, parameterList); CodeGenerationEventInfo.Attach(result, modifiers.IsUnsafe); return result; } internal static IPropertySymbol CreatePropertySymbol( INamedTypeSymbol containingType, IList<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol type, IPropertySymbol explicitInterfaceSymbol, string name, IList<IParameterSymbol> parameters, IMethodSymbol getMethod, IMethodSymbol setMethod, bool isIndexer = false, SyntaxNode initializer = null) { var result = new CodeGenerationPropertySymbol( containingType, attributes, accessibility, modifiers, type, explicitInterfaceSymbol, name, isIndexer, parameters, getMethod, setMethod); CodeGenerationPropertyInfo.Attach(result, modifiers.IsNew, modifiers.IsUnsafe, initializer); return result; } /// <summary> /// Creates a property symbol that can be used to describe a property declaration. /// </summary> public static IPropertySymbol CreatePropertySymbol(IList<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol type, IPropertySymbol explicitInterfaceSymbol, string name, IList<IParameterSymbol> parameters, IMethodSymbol getMethod, IMethodSymbol setMethod, bool isIndexer = false) { return CreatePropertySymbol( containingType: null, attributes: attributes, accessibility: accessibility, modifiers: modifiers, type: type, explicitInterfaceSymbol: explicitInterfaceSymbol, name: name, parameters: parameters, getMethod: getMethod, setMethod: setMethod, isIndexer: isIndexer); } /// <summary> /// Creates a field symbol that can be used to describe a field declaration. /// </summary> public static IFieldSymbol CreateFieldSymbol(IList<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol type, string name, bool hasConstantValue = false, object constantValue = null, SyntaxNode initializer = null) { var result = new CodeGenerationFieldSymbol(null, attributes, accessibility, modifiers, type, name, hasConstantValue, constantValue); CodeGenerationFieldInfo.Attach(result, modifiers.IsUnsafe, modifiers.IsWithEvents, initializer); return result; } /// <summary> /// Creates a constructor symbol that can be used to describe a constructor declaration. /// </summary> public static IMethodSymbol CreateConstructorSymbol(IList<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, string typeName, IList<IParameterSymbol> parameters, IList<SyntaxNode> statements = null, IList<SyntaxNode> baseConstructorArguments = null, IList<SyntaxNode> thisConstructorArguments = null) { var result = new CodeGenerationConstructorSymbol(null, attributes, accessibility, modifiers, parameters); CodeGenerationConstructorInfo.Attach(result, typeName, statements, baseConstructorArguments, thisConstructorArguments); return result; } /// <summary> /// Creates a destructor symbol that can be used to describe a destructor declaration. /// </summary> public static IMethodSymbol CreateDestructorSymbol(IList<AttributeData> attributes, string typeName, IList<SyntaxNode> statements = null) { var result = new CodeGenerationDestructorSymbol(null, attributes); CodeGenerationDestructorInfo.Attach(result, typeName, statements); return result; } internal static IMethodSymbol CreateMethodSymbol(INamedTypeSymbol containingType, IList<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol returnType, IMethodSymbol explicitInterfaceSymbol, string name, IList<ITypeParameterSymbol> typeParameters, IList<IParameterSymbol> parameters, IList<SyntaxNode> statements = null, IList<SyntaxNode> handlesExpressions = null, IList<AttributeData> returnTypeAttributes = null, MethodKind methodKind = MethodKind.Ordinary, bool returnsByRef = false) { var result = new CodeGenerationMethodSymbol(containingType, attributes, accessibility, modifiers, returnType, returnsByRef, explicitInterfaceSymbol, name, typeParameters, parameters, returnTypeAttributes, methodKind); CodeGenerationMethodInfo.Attach(result, modifiers.IsNew, modifiers.IsUnsafe, modifiers.IsPartial, modifiers.IsAsync, statements, handlesExpressions); return result; } /// <summary> /// Creates a method symbol that can be used to describe a method declaration. /// </summary> public static IMethodSymbol CreateMethodSymbol(IList<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol returnType, IMethodSymbol explicitInterfaceSymbol, string name, IList<ITypeParameterSymbol> typeParameters, IList<IParameterSymbol> parameters, IList<SyntaxNode> statements = null, IList<SyntaxNode> handlesExpressions = null, IList<AttributeData> returnTypeAttributes = null, MethodKind methodKind = MethodKind.Ordinary) { return CreateMethodSymbol(null, attributes, accessibility, modifiers, returnType, explicitInterfaceSymbol, name, typeParameters, parameters, statements, handlesExpressions, returnTypeAttributes, methodKind); } /// <summary> /// Creates a method symbol that can be used to describe an operator declaration. /// </summary> public static IMethodSymbol CreateOperatorSymbol(IList<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol returnType, CodeGenerationOperatorKind operatorKind, IList<IParameterSymbol> parameters, IList<SyntaxNode> statements = null, IList<AttributeData> returnTypeAttributes = null) { int expectedParameterCount = CodeGenerationOperatorSymbol.GetParameterCount(operatorKind); if (parameters.Count != expectedParameterCount) { var message = expectedParameterCount == 1 ? WorkspacesResources.Invalid_number_of_parameters_for_unary_operator : WorkspacesResources.Invalid_number_of_parameters_for_binary_operator; throw new ArgumentException(message, nameof(parameters)); } var result = new CodeGenerationOperatorSymbol(null, attributes, accessibility, modifiers, returnType, operatorKind, parameters, returnTypeAttributes); CodeGenerationMethodInfo.Attach(result, modifiers.IsNew, modifiers.IsUnsafe, modifiers.IsPartial, modifiers.IsAsync, statements, handlesExpressions: null); return result; } /// <summary> /// Creates a method symbol that can be used to describe a conversion declaration. /// </summary> public static IMethodSymbol CreateConversionSymbol(IList<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol toType, IParameterSymbol fromType, bool isImplicit = false, IList<SyntaxNode> statements = null, IList<AttributeData> toTypeAttributes = null) { var result = new CodeGenerationConversionSymbol(null, attributes, accessibility, modifiers, toType, fromType, isImplicit, toTypeAttributes); CodeGenerationMethodInfo.Attach(result, modifiers.IsNew, modifiers.IsUnsafe, modifiers.IsPartial, modifiers.IsAsync, statements, handlesExpressions: null); return result; } /// <summary> /// Creates a parameter symbol that can be used to describe a parameter declaration. /// </summary> public static IParameterSymbol CreateParameterSymbol(ITypeSymbol type, string name) { return CreateParameterSymbol(attributes: null, refKind: RefKind.None, isParams: false, type: type, name: name, isOptional: false); } /// <summary> /// Creates a parameter symbol that can be used to describe a parameter declaration. /// </summary> public static IParameterSymbol CreateParameterSymbol(IList<AttributeData> attributes, RefKind refKind, bool isParams, ITypeSymbol type, string name, bool isOptional = false, bool hasDefaultValue = false, object defaultValue = null) { return new CodeGenerationParameterSymbol(null, attributes, refKind, isParams, type, name, isOptional, hasDefaultValue, defaultValue); } /// <summary> /// Creates a parameter symbol that can be used to describe a parameter declaration. /// </summary> public static ITypeParameterSymbol CreateTypeParameterSymbol(string name, int ordinal = 0) { return CreateTypeParameter(attributes: null, varianceKind: VarianceKind.None, name: name, constraintTypes: ImmutableArray.Create<ITypeSymbol>(), hasConstructorConstraint: false, hasReferenceConstraint: false, hasValueConstraint: false, ordinal: ordinal); } /// <summary> /// Creates a type parameter symbol that can be used to describe a type parameter declaration. /// </summary> public static ITypeParameterSymbol CreateTypeParameter(IList<AttributeData> attributes, VarianceKind varianceKind, string name, ImmutableArray<ITypeSymbol> constraintTypes, bool hasConstructorConstraint = false, bool hasReferenceConstraint = false, bool hasValueConstraint = false, int ordinal = 0) { return new CodeGenerationTypeParameterSymbol(null, attributes, varianceKind, name, constraintTypes, hasConstructorConstraint, hasReferenceConstraint, hasValueConstraint, ordinal); } /// <summary> /// Creates a pointer type symbol that can be used to describe a pointer type reference. /// </summary> public static IPointerTypeSymbol CreatePointerTypeSymbol(ITypeSymbol pointedAtType) { return new CodeGenerationPointerTypeSymbol(pointedAtType); } /// <summary> /// Creates an array type symbol that can be used to describe an array type reference. /// </summary> public static IArrayTypeSymbol CreateArrayTypeSymbol(ITypeSymbol elementType, int rank = 1) { return new CodeGenerationArrayTypeSymbol(elementType, rank); } internal static IMethodSymbol CreateAccessorSymbol( IMethodSymbol accessor, IList<AttributeData> attributes = null, Accessibility? accessibility = null, IMethodSymbol explicitInterfaceSymbol = null, IList<SyntaxNode> statements = null) { return CodeGenerationSymbolFactory.CreateMethodSymbol( attributes, accessibility ?? accessor.DeclaredAccessibility, accessor.GetSymbolModifiers().WithIsAbstract(statements == null), accessor.ReturnType, explicitInterfaceSymbol ?? accessor.ExplicitInterfaceImplementations.FirstOrDefault(), accessor.Name, accessor.TypeParameters, accessor.Parameters, statements, returnTypeAttributes: accessor.GetReturnTypeAttributes()); } /// <summary> /// Creates an method type symbol that can be used to describe an accessor method declaration. /// </summary> public static IMethodSymbol CreateAccessorSymbol( IList<AttributeData> attributes, Accessibility accessibility, IList<SyntaxNode> statements) { return CodeGenerationSymbolFactory.CreateMethodSymbol( attributes, accessibility, new DeclarationModifiers(isAbstract: statements == null), null, null, string.Empty, null, null, statements: statements); } /// <summary> /// Create attribute data that can be used in describing an attribute declaration. /// </summary> public static AttributeData CreateAttributeData( INamedTypeSymbol attributeClass, ImmutableArray<TypedConstant> constructorArguments = default(ImmutableArray<TypedConstant>), ImmutableArray<KeyValuePair<string, TypedConstant>> namedArguments = default(ImmutableArray<KeyValuePair<string, TypedConstant>>)) { return new CodeGenerationAttributeData(attributeClass, constructorArguments, namedArguments); } /// <summary> /// Creates a named type symbol that can be used to describe a named type declaration. /// </summary> public static INamedTypeSymbol CreateNamedTypeSymbol(IList<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, TypeKind typeKind, string name, IList<ITypeParameterSymbol> typeParameters = null, INamedTypeSymbol baseType = null, IList<INamedTypeSymbol> interfaces = null, SpecialType specialType = SpecialType.None, IList<ISymbol> members = null) { members = members ?? SpecializedCollections.EmptyList<ISymbol>(); return new CodeGenerationNamedTypeSymbol( null, attributes, accessibility, modifiers, typeKind, name, typeParameters, baseType, interfaces, specialType, members.Where(m => !(m is INamedTypeSymbol)).ToList(), members.OfType<INamedTypeSymbol>().Select(n => n.ToCodeGenerationSymbol()).ToList(), enumUnderlyingType: null); } /// <summary> /// Creates a method type symbol that can be used to describe a delegate type declaration. /// </summary> public static INamedTypeSymbol CreateDelegateTypeSymbol(IList<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol returnType, string name, IList<ITypeParameterSymbol> typeParameters = null, IList<IParameterSymbol> parameters = null) { var invokeMethod = CreateMethodSymbol( attributes: null, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(), returnType: returnType, explicitInterfaceSymbol: null, name: "Invoke", typeParameters: null, parameters: parameters); return new CodeGenerationNamedTypeSymbol( containingType: null, attributes: attributes, declaredAccessibility: accessibility, modifiers: modifiers, typeKind: TypeKind.Delegate, name: name, typeParameters: typeParameters, baseType: null, interfaces: null, specialType: SpecialType.None, members: new[] { invokeMethod }, typeMembers: SpecializedCollections.EmptyList<CodeGenerationAbstractNamedTypeSymbol>(), enumUnderlyingType: null); } /// <summary> /// Creates a namespace symbol that can be used to describe a namespace declaration. /// </summary> public static INamespaceSymbol CreateNamespaceSymbol(string name, IList<ISymbol> imports = null, IList<INamespaceOrTypeSymbol> members = null) { var @namespace = new CodeGenerationNamespaceSymbol(name, members); CodeGenerationNamespaceInfo.Attach(@namespace, imports); return @namespace; } internal static IMethodSymbol CreateMethodSymbol( IMethodSymbol method, IList<AttributeData> attributes = null, Accessibility? accessibility = null, DeclarationModifiers? modifiers = null, IMethodSymbol explicitInterfaceSymbol = null, string name = null, IList<SyntaxNode> statements = null) { return CodeGenerationSymbolFactory.CreateMethodSymbol( attributes, accessibility ?? method.DeclaredAccessibility, modifiers ?? method.GetSymbolModifiers(), method.ReturnType, explicitInterfaceSymbol, name ?? method.Name, method.TypeParameters, method.Parameters, statements, returnTypeAttributes: method.GetReturnTypeAttributes()); } internal static IPropertySymbol CreatePropertySymbol( IPropertySymbol property, IList<AttributeData> attributes = null, Accessibility? accessibility = null, DeclarationModifiers? modifiers = null, IPropertySymbol explicitInterfaceSymbol = null, string name = null, bool? isIndexer = null, IMethodSymbol getMethod = null, IMethodSymbol setMethod = null) { return CodeGenerationSymbolFactory.CreatePropertySymbol( attributes, accessibility ?? property.DeclaredAccessibility, modifiers ?? property.GetSymbolModifiers(), property.Type, explicitInterfaceSymbol, name ?? property.Name, property.Parameters, getMethod, setMethod, isIndexer ?? property.IsIndexer); } internal static IEventSymbol CreateEventSymbol( IEventSymbol @event, IList<AttributeData> attributes = null, Accessibility? accessibility = null, DeclarationModifiers? modifiers = null, IEventSymbol explicitInterfaceSymbol = null, string name = null, IMethodSymbol addMethod = null, IMethodSymbol removeMethod = null) { return CodeGenerationSymbolFactory.CreateEventSymbol( attributes, accessibility ?? @event.DeclaredAccessibility, modifiers ?? @event.GetSymbolModifiers(), @event.Type, explicitInterfaceSymbol, name ?? @event.Name, addMethod, removeMethod); } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.Management.Automation; using System.Management.Automation.Internal; using Dbg = System.Management.Automation.Diagnostics; using System.Collections.Generic; using System.Collections; using System.IO; using System.Management.Automation.Provider; using System.Security; using System.Security.Cryptography.X509Certificates; using System.Runtime.InteropServices; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using DWORD = System.UInt32; namespace Microsoft.PowerShell.Commands { /// <summary> /// Defines the base class from which all signature commands /// are derived. /// </summary> public abstract class SignatureCommandsBase : PSCmdlet { /// <summary> /// Gets or sets the path to the file for which to get or set the /// digital signature. /// </summary> [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")] public string[] FilePath { get { return _path; } set { _path = value; } } private string[] _path; /// <summary> /// Gets or sets the literal path to the file for which to get or set the /// digital signature. /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByLiteralPath")] [Alias("PSPath")] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] LiteralPath { get { return _path; } set { _path = value; _isLiteralPath = true; } } private bool _isLiteralPath = false; /// <summary> /// Gets or sets the digital signature to be written to /// the output pipeline. /// </summary> protected Signature Signature { get { return _signature; } set { _signature = value; } } private Signature _signature; /// <summary> /// Gets or sets the file type of the byte array containing the content with /// digital signature. /// </summary> [Parameter(Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByContent")] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] SourcePathOrExtension { get { return _sourcePathOrExtension; } set { _sourcePathOrExtension = value; } } private string[] _sourcePathOrExtension; /// <summary> /// File contents as a byte array /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByContent")] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public byte[] Content { get { return _content; } set { _content = value; } } private byte[] _content; // // name of this command // private string _commandName; /// <summary> /// Initializes a new instance of the SignatureCommandsBase class, /// using the given command name. /// </summary> /// /// <param name="name"> /// The name of the command. /// </param> protected SignatureCommandsBase(string name) : base() { _commandName = name; } // // hide default ctor // private SignatureCommandsBase() : base() { } /// <summary> /// Processes records from the input pipeline. /// For each input object, the command gets or /// sets the digital signature on the object, and /// and exports the object. /// </summary> protected override void ProcessRecord() { if (Content == null) { // // this cannot happen as we have specified the Path // property to be mandatory parameter // Dbg.Assert((FilePath != null) && (FilePath.Length > 0), "GetSignatureCommand: Param binder did not bind path"); foreach (string p in FilePath) { Collection<string> paths = new Collection<string>(); // Expand wildcard characters if (_isLiteralPath) { paths.Add(SessionState.Path.GetUnresolvedProviderPathFromPSPath(p)); } else { try { foreach (PathInfo tempPath in SessionState.Path.GetResolvedPSPathFromPSPath(p)) { paths.Add(tempPath.ProviderPath); } } catch (ItemNotFoundException) { WriteError( SecurityUtils.CreateFileNotFoundErrorRecord( SignatureCommands.FileNotFound, "SignatureCommandsBaseFileNotFound", p)); } } if (paths.Count == 0) continue; bool foundFile = false; foreach (string path in paths) { if (!System.IO.Directory.Exists(path)) { foundFile = true; string resolvedFilePath = SecurityUtils.GetFilePathOfExistingFile(this, path); if (resolvedFilePath == null) { WriteError(SecurityUtils.CreateFileNotFoundErrorRecord( SignatureCommands.FileNotFound, "SignatureCommandsBaseFileNotFound", path)); } else { if ((Signature = PerformAction(resolvedFilePath)) != null) { WriteObject(Signature); } } } } if (!foundFile) { WriteError(SecurityUtils.CreateFileNotFoundErrorRecord( SignatureCommands.CannotRetrieveFromContainer, "SignatureCommandsBaseCannotRetrieveFromContainer")); } } } else { foreach (string sourcePathOrExtension in SourcePathOrExtension) { if ((Signature = PerformAction(sourcePathOrExtension, Content)) != null) { WriteObject(Signature); } } } } /// <summary> /// Performs the action (ie: get signature, or set signature) /// on the specified file. /// </summary> /// <param name="filePath"> /// The name of the file on which to perform the action. /// </param> protected abstract Signature PerformAction(string filePath); /// <summary> /// Performs the action (ie: get signature, or set signature) /// on the specified contents. /// </summary> /// <param name="fileName"> /// The filename used for type if content is specified. /// </param> /// <param name="content"> /// The file contents on which to perform the action. /// </param> protected abstract Signature PerformAction(string fileName, byte[] content); } /// <summary> /// Defines the implementation of the 'get-AuthenticodeSignature' cmdlet. /// This cmdlet extracts the digital signature from the given file. /// </summary> [Cmdlet(VerbsCommon.Get, "AuthenticodeSignature", DefaultParameterSetName = "ByPath", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113307")] [OutputType(typeof(Signature))] public sealed class GetAuthenticodeSignatureCommand : SignatureCommandsBase { /// <summary> /// Initializes a new instance of the GetSignatureCommand class. /// </summary> public GetAuthenticodeSignatureCommand() : base("Get-AuthenticodeSignature") { } /// <summary> /// Gets the signature from the specified file. /// </summary> /// <param name="filePath"> /// The name of the file on which to perform the action. /// </param> /// <returns> /// The signature on the specified file. /// </returns> protected override Signature PerformAction(string filePath) { return SignatureHelper.GetSignature(filePath, null); } /// <summary> /// Gets the signature from the specified file contents. /// </summary> /// <param name="sourcePathOrExtension">The file type associated with the contents</param> /// <param name="content"> /// The contents of the file on which to perform the action. /// </param> /// <returns> /// The signature on the specified file contents. /// </returns> protected override Signature PerformAction(string sourcePathOrExtension, byte[] content) { return SignatureHelper.GetSignature(sourcePathOrExtension, System.Text.Encoding.Unicode.GetString(content)); } } /// <summary> /// Defines the implementation of the 'set-AuthenticodeSignature' cmdlet. /// This cmdlet sets the digital signature on a given file. /// </summary> [Cmdlet(VerbsCommon.Set, "AuthenticodeSignature", SupportsShouldProcess = true, DefaultParameterSetName = "ByPath", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113391")] [OutputType(typeof(Signature))] public sealed class SetAuthenticodeSignatureCommand : SignatureCommandsBase { /// <summary> /// Initializes a new instance of the SetAuthenticodeSignatureCommand class. /// </summary> public SetAuthenticodeSignatureCommand() : base("set-AuthenticodeSignature") { } /// <summary> /// Gets or sets the certificate with which to sign the /// file. /// </summary> [Parameter(Position = 1, Mandatory = true)] public X509Certificate2 Certificate { get { return _certificate; } set { _certificate = value; } } private X509Certificate2 _certificate; /// <summary> /// Gets or sets the additional certificates to /// include in the digital signature. /// Use 'signer' to include only the signer's certificate. /// Use 'notroot' to include all certificates in the certificate /// chain, except for the root authority. /// Use 'all' to include all certificates in the certificate chain. /// /// Defaults to 'notroot'. /// </summary> /// [Parameter(Mandatory = false)] [ValidateSet("signer", "notroot", "all")] public string IncludeChain { get { return _includeChain; } set { _includeChain = value; } } private string _includeChain = "notroot"; /// <summary> /// Gets or sets the Url of the time stamping server. /// The time stamping server certifies the exact time /// that the certificate was added to the file. /// </summary> [Parameter(Mandatory = false)] public string TimestampServer { get { return _timestampServer; } set { if (value == null) { value = String.Empty; } _timestampServer = value; } } private string _timestampServer = ""; /// <summary> /// Gets or sets the hash algorithm used for signing. /// This string value must represent the name of a Cryptographic Algorithm /// Identifier supported by Windows. /// </summary> [Parameter(Mandatory = false)] public string HashAlgorithm { get { return _hashAlgorithm; } set { _hashAlgorithm = value; } } private string _hashAlgorithm = null; /// <summary> /// Property that sets force parameter. /// </summary> [Parameter()] public SwitchParameter Force { get { return _force; } set { _force = value; } } private bool _force; /// <summary> /// Sets the digital signature on the specified file. /// </summary> /// <param name="filePath"> /// The name of the file on which to perform the action. /// </param> /// <returns> /// The signature on the specified file. /// </returns> protected override Signature PerformAction(string filePath) { SigningOption option = GetSigningOption(IncludeChain); if (Certificate == null) { throw PSTraceSource.NewArgumentNullException("certificate"); } // // if the cert is not good for signing, we cannot // process any more files. Exit the command. // if (!SecuritySupport.CertIsGoodForSigning(Certificate)) { Exception e = PSTraceSource.NewArgumentException( "certificate", SignatureCommands.CertNotGoodForSigning); throw e; } if (!ShouldProcess(filePath)) return null; FileInfo readOnlyFileInfo = null; try { if (this.Force) { try { // remove readonly attributes on the file FileInfo fInfo = new FileInfo(filePath); if (fInfo != null) { // Save some disk write time by checking whether file is readonly.. if ((fInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { // remember to reset the read-only attribute later readOnlyFileInfo = fInfo; //Make sure the file is not read only fInfo.Attributes &= ~(FileAttributes.ReadOnly); } } } // These are the known exceptions for File.Load and StreamWriter.ctor catch (ArgumentException e) { ErrorRecord er = new ErrorRecord( e, "ForceArgumentException", ErrorCategory.WriteError, filePath ); WriteError(er); return null; } catch (IOException e) { ErrorRecord er = new ErrorRecord( e, "ForceIOException", ErrorCategory.WriteError, filePath ); WriteError(er); return null; } catch (UnauthorizedAccessException e) { ErrorRecord er = new ErrorRecord( e, "ForceUnauthorizedAccessException", ErrorCategory.PermissionDenied, filePath ); WriteError(er); return null; } catch (NotSupportedException e) { ErrorRecord er = new ErrorRecord( e, "ForceNotSupportedException", ErrorCategory.WriteError, filePath ); WriteError(er); return null; } catch (System.Security.SecurityException e) { ErrorRecord er = new ErrorRecord( e, "ForceSecurityException", ErrorCategory.PermissionDenied, filePath ); WriteError(er); return null; } } // // ProcessRecord() code in base class has already // ascertained that filePath really represents an existing // file. Thus we can safely call GetFileSize() below. // if (SecurityUtils.GetFileSize(filePath) < 4) { // Note that the message param comes first string message = String.Format( System.Globalization.CultureInfo.CurrentCulture, UtilsStrings.FileSmallerThan4Bytes, filePath); PSArgumentException e = new PSArgumentException(message, "filePath"); ErrorRecord er = SecurityUtils.CreateInvalidArgumentErrorRecord( e, "SignatureCommandsBaseFileSmallerThan4Bytes" ); WriteError(er); return null; } return SignatureHelper.SignFile(option, filePath, Certificate, TimestampServer, _hashAlgorithm); } finally { // reset the read-only attribute if (null != readOnlyFileInfo) { readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly; } } } /// <summary> /// Not implemented /// </summary> protected override Signature PerformAction(string sourcePathOrExtension, byte[] content) { throw new NotImplementedException(); } private struct SigningOptionInfo { internal SigningOption option; internal string optionName; internal SigningOptionInfo(SigningOption o, string n) { option = o; optionName = n; } } /// <summary> /// association between SigningOption.* values and the /// corresponding string names. /// </summary> private static readonly SigningOptionInfo[] s_sigOptionInfo = { new SigningOptionInfo(SigningOption.AddOnlyCertificate, "signer"), new SigningOptionInfo(SigningOption.AddFullCertificateChainExceptRoot, "notroot"), new SigningOptionInfo(SigningOption.AddFullCertificateChain, "all") }; /// <summary> /// get SigningOption value corresponding to a string name /// </summary> /// /// <param name="optionName"> name of option </param> /// /// <returns> SigningOption </returns> /// private static SigningOption GetSigningOption(string optionName) { foreach (SigningOptionInfo si in s_sigOptionInfo) { if (String.Equals(optionName, si.optionName, StringComparison.OrdinalIgnoreCase)) { return si.option; } } return SigningOption.AddFullCertificateChainExceptRoot; } } }
/* * 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 cloudformation-2010-05-15.normal.json service model. */ using System; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.CloudFormation.Model; using Amazon.CloudFormation.Model.Internal.MarshallTransformations; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.CloudFormation { /// <summary> /// Implementation for accessing CloudFormation /// /// AWS CloudFormation /// <para> /// AWS CloudFormation enables you to create and manage AWS infrastructure deployments /// predictably and repeatedly. AWS CloudFormation helps you leverage AWS products such /// as Amazon EC2, EBS, Amazon SNS, ELB, and Auto Scaling to build highly-reliable, highly /// scalable, cost effective applications without worrying about creating and configuring /// the underlying AWS infrastructure. /// </para> /// /// <para> /// With AWS CloudFormation, you declare all of your resources and dependencies in a template /// file. The template defines a collection of resources as a single unit called a stack. /// AWS CloudFormation creates and deletes all member resources of the stack together /// and manages all dependencies between the resources for you. /// </para> /// /// <para> /// For more information about this product, go to the <a href="http://aws.amazon.com/cloudformation/">CloudFormation /// Product Page</a>. /// </para> /// /// <para> /// Amazon CloudFormation makes use of other AWS products. If you need additional technical /// information about a specific AWS product, you can find the product's technical documentation /// at <a href="http://aws.amazon.com/documentation/">http://aws.amazon.com/documentation/</a>. /// </para> /// </summary> public partial class AmazonCloudFormationClient : AmazonServiceClient, IAmazonCloudFormation { #region Constructors /// <summary> /// Constructs AmazonCloudFormationClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> public AmazonCloudFormationClient(AWSCredentials credentials) : this(credentials, new AmazonCloudFormationConfig()) { } /// <summary> /// Constructs AmazonCloudFormationClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="region">The region to connect.</param> public AmazonCloudFormationClient(AWSCredentials credentials, RegionEndpoint region) : this(credentials, new AmazonCloudFormationConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonCloudFormationClient with AWS Credentials and an /// AmazonCloudFormationClient Configuration object. /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="clientConfig">The AmazonCloudFormationClient Configuration Object</param> public AmazonCloudFormationClient(AWSCredentials credentials, AmazonCloudFormationConfig clientConfig) : base(credentials, clientConfig) { } /// <summary> /// Constructs AmazonCloudFormationClient 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 AmazonCloudFormationClient(string awsAccessKeyId, string awsSecretAccessKey) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonCloudFormationConfig()) { } /// <summary> /// Constructs AmazonCloudFormationClient 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 AmazonCloudFormationClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonCloudFormationConfig() {RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonCloudFormationClient with AWS Access Key ID, AWS Secret Key and an /// AmazonCloudFormationClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="clientConfig">The AmazonCloudFormationClient Configuration Object</param> public AmazonCloudFormationClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonCloudFormationConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, clientConfig) { } /// <summary> /// Constructs AmazonCloudFormationClient 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 AmazonCloudFormationClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonCloudFormationConfig()) { } /// <summary> /// Constructs AmazonCloudFormationClient 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 AmazonCloudFormationClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonCloudFormationConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonCloudFormationClient with AWS Access Key ID, AWS Secret Key and an /// AmazonCloudFormationClient 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 AmazonCloudFormationClient Configuration Object</param> public AmazonCloudFormationClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonCloudFormationConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig) { } #endregion #region Overrides /// <summary> /// Creates the signer for the service. /// </summary> protected override AbstractAWSSigner CreateSigner() { return new AWS4Signer(); } /// <summary> /// Customizes the runtime pipeline. /// </summary> /// <param name="pipeline">Runtime pipeline for the current client.</param> protected override void CustomizeRuntimePipeline(RuntimePipeline pipeline) { pipeline.AddHandlerAfter<Amazon.Runtime.Internal.Marshaller>(new Amazon.CloudFormation.Internal.ProcessRequestHandler()); } #endregion #region Dispose /// <summary> /// Disposes the service client. /// </summary> protected override void Dispose(bool disposing) { base.Dispose(disposing); } #endregion #region CancelUpdateStack internal CancelUpdateStackResponse CancelUpdateStack(CancelUpdateStackRequest request) { var marshaller = new CancelUpdateStackRequestMarshaller(); var unmarshaller = CancelUpdateStackResponseUnmarshaller.Instance; return Invoke<CancelUpdateStackRequest,CancelUpdateStackResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CancelUpdateStack operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CancelUpdateStack 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<CancelUpdateStackResponse> CancelUpdateStackAsync(CancelUpdateStackRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CancelUpdateStackRequestMarshaller(); var unmarshaller = CancelUpdateStackResponseUnmarshaller.Instance; return InvokeAsync<CancelUpdateStackRequest,CancelUpdateStackResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateStack internal CreateStackResponse CreateStack(CreateStackRequest request) { var marshaller = new CreateStackRequestMarshaller(); var unmarshaller = CreateStackResponseUnmarshaller.Instance; return Invoke<CreateStackRequest,CreateStackResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateStack operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateStack 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<CreateStackResponse> CreateStackAsync(CreateStackRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateStackRequestMarshaller(); var unmarshaller = CreateStackResponseUnmarshaller.Instance; return InvokeAsync<CreateStackRequest,CreateStackResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteStack internal DeleteStackResponse DeleteStack(DeleteStackRequest request) { var marshaller = new DeleteStackRequestMarshaller(); var unmarshaller = DeleteStackResponseUnmarshaller.Instance; return Invoke<DeleteStackRequest,DeleteStackResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteStack operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteStack 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<DeleteStackResponse> DeleteStackAsync(DeleteStackRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteStackRequestMarshaller(); var unmarshaller = DeleteStackResponseUnmarshaller.Instance; return InvokeAsync<DeleteStackRequest,DeleteStackResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeAccountLimits internal DescribeAccountLimitsResponse DescribeAccountLimits(DescribeAccountLimitsRequest request) { var marshaller = new DescribeAccountLimitsRequestMarshaller(); var unmarshaller = DescribeAccountLimitsResponseUnmarshaller.Instance; return Invoke<DescribeAccountLimitsRequest,DescribeAccountLimitsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeAccountLimits operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeAccountLimits 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<DescribeAccountLimitsResponse> DescribeAccountLimitsAsync(DescribeAccountLimitsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeAccountLimitsRequestMarshaller(); var unmarshaller = DescribeAccountLimitsResponseUnmarshaller.Instance; return InvokeAsync<DescribeAccountLimitsRequest,DescribeAccountLimitsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeStackEvents internal DescribeStackEventsResponse DescribeStackEvents(DescribeStackEventsRequest request) { var marshaller = new DescribeStackEventsRequestMarshaller(); var unmarshaller = DescribeStackEventsResponseUnmarshaller.Instance; return Invoke<DescribeStackEventsRequest,DescribeStackEventsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeStackEvents operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeStackEvents 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<DescribeStackEventsResponse> DescribeStackEventsAsync(DescribeStackEventsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeStackEventsRequestMarshaller(); var unmarshaller = DescribeStackEventsResponseUnmarshaller.Instance; return InvokeAsync<DescribeStackEventsRequest,DescribeStackEventsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeStackResource internal DescribeStackResourceResponse DescribeStackResource(DescribeStackResourceRequest request) { var marshaller = new DescribeStackResourceRequestMarshaller(); var unmarshaller = DescribeStackResourceResponseUnmarshaller.Instance; return Invoke<DescribeStackResourceRequest,DescribeStackResourceResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeStackResource operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeStackResource 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<DescribeStackResourceResponse> DescribeStackResourceAsync(DescribeStackResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeStackResourceRequestMarshaller(); var unmarshaller = DescribeStackResourceResponseUnmarshaller.Instance; return InvokeAsync<DescribeStackResourceRequest,DescribeStackResourceResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeStackResources internal DescribeStackResourcesResponse DescribeStackResources(DescribeStackResourcesRequest request) { var marshaller = new DescribeStackResourcesRequestMarshaller(); var unmarshaller = DescribeStackResourcesResponseUnmarshaller.Instance; return Invoke<DescribeStackResourcesRequest,DescribeStackResourcesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeStackResources operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeStackResources 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<DescribeStackResourcesResponse> DescribeStackResourcesAsync(DescribeStackResourcesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeStackResourcesRequestMarshaller(); var unmarshaller = DescribeStackResourcesResponseUnmarshaller.Instance; return InvokeAsync<DescribeStackResourcesRequest,DescribeStackResourcesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeStacks internal DescribeStacksResponse DescribeStacks() { return DescribeStacks(new DescribeStacksRequest()); } internal DescribeStacksResponse DescribeStacks(DescribeStacksRequest request) { var marshaller = new DescribeStacksRequestMarshaller(); var unmarshaller = DescribeStacksResponseUnmarshaller.Instance; return Invoke<DescribeStacksRequest,DescribeStacksResponse>(request, marshaller, unmarshaller); } /// <summary> /// Returns the description for the specified stack; if no stack name was specified, then /// it returns the description for all the stacks created. /// </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 DescribeStacks service method, as returned by CloudFormation.</returns> public Task<DescribeStacksResponse> DescribeStacksAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { return DescribeStacksAsync(new DescribeStacksRequest(), cancellationToken); } /// <summary> /// Initiates the asynchronous execution of the DescribeStacks operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeStacks 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<DescribeStacksResponse> DescribeStacksAsync(DescribeStacksRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeStacksRequestMarshaller(); var unmarshaller = DescribeStacksResponseUnmarshaller.Instance; return InvokeAsync<DescribeStacksRequest,DescribeStacksResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region EstimateTemplateCost internal EstimateTemplateCostResponse EstimateTemplateCost(EstimateTemplateCostRequest request) { var marshaller = new EstimateTemplateCostRequestMarshaller(); var unmarshaller = EstimateTemplateCostResponseUnmarshaller.Instance; return Invoke<EstimateTemplateCostRequest,EstimateTemplateCostResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the EstimateTemplateCost operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the EstimateTemplateCost 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<EstimateTemplateCostResponse> EstimateTemplateCostAsync(EstimateTemplateCostRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new EstimateTemplateCostRequestMarshaller(); var unmarshaller = EstimateTemplateCostResponseUnmarshaller.Instance; return InvokeAsync<EstimateTemplateCostRequest,EstimateTemplateCostResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region GetStackPolicy internal GetStackPolicyResponse GetStackPolicy(GetStackPolicyRequest request) { var marshaller = new GetStackPolicyRequestMarshaller(); var unmarshaller = GetStackPolicyResponseUnmarshaller.Instance; return Invoke<GetStackPolicyRequest,GetStackPolicyResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetStackPolicy operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetStackPolicy 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<GetStackPolicyResponse> GetStackPolicyAsync(GetStackPolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new GetStackPolicyRequestMarshaller(); var unmarshaller = GetStackPolicyResponseUnmarshaller.Instance; return InvokeAsync<GetStackPolicyRequest,GetStackPolicyResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region GetTemplate internal GetTemplateResponse GetTemplate(GetTemplateRequest request) { var marshaller = new GetTemplateRequestMarshaller(); var unmarshaller = GetTemplateResponseUnmarshaller.Instance; return Invoke<GetTemplateRequest,GetTemplateResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetTemplate operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetTemplate 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<GetTemplateResponse> GetTemplateAsync(GetTemplateRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new GetTemplateRequestMarshaller(); var unmarshaller = GetTemplateResponseUnmarshaller.Instance; return InvokeAsync<GetTemplateRequest,GetTemplateResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region GetTemplateSummary internal GetTemplateSummaryResponse GetTemplateSummary(GetTemplateSummaryRequest request) { var marshaller = new GetTemplateSummaryRequestMarshaller(); var unmarshaller = GetTemplateSummaryResponseUnmarshaller.Instance; return Invoke<GetTemplateSummaryRequest,GetTemplateSummaryResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetTemplateSummary operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetTemplateSummary 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<GetTemplateSummaryResponse> GetTemplateSummaryAsync(GetTemplateSummaryRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new GetTemplateSummaryRequestMarshaller(); var unmarshaller = GetTemplateSummaryResponseUnmarshaller.Instance; return InvokeAsync<GetTemplateSummaryRequest,GetTemplateSummaryResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListStackResources internal ListStackResourcesResponse ListStackResources(ListStackResourcesRequest request) { var marshaller = new ListStackResourcesRequestMarshaller(); var unmarshaller = ListStackResourcesResponseUnmarshaller.Instance; return Invoke<ListStackResourcesRequest,ListStackResourcesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ListStackResources operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListStackResources 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<ListStackResourcesResponse> ListStackResourcesAsync(ListStackResourcesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListStackResourcesRequestMarshaller(); var unmarshaller = ListStackResourcesResponseUnmarshaller.Instance; return InvokeAsync<ListStackResourcesRequest,ListStackResourcesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListStacks internal ListStacksResponse ListStacks() { return ListStacks(new ListStacksRequest()); } internal ListStacksResponse ListStacks(ListStacksRequest request) { var marshaller = new ListStacksRequestMarshaller(); var unmarshaller = ListStacksResponseUnmarshaller.Instance; return Invoke<ListStacksRequest,ListStacksResponse>(request, marshaller, unmarshaller); } /// <summary> /// Returns the summary information for stacks whose status matches the specified StackStatusFilter. /// Summary information for stacks that have been deleted is kept for 90 days after the /// stack is deleted. If no StackStatusFilter is specified, summary information for all /// stacks is returned (including existing stacks and stacks that have been deleted). /// </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 ListStacks service method, as returned by CloudFormation.</returns> public Task<ListStacksResponse> ListStacksAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { return ListStacksAsync(new ListStacksRequest(), cancellationToken); } /// <summary> /// Initiates the asynchronous execution of the ListStacks operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListStacks 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<ListStacksResponse> ListStacksAsync(ListStacksRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListStacksRequestMarshaller(); var unmarshaller = ListStacksResponseUnmarshaller.Instance; return InvokeAsync<ListStacksRequest,ListStacksResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region SetStackPolicy internal SetStackPolicyResponse SetStackPolicy(SetStackPolicyRequest request) { var marshaller = new SetStackPolicyRequestMarshaller(); var unmarshaller = SetStackPolicyResponseUnmarshaller.Instance; return Invoke<SetStackPolicyRequest,SetStackPolicyResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the SetStackPolicy operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SetStackPolicy 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<SetStackPolicyResponse> SetStackPolicyAsync(SetStackPolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new SetStackPolicyRequestMarshaller(); var unmarshaller = SetStackPolicyResponseUnmarshaller.Instance; return InvokeAsync<SetStackPolicyRequest,SetStackPolicyResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region SignalResource internal SignalResourceResponse SignalResource(SignalResourceRequest request) { var marshaller = new SignalResourceRequestMarshaller(); var unmarshaller = SignalResourceResponseUnmarshaller.Instance; return Invoke<SignalResourceRequest,SignalResourceResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the SignalResource operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SignalResource 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<SignalResourceResponse> SignalResourceAsync(SignalResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new SignalResourceRequestMarshaller(); var unmarshaller = SignalResourceResponseUnmarshaller.Instance; return InvokeAsync<SignalResourceRequest,SignalResourceResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region UpdateStack internal UpdateStackResponse UpdateStack(UpdateStackRequest request) { var marshaller = new UpdateStackRequestMarshaller(); var unmarshaller = UpdateStackResponseUnmarshaller.Instance; return Invoke<UpdateStackRequest,UpdateStackResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the UpdateStack operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateStack 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<UpdateStackResponse> UpdateStackAsync(UpdateStackRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new UpdateStackRequestMarshaller(); var unmarshaller = UpdateStackResponseUnmarshaller.Instance; return InvokeAsync<UpdateStackRequest,UpdateStackResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ValidateTemplate internal ValidateTemplateResponse ValidateTemplate() { return ValidateTemplate(new ValidateTemplateRequest()); } internal ValidateTemplateResponse ValidateTemplate(ValidateTemplateRequest request) { var marshaller = new ValidateTemplateRequestMarshaller(); var unmarshaller = ValidateTemplateResponseUnmarshaller.Instance; return Invoke<ValidateTemplateRequest,ValidateTemplateResponse>(request, marshaller, unmarshaller); } /// <summary> /// Validates a specified template. /// </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 ValidateTemplate service method, as returned by CloudFormation.</returns> public Task<ValidateTemplateResponse> ValidateTemplateAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { return ValidateTemplateAsync(new ValidateTemplateRequest(), cancellationToken); } /// <summary> /// Initiates the asynchronous execution of the ValidateTemplate operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ValidateTemplate 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<ValidateTemplateResponse> ValidateTemplateAsync(ValidateTemplateRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ValidateTemplateRequestMarshaller(); var unmarshaller = ValidateTemplateResponseUnmarshaller.Instance; return InvokeAsync<ValidateTemplateRequest,ValidateTemplateResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { // Some utility functions for compiling and checking errors. public abstract class CompilingTestBase : CSharpTestBase { private const string DefaultTypeName = "C"; private const string DefaultMethodName = "M"; internal static BoundBlock ParseAndBindMethodBody(string program, string typeName = DefaultTypeName, string methodName = DefaultMethodName) { var compilation = CreateCompilationWithMscorlib(program); var method = (MethodSymbol)compilation.GlobalNamespace.GetTypeMembers(typeName).Single().GetMembers(methodName).Single(); // Provide an Emit.Module so that the lowering passes will be run var module = new PEAssemblyBuilder( (SourceAssemblySymbol)compilation.Assembly, emitOptions: EmitOptions.Default, outputKind: OutputKind.ConsoleApplication, serializationProperties: GetDefaultModulePropertiesForSerialization(), manifestResources: Enumerable.Empty<ResourceDescription>()); TypeCompilationState compilationState = new TypeCompilationState(method.ContainingType, compilation, module); var diagnostics = DiagnosticBag.GetInstance(); var block = MethodCompiler.BindMethodBody(method, compilationState, diagnostics); diagnostics.Free(); return block; } public static string DumpDiagnostic(Diagnostic diagnostic) { return string.Format("'{0}' {1}", diagnostic.Location.SourceTree.GetText().ToString(diagnostic.Location.SourceSpan), DiagnosticFormatter.Instance.Format(diagnostic.WithLocation(Location.None), EnsureEnglishUICulture.PreferredOrNull)); } [Obsolete("Use VerifyDiagnostics", true)] public static void TestDiagnostics(IEnumerable<Diagnostic> diagnostics, params string[] diagStrings) { AssertEx.SetEqual(diagStrings, diagnostics.Select(DumpDiagnostic)); } // Do a full compilation and check all the errors. [Obsolete("Use VerifyDiagnostics", true)] public void TestAllErrors(string code, params string[] errors) { var compilation = CreateCompilationWithMscorlib(code); var diagnostics = compilation.GetDiagnostics(); AssertEx.SetEqual(errors, diagnostics.Select(DumpDiagnostic)); } // Tests just the errors found while binding method M in class C. [Obsolete("Use VerifyDiagnostics", true)] public void TestErrors(string code, params string[] errors) { var compilation = CreateCompilationWithMscorlib(code); var method = (SourceMethodSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single().GetMembers("M").Single(); var factory = compilation.GetBinderFactory(method.SyntaxTree); var bodyBlock = (BlockSyntax)method.BodySyntax; var parameterBinderContext = factory.GetBinder(bodyBlock); var binder = new ExecutableCodeBinder(bodyBlock.Parent, method, parameterBinderContext); var diagnostics = new DiagnosticBag(); var block = (BoundBlock)binder.BindStatement(bodyBlock, diagnostics); AssertEx.SetEqual(errors, diagnostics.AsEnumerable().Select(DumpDiagnostic)); } [Obsolete("Use VerifyDiagnostics", true)] public void TestWarnings(string code, params string[] expectedWarnings) { var compilation = CreateCompilationWithMscorlib(code); var method = (SourceMethodSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single().GetMembers("M").Single(); var factory = compilation.GetBinderFactory(method.SyntaxTree); var bodyBlock = (BlockSyntax)method.BodySyntax; var parameterBinderContext = factory.GetBinder(bodyBlock); var binder = new ExecutableCodeBinder(bodyBlock.Parent, method, parameterBinderContext); var block = (BoundBlock)binder.BindStatement(bodyBlock, new DiagnosticBag()); var actualWarnings = new DiagnosticBag(); DiagnosticsPass.IssueDiagnostics(compilation, block, actualWarnings, method); AssertEx.SetEqual(expectedWarnings, actualWarnings.AsEnumerable().Select(DumpDiagnostic)); } public const string LINQ = #region the string LINQ defines a complete LINQ API called List1<T> (for instance method) and List2<T> (for extension methods) @"using System; using System.Text; public delegate R Func1<in T1, out R>(T1 arg1); public delegate R Func1<in T1, in T2, out R>(T1 arg1, T2 arg2); public class List1<T> { internal T[] data; internal int length; public List1(params T[] args) { this.data = (T[])args.Clone(); this.length = data.Length; } public List1() { this.data = new T[0]; this.length = 0; } public int Length { get { return length; } } //public T this[int index] { get { return this.data[index]; } } public T Get(int index) { return this.data[index]; } public virtual void Add(T t) { if (data.Length == length) Array.Resize(ref data, data.Length * 2 + 1); data[length++] = t; } public override string ToString() { StringBuilder builder = new StringBuilder(); builder.Append('['); for (int i = 0; i < Length; i++) { if (i != 0) builder.Append(',').Append(' '); builder.Append(data[i]); } builder.Append(']'); return builder.ToString(); } public List1<E> Cast<E>() { E[] data = new E[Length]; for (int i = 0; i < Length; i++) data[i] = (E)(object)this.data[i]; return new List1<E>(data); } public List1<T> Where(Func1<T, bool> predicate) { List1<T> result = new List1<T>(); for (int i = 0; i < Length; i++) { T datum = this.data[i]; if (predicate(datum)) result.Add(datum); } return result; } public List1<U> Select<U>(Func1<T, U> selector) { int length = this.Length; U[] data = new U[length]; for (int i = 0; i < length; i++) data[i] = selector(this.data[i]); return new List1<U>(data); } public List1<V> SelectMany<U, V>(Func1<T, List1<U>> selector, Func1<T, U, V> resultSelector) { List1<V> result = new List1<V>(); int length = this.Length; for (int i = 0; i < length; i++) { T t = this.data[i]; List1<U> selected = selector(t); int ulength = selected.Length; for (int j = 0; j < ulength; j++) { U u = selected.data[j]; V v = resultSelector(t, u); result.Add(v); } } return result; } public List1<V> Join<U, K, V>(List1<U> inner, Func1<T, K> outerKeyselector, Func1<U, K> innerKeyselector, Func1<T, U, V> resultSelector) { List1<Joined<K, T, U>> joined = new List1<Joined<K, T, U>>(); for (int i = 0; i < Length; i++) { T t = this.Get(i); K k = outerKeyselector(t); Joined<K, T, U> row = null; for (int j = 0; j < joined.Length; j++) { if (joined.Get(j).k.Equals(k)) { row = joined.Get(j); break; } } if (row == null) joined.Add(row = new Joined<K, T, U>(k)); row.t.Add(t); } for (int i = 0; i < inner.Length; i++) { U u = inner.Get(i); K k = innerKeyselector(u); Joined<K, T, U> row = null; for (int j = 0; j < joined.Length; j++) { if (joined.Get(j).k.Equals(k)) { row = joined.Get(j); break; } } if (row == null) joined.Add(row = new Joined<K, T, U>(k)); row.u.Add(u); } List1<V> result = new List1<V>(); for (int i = 0; i < joined.Length; i++) { Joined<K, T, U> row = joined.Get(i); for (int j = 0; j < row.t.Length; j++) { T t = row.t.Get(j); for (int k = 0; k < row.u.Length; k++) { U u = row.u.Get(k); V v = resultSelector(t, u); result.Add(v); } } } return result; } class Joined<K, T2, U> { public Joined(K k) { this.k = k; this.t = new List1<T2>(); this.u = new List1<U>(); } public readonly K k; public readonly List1<T2> t; public readonly List1<U> u; } public List1<V> GroupJoin<U, K, V>(List1<U> inner, Func1<T, K> outerKeyselector, Func1<U, K> innerKeyselector, Func1<T, List1<U>, V> resultSelector) { List1<Joined<K, T, U>> joined = new List1<Joined<K, T, U>>(); for (int i = 0; i < Length; i++) { T t = this.Get(i); K k = outerKeyselector(t); Joined<K, T, U> row = null; for (int j = 0; j < joined.Length; j++) { if (joined.Get(j).k.Equals(k)) { row = joined.Get(j); break; } } if (row == null) joined.Add(row = new Joined<K, T, U>(k)); row.t.Add(t); } for (int i = 0; i < inner.Length; i++) { U u = inner.Get(i); K k = innerKeyselector(u); Joined<K, T, U> row = null; for (int j = 0; j < joined.Length; j++) { if (joined.Get(j).k.Equals(k)) { row = joined.Get(j); break; } } if (row == null) joined.Add(row = new Joined<K, T, U>(k)); row.u.Add(u); } List1<V> result = new List1<V>(); for (int i = 0; i < joined.Length; i++) { Joined<K, T, U> row = joined.Get(i); for (int j = 0; j < row.t.Length; j++) { T t = row.t.Get(j); V v = resultSelector(t, row.u); result.Add(v); } } return result; } public OrderedList1<T> OrderBy<K>(Func1<T, K> Keyselector) { OrderedList1<T> result = new OrderedList1<T>(this); result.ThenBy(Keyselector); return result; } public OrderedList1<T> OrderByDescending<K>(Func1<T, K> Keyselector) { OrderedList1<T> result = new OrderedList1<T>(this); result.ThenByDescending(Keyselector); return result; } public List1<Group1<K, T>> GroupBy<K>(Func1<T, K> Keyselector) { List1<Group1<K, T>> result = new List1<Group1<K, T>>(); for (int i = 0; i < Length; i++) { T t = this.Get(i); K k = Keyselector(t); Group1<K, T> Group1 = null; for (int j = 0; j < result.Length; j++) { if (result.Get(j).Key.Equals(k)) { Group1 = result.Get(j); break; } } if (Group1 == null) { result.Add(Group1 = new Group1<K, T>(k)); } Group1.Add(t); } return result; } public List1<Group1<K, E>> GroupBy<K, E>(Func1<T, K> Keyselector, Func1<T, E> elementSelector) { List1<Group1<K, E>> result = new List1<Group1<K, E>>(); for (int i = 0; i < Length; i++) { T t = this.Get(i); K k = Keyselector(t); Group1<K, E> Group1 = null; for (int j = 0; j < result.Length; j++) { if (result.Get(j).Key.Equals(k)) { Group1 = result.Get(j); break; } } if (Group1 == null) { result.Add(Group1 = new Group1<K, E>(k)); } Group1.Add(elementSelector(t)); } return result; } } public class OrderedList1<T> : List1<T> { private List1<Keys1> Keys1; public override void Add(T t) { throw new NotSupportedException(); } internal OrderedList1(List1<T> list) { Keys1 = new List1<Keys1>(); for (int i = 0; i < list.Length; i++) { base.Add(list.Get(i)); Keys1.Add(new Keys1()); } } public OrderedList1<T> ThenBy<K>(Func1<T, K> Keyselector) { for (int i = 0; i < Length; i++) { object o = Keyselector(this.Get(i)); // work around bug 8405 Keys1.Get(i).Add((IComparable)o); } Sort(); return this; } class ReverseOrder : IComparable { IComparable c; public ReverseOrder(IComparable c) { this.c = c; } public int CompareTo(object o) { ReverseOrder other = (ReverseOrder)o; return other.c.CompareTo(this.c); } public override string ToString() { return String.Empty + '-' + c; } } public OrderedList1<T> ThenByDescending<K>(Func1<T, K> Keyselector) { for (int i = 0; i < Length; i++) { object o = Keyselector(this.Get(i)); // work around bug 8405 Keys1.Get(i).Add(new ReverseOrder((IComparable)o)); } Sort(); return this; } void Sort() { Array.Sort(this.Keys1.data, this.data, 0, Length); } } class Keys1 : List1<IComparable>, IComparable { public int CompareTo(object o) { Keys1 other = (Keys1)o; for (int i = 0; i < Length; i++) { int c = this.Get(i).CompareTo(other.Get(i)); if (c != 0) return c; } return 0; } } public class Group1<K, T> : List1<T> { public Group1(K k, params T[] data) : base(data) { this.Key = k; } public K Key { get; private set; } public override string ToString() { return Key + String.Empty + ':' + base.ToString(); } } //public delegate R Func2<in T1, out R>(T1 arg1); //public delegate R Func2<in T1, in T2, out R>(T1 arg1, T2 arg2); // //public class List2<T> //{ // internal T[] data; // internal int length; // // public List2(params T[] args) // { // this.data = (T[])args.Clone(); // this.length = data.Length; // } // // public List2() // { // this.data = new T[0]; // this.length = 0; // } // // public int Length { get { return length; } } // // //public T this[int index] { get { return this.data[index]; } } // public T Get(int index) { return this.data[index]; } // // public virtual void Add(T t) // { // if (data.Length == length) Array.Resize(ref data, data.Length * 2 + 1); // data[length++] = t; // } // // public override string ToString() // { // StringBuilder builder = new StringBuilder(); // builder.Append('['); // for (int i = 0; i < Length; i++) // { // if (i != 0) builder.Append(',').Append(' '); // builder.Append(data[i]); // } // builder.Append(']'); // return builder.ToString(); // } // //} // //public class OrderedList2<T> : List2<T> //{ // internal List2<Keys2> Keys2; // // public override void Add(T t) // { // throw new NotSupportedException(); // } // // internal OrderedList2(List2<T> list) // { // Keys2 = new List2<Keys2>(); // for (int i = 0; i < list.Length; i++) // { // base.Add(list.Get(i)); // Keys2.Add(new Keys2()); // } // } // // internal void Sort() // { // Array.Sort(this.Keys2.data, this.data, 0, Length); // } //} // //class Keys2 : List2<IComparable>, IComparable //{ // public int CompareTo(object o) // { // Keys2 other = (Keys2)o; // for (int i = 0; i < Length; i++) // { // int c = this.Get(i).CompareTo(other.Get(i)); // if (c != 0) return c; // } // return 0; // } //} // //public class Group2<K, T> : List2<T> //{ // public Group2(K k, params T[] data) // : base(data) // { // this.Key = k; // } // // public K Key { get; private set; } // // public override string ToString() // { // return Key + String.Empty + ':' + base.ToString(); // } //} // //public static class Extensions2 //{ // // public static List2<E> Cast<T, E>(this List2<T> _this) // { // E[] data = new E[_this.Length]; // for (int i = 0; i < _this.Length; i++) // data[i] = (E)(object)_this.data[i]; // return new List2<E>(data); // } // // public static List2<T> Where<T>(this List2<T> _this, Func2<T, bool> predicate) // { // List2<T> result = new List2<T>(); // for (int i = 0; i < _this.Length; i++) // { // T datum = _this.data[i]; // if (predicate(datum)) result.Add(datum); // } // return result; // } // // public static List2<U> Select<T,U>(this List2<T> _this, Func2<T, U> selector) // { // int length = _this.Length; // U[] data = new U[length]; // for (int i = 0; i < length; i++) data[i] = selector(_this.data[i]); // return new List2<U>(data); // } // // public static List2<V> SelectMany<T, U, V>(this List2<T> _this, Func2<T, List2<U>> selector, Func2<T, U, V> resultSelector) // { // List2<V> result = new List2<V>(); // int length = _this.Length; // for (int i = 0; i < length; i++) // { // T t = _this.data[i]; // List2<U> selected = selector(t); // int ulength = selected.Length; // for (int j = 0; j < ulength; j++) // { // U u = selected.data[j]; // V v = resultSelector(t, u); // result.Add(v); // } // } // // return result; // } // // public static List2<V> Join<T, U, K, V>(this List2<T> _this, List2<U> inner, Func2<T, K> outerKeyselector, // Func2<U, K> innerKeyselector, Func2<T, U, V> resultSelector) // { // List2<Joined<K, T, U>> joined = new List2<Joined<K, T, U>>(); // for (int i = 0; i < _this.Length; i++) // { // T t = _this.Get(i); // K k = outerKeyselector(t); // Joined<K, T, U> row = null; // for (int j = 0; j < joined.Length; j++) // { // if (joined.Get(j).k.Equals(k)) // { // row = joined.Get(j); // break; // } // } // if (row == null) joined.Add(row = new Joined<K, T, U>(k)); // row.t.Add(t); // } // for (int i = 0; i < inner.Length; i++) // { // U u = inner.Get(i); // K k = innerKeyselector(u); // Joined<K, T, U> row = null; // for (int j = 0; j < joined.Length; j++) // { // if (joined.Get(j).k.Equals(k)) // { // row = joined.Get(j); // break; // } // } // if (row == null) joined.Add(row = new Joined<K, T, U>(k)); // row.u.Add(u); // } // List2<V> result = new List2<V>(); // for (int i = 0; i < joined.Length; i++) // { // Joined<K, T, U> row = joined.Get(i); // for (int j = 0; j < row.t.Length; j++) // { // T t = row.t.Get(j); // for (int k = 0; k < row.u.Length; k++) // { // U u = row.u.Get(k); // V v = resultSelector(t, u); // result.Add(v); // } // } // } // return result; // } // // class Joined<K, T2, U> // { // public Joined(K k) // { // this.k = k; // this.t = new List2<T2>(); // this.u = new List2<U>(); // } // public readonly K k; // public readonly List2<T2> t; // public readonly List2<U> u; // } // // public static List2<V> GroupJoin<T, U, K, V>(this List2<T> _this, List2<U> inner, Func2<T, K> outerKeyselector, // Func2<U, K> innerKeyselector, Func2<T, List2<U>, V> resultSelector) // { // List2<Joined<K, T, U>> joined = new List2<Joined<K, T, U>>(); // for (int i = 0; i < _this.Length; i++) // { // T t = _this.Get(i); // K k = outerKeyselector(t); // Joined<K, T, U> row = null; // for (int j = 0; j < joined.Length; j++) // { // if (joined.Get(j).k.Equals(k)) // { // row = joined.Get(j); // break; // } // } // if (row == null) joined.Add(row = new Joined<K, T, U>(k)); // row.t.Add(t); // } // for (int i = 0; i < inner.Length; i++) // { // U u = inner.Get(i); // K k = innerKeyselector(u); // Joined<K, T, U> row = null; // for (int j = 0; j < joined.Length; j++) // { // if (joined.Get(j).k.Equals(k)) // { // row = joined.Get(j); // break; // } // } // if (row == null) joined.Add(row = new Joined<K, T, U>(k)); // row.u.Add(u); // } // List2<V> result = new List2<V>(); // for (int i = 0; i < joined.Length; i++) // { // Joined<K, T, U> row = joined.Get(i); // for (int j = 0; j < row.t.Length; j++) // { // T t = row.t.Get(j); // V v = resultSelector(t, row.u); // result.Add(v); // } // } // return result; // } // // public static OrderedList2<T> OrderBy<T, K>(this List2<T> _this, Func2<T, K> Keyselector) // { // OrderedList2<T> result = new OrderedList2<T>(_this); // result.ThenBy(Keyselector); // return result; // } // // public static OrderedList2<T> OrderByDescending<T, K>(this List2<T> _this, Func2<T, K> Keyselector) // { // OrderedList2<T> result = new OrderedList2<T>(_this); // result.ThenByDescending(Keyselector); // return result; // } // // public static List2<Group2<K, T>> GroupBy<T, K>(this List2<T> _this, Func2<T, K> Keyselector) // { // List2<Group2<K, T>> result = new List2<Group2<K, T>>(); // for (int i = 0; i < _this.Length; i++) // { // T t = _this.Get(i); // K k = Keyselector(t); // Group2<K, T> Group2 = null; // for (int j = 0; j < result.Length; j++) // { // if (result.Get(j).Key.Equals(k)) // { // Group2 = result.Get(j); // break; // } // } // if (Group2 == null) // { // result.Add(Group2 = new Group2<K, T>(k)); // } // Group2.Add(t); // } // return result; // } // // public static List2<Group2<K, E>> GroupBy<T, K, E>(this List2<T> _this, Func2<T, K> Keyselector, // Func2<T, E> elementSelector) // { // List2<Group2<K, E>> result = new List2<Group2<K, E>>(); // for (int i = 0; i < _this.Length; i++) // { // T t = _this.Get(i); // K k = Keyselector(t); // Group2<K, E> Group2 = null; // for (int j = 0; j < result.Length; j++) // { // if (result.Get(j).Key.Equals(k)) // { // Group2 = result.Get(j); // break; // } // } // if (Group2 == null) // { // result.Add(Group2 = new Group2<K, E>(k)); // } // Group2.Add(elementSelector(t)); // } // return result; // } // // public static OrderedList2<T> ThenBy<T, K>(this OrderedList2<T> _this, Func2<T, K> Keyselector) // { // for (int i = 0; i < _this.Length; i++) // { // object o = Keyselector(_this.Get(i)); // work around bug 8405 // _this.Keys2.Get(i).Add((IComparable)o); // } // _this.Sort(); // return _this; // } // // class ReverseOrder : IComparable // { // IComparable c; // public ReverseOrder(IComparable c) // { // this.c = c; // } // public int CompareTo(object o) // { // ReverseOrder other = (ReverseOrder)o; // return other.c.CompareTo(this.c); // } // public override string ToString() // { // return String.Empty + '-' + c; // } // } // // public static OrderedList2<T> ThenByDescending<T, K>(this OrderedList2<T> _this, Func2<T, K> Keyselector) // { // for (int i = 0; i < _this.Length; i++) // { // object o = Keyselector(_this.Get(i)); // work around bug 8405 // _this.Keys2.Get(i).Add(new ReverseOrder((IComparable)o)); // } // _this.Sort(); // return _this; // } // //} " #endregion the string LINQ ; } }
namespace Gu.Wpf.Geometry.UiTests { using System; using System.Windows; using Gu.Wpf.UiAutomation; using NUnit.Framework; using Application = Gu.Wpf.UiAutomation.Application; public sealed class ZoomWindowTests { private const string WindowName = "ZoomWindow"; [SetUp] public void SetUp() { using var app = Application.AttachOrLaunch("Gu.Wpf.Geometry.Demo.exe", WindowName); var window = app.MainWindow; window.FindButton("None").Invoke(); } [OneTimeTearDown] public void OneTimeTearDown() { Application.KillLaunched(Application.FindExe("Gu.Wpf.Geometry.Demo.exe")); } [Test] public void ZoomUniform() { using var app = Application.AttachOrLaunch("Gu.Wpf.Geometry.Demo.exe", WindowName); var window = app.MainWindow; var renderSize = window.FindTextBlock("Size"); var contentMatrix = window.FindTextBlock("ContentMatrix"); var zoomButton = window.FindButton("Uniform"); Assert.AreEqual(true, zoomButton.IsEnabled); zoomButton.Click(); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("0.62,0,0,0.62,100,0", contentMatrix.Text); window.FindButton("None").Click(); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("Identity", contentMatrix.Text); Assert.AreEqual(true, zoomButton.IsEnabled); zoomButton.Click(); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("0.62,0,0,0.62,100,0", contentMatrix.Text); } [Test] public void ZoomUniformToFill() { using var app = Application.AttachOrLaunch("Gu.Wpf.Geometry.Demo.exe", WindowName); var window = app.MainWindow; var renderSize = window.FindTextBlock("Size"); var contentMatrix = window.FindTextBlock("ContentMatrix"); var zoomButton = window.FindButton("UniformToFill"); Assert.AreEqual(true, zoomButton.IsEnabled); zoomButton.Click(); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("1.28667,0,0,1.28667,0,-133.33333", contentMatrix.Text); window.FindButton("None").Click(); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("Identity", contentMatrix.Text); Assert.AreEqual(true, zoomButton.IsEnabled); zoomButton.Click(); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("1.28667,0,0,1.28667,0,-133.33333", contentMatrix.Text); } [Test] public void Increase() { using var app = Application.AttachOrLaunch("Gu.Wpf.Geometry.Demo.exe", WindowName); var window = app.MainWindow; var renderSize = window.FindTextBlock("Size"); var contentMatrix = window.FindTextBlock("ContentMatrix"); window.FindButton("Uniform").Invoke(); var zoomButton = window.FindButton("Increase"); Assert.AreEqual(true, zoomButton.IsEnabled); zoomButton.Click(); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("1.24,0,0,1.24,7,-124", contentMatrix.Text); Assert.AreEqual(true, zoomButton.IsEnabled); zoomButton.Click(); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("2.48,0,0,2.48,-179,-372", contentMatrix.Text); } [Test] public void Decrease() { using var app = Application.AttachOrLaunch("Gu.Wpf.Geometry.Demo.exe", WindowName); var window = app.MainWindow; var renderSize = window.FindTextBlock("Size"); var contentMatrix = window.FindTextBlock("ContentMatrix"); window.FindButton("Uniform").Invoke(); var zoomButton = window.FindButton("Decrease"); Assert.AreEqual(true, zoomButton.IsEnabled); zoomButton.Click(); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("0.31,0,0,0.31,146.5,62", contentMatrix.Text); Assert.AreEqual(true, zoomButton.IsEnabled); zoomButton.Click(); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("0.155,0,0,0.155,169.75,93", contentMatrix.Text); } [Test] public void PanFromNone() { using var app = Application.AttachOrLaunch("Gu.Wpf.Geometry.Demo.exe", WindowName); var window = app.MainWindow; var renderSize = window.FindTextBlock("Size"); var contentMatrix = window.FindTextBlock("ContentMatrix"); var zoomBox = window.FindGroupBox("Zoombox"); window.FindButton("None").Invoke(); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("Identity", contentMatrix.Text); Mouse.DragHorizontally(MouseButton.Left, zoomBox.Bounds.Center(), 50); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("1,0,0,1,50,0", contentMatrix.Text); Mouse.DragHorizontally(MouseButton.Left, zoomBox.Bounds.Center(), -50); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("Identity", contentMatrix.Text); Mouse.DragVertically(MouseButton.Left, zoomBox.Bounds.Center(), 50); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("1,0,0,1,0,50", contentMatrix.Text); Mouse.DragVertically(MouseButton.Left, zoomBox.Bounds.Center(), -50); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("Identity", contentMatrix.Text); } [Test] public void PanFromUniform() { using var app = Application.AttachOrLaunch("Gu.Wpf.Geometry.Demo.exe", WindowName); var window = app.MainWindow; var renderSize = window.FindTextBlock("Size"); var contentMatrix = window.FindTextBlock("ContentMatrix"); var zoomBox = window.FindGroupBox("Zoombox"); window.FindButton("Uniform").Invoke(); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("0.62,0,0,0.62,100,0", contentMatrix.Text); Mouse.DragHorizontally(MouseButton.Left, zoomBox.Bounds.Center(), 50); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("0.62,0,0,0.62,150,0", contentMatrix.Text); Mouse.DragHorizontally(MouseButton.Left, zoomBox.Bounds.Center(), -50); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("0.62,0,0,0.62,100,0", contentMatrix.Text); Mouse.DragVertically(MouseButton.Left, zoomBox.Bounds.Center(), 50); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("0.62,0,0,0.62,100,50", contentMatrix.Text); Mouse.DragVertically(MouseButton.Left, zoomBox.Bounds.Center(), -50); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("0.62,0,0,0.62,100,0", contentMatrix.Text); } [Test] public void MouseWheelTopLeft() { using var app = Application.AttachOrLaunch("Gu.Wpf.Geometry.Demo.exe", WindowName); var window = app.MainWindow; var renderSize = window.FindTextBlock("Size"); var contentMatrix = window.FindTextBlock("ContentMatrix"); Mouse.Position = window.FindGroupBox("Zoombox").Bounds.TopLeft + new Vector(1, 1); Assert.AreEqual("Identity", contentMatrix.Text); Mouse.Scroll(1); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("1.05,0,0,1.05,0,0", contentMatrix.Text); Mouse.Scroll(1); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("1.1025,0,0,1.1025,0,0", contentMatrix.Text); Mouse.Scroll(-1); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("1.05,0,0,1.05,0,0", contentMatrix.Text); Mouse.Scroll(-1); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("Identity", contentMatrix.Text); } [Test] public void MouseWheelTopLeftExplicitWheelZoomFactor() { using var app = Application.Launch("Gu.Wpf.Geometry.Demo.exe", WindowName); var window = app.MainWindow; window.FindTextBox("WheelZoomFactor").Text = "1.1"; window.FindButton("None").Click(); var renderSize = window.FindTextBlock("Size"); var contentMatrix = window.FindTextBlock("ContentMatrix"); Mouse.Position = window.FindGroupBox("Zoombox").Bounds.TopLeft + new Vector(1, 1); Assert.AreEqual("Identity", contentMatrix.Text); Mouse.Scroll(1); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("1.1,0,0,1.1,0,0", contentMatrix.Text); Mouse.Scroll(1); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("1.21,0,0,1.21,0,0", contentMatrix.Text); Mouse.Scroll(-1); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("1.1,0,0,1.1,0,0", contentMatrix.Text); Mouse.Scroll(-1); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("Identity", contentMatrix.Text); } [Test] public void MouseWheelTopRight() { using var app = Application.AttachOrLaunch("Gu.Wpf.Geometry.Demo.exe", WindowName); var window = app.MainWindow; var renderSize = window.FindTextBlock("Size"); var contentMatrix = window.FindTextBlock("ContentMatrix"); Mouse.Position = window.FindGroupBox("Zoombox").Bounds.TopRight + new Vector(-1, 1); Assert.AreEqual("Identity", contentMatrix.Text); Mouse.Scroll(1); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("1.05,0,0,1.05,-19.3,0", contentMatrix.Text); Mouse.Scroll(1); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("1.1025,0,0,1.1025,-39.565,0", contentMatrix.Text); Mouse.Scroll(-1); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("1.05,0,0,1.05,-19.3,0", contentMatrix.Text); Mouse.Scroll(-1); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("1,0,0,1,0,0", contentMatrix.Text); } [Test] public void MouseWheelBottomRight() { using var app = Application.AttachOrLaunch("Gu.Wpf.Geometry.Demo.exe", WindowName); var window = app.MainWindow; var renderSize = window.FindTextBlock("Size"); var contentMatrix = window.FindTextBlock("ContentMatrix"); Mouse.Position = window.FindGroupBox("Zoombox").Bounds.BottomRight + new Vector(-1, -1); Assert.AreEqual("Identity", contentMatrix.Text); Mouse.Scroll(1); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("1.05,0,0,1.05,-19.3,-12.4", contentMatrix.Text); Mouse.Scroll(1); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("1.1025,0,0,1.1025,-39.565,-25.42", contentMatrix.Text); Mouse.Scroll(-1); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("1.05,0,0,1.05,-19.3,-12.4", contentMatrix.Text); Mouse.Scroll(-1); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("1,0,0,1,0,-0", contentMatrix.Text); } [Test] public void MouseWheelBottomLeft() { using var app = Application.AttachOrLaunch("Gu.Wpf.Geometry.Demo.exe", WindowName); var window = app.MainWindow; var renderSize = window.FindTextBlock("Size"); var contentMatrix = window.FindTextBlock("ContentMatrix"); Mouse.Position = window.FindGroupBox("Zoombox").Bounds.BottomLeft + new Vector(1, -1); Assert.AreEqual("Identity", contentMatrix.Text); Mouse.Scroll(1); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("1.05,0,0,1.05,0,-12.4", contentMatrix.Text); Mouse.Scroll(1); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("1.1025,0,0,1.1025,0,-25.42", contentMatrix.Text); Mouse.Scroll(-1); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("1.05,0,0,1.05,0,-12.4", contentMatrix.Text); Mouse.Scroll(-1); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("1,0,0,1,0,-0", contentMatrix.Text); } [Test] public void MouseWheelCenter() { using var app = Application.AttachOrLaunch("Gu.Wpf.Geometry.Demo.exe", WindowName); var window = app.MainWindow; var renderSize = window.FindTextBlock("Size"); var contentMatrix = window.FindTextBlock("ContentMatrix"); Mouse.Position = window.FindGroupBox("Zoombox").Bounds.Center(); Assert.AreEqual("Identity", contentMatrix.Text); Mouse.Scroll(1); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("1.05,0,0,1.05,-9.65,-6.2", contentMatrix.Text); Mouse.Scroll(1); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("1.1025,0,0,1.1025,-19.7825,-12.71", contentMatrix.Text); Mouse.Scroll(-1); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("1.05,0,0,1.05,-9.65,-6.2", contentMatrix.Text); Mouse.Scroll(-1); Assert.AreEqual("386, 248", renderSize.Text); Assert.AreEqual("1,0,0,1,0,-0", contentMatrix.Text); } [Test] public void SetsToUniformInCodeBehind() { using var app = Application.Launch("Gu.Wpf.Geometry.Demo.exe", "ZoomboxContentChanged"); var window = app.MainWindow; Wait.For(TimeSpan.FromMilliseconds(200)); window.FindButton("Uniform").Invoke(); var zoomBox = window.FindGroupBox("Zoom"); var imageSources = window.FindComboBox("ImageSources"); using var expected = zoomBox.Capture(); imageSources.SelectedIndex = 1; window.FindButton("UniformToFill").Invoke(); imageSources.SelectedIndex = 0; ImageAssert.AreEqual(expected, zoomBox); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Xunit; namespace Microsoft.AspNetCore.Mvc.FunctionalTests { public class AntiforgeryTests : IClassFixture<MvcTestFixture<BasicWebSite.StartupWithoutEndpointRouting>> { public AntiforgeryTests(MvcTestFixture<BasicWebSite.StartupWithoutEndpointRouting> fixture) { Client = fixture.CreateDefaultClient(); } public HttpClient Client { get; } [Fact] public async Task MultipleAFTokensWithinTheSamePage_GeneratesASingleCookieToken() { // Arrange & Act var response = await Client.GetAsync("http://localhost/Antiforgery/Login"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var header = Assert.Single(response.Headers.GetValues("X-Frame-Options")); Assert.Equal("SAMEORIGIN", header); var setCookieHeader = response.Headers.GetValues("Set-Cookie").ToArray(); // Even though there are two forms there should only be one response cookie, // as for the second form, the cookie from the first token should be reused. Assert.Single(setCookieHeader); Assert.True(response.Headers.CacheControl.NoCache); var pragmaValue = Assert.Single(response.Headers.Pragma.ToArray()); Assert.Equal("no-cache", pragmaValue.Name); } [Fact] public async Task MultipleFormPostWithingASingleView_AreAllowed() { // Arrange // Do a get request. var getResponse = await Client.GetAsync("http://localhost/Antiforgery/Login"); var responseBody = await getResponse.Content.ReadAsStringAsync(); // Get the AF token for the second login. If the cookies are generated twice(i.e are different), // this AF token will not work with the first cookie. var formToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken( responseBody, "/Antiforgery/UseFacebookLogin"); var cookieToken = AntiforgeryTestHelper.RetrieveAntiforgeryCookie(getResponse); var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Antiforgery/Login"); request.Headers.Add("Cookie", cookieToken.Key + "=" + cookieToken.Value); var nameValueCollection = new List<KeyValuePair<string, string>> { new KeyValuePair<string,string>("__RequestVerificationToken", formToken), new KeyValuePair<string,string>("UserName", "abra"), new KeyValuePair<string,string>("Password", "cadabra"), }; request.Content = new FormUrlEncodedContent(nameValueCollection); // Act var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("OK", await response.Content.ReadAsStringAsync()); } [Fact] public async Task SetCookieAndHeaderBeforeFlushAsync_GeneratesCookieTokenAndHeader() { // Arrange & Act var response = await Client.GetAsync("http://localhost/Antiforgery/FlushAsyncLogin"); // Assert var header = Assert.Single(response.Headers.GetValues("X-Frame-Options")); Assert.Equal("SAMEORIGIN", header); var setCookieHeader = response.Headers.GetValues("Set-Cookie").ToArray(); Assert.Single(setCookieHeader); Assert.True(response.Headers.CacheControl.NoCache); var pragmaValue = Assert.Single(response.Headers.Pragma.ToArray()); Assert.Equal("no-cache", pragmaValue.Name); } [Fact] public async Task SetCookieAndHeaderBeforeFlushAsync_PostToForm() { // Arrange // do a get response. var getResponse = await Client.GetAsync("http://localhost/Antiforgery/FlushAsyncLogin"); var responseBody = await getResponse.Content.ReadAsStringAsync(); var formToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken( responseBody, "Antiforgery/FlushAsyncLogin"); var cookieToken = AntiforgeryTestHelper.RetrieveAntiforgeryCookie(getResponse); var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Antiforgery/FlushAsyncLogin"); request.Headers.Add("Cookie", cookieToken.Key + "=" + cookieToken.Value); var nameValueCollection = new List<KeyValuePair<string, string>> { new KeyValuePair<string,string>("__RequestVerificationToken", formToken), new KeyValuePair<string,string>("UserName", "test"), new KeyValuePair<string,string>("Password", "password"), }; request.Content = new FormUrlEncodedContent(nameValueCollection); // Act var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("OK", await response.Content.ReadAsStringAsync()); } [Fact] public async Task Antiforgery_HeaderNotSet_SendsBadRequest() { // Arrange var getResponse = await Client.GetAsync("http://localhost/Antiforgery/Login"); var responseBody = await getResponse.Content.ReadAsStringAsync(); var formToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken( responseBody, "Antiforgery/Login"); var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Antiforgery/Login"); var nameValueCollection = new List<KeyValuePair<string, string>> { new KeyValuePair<string,string>("__RequestVerificationToken", formToken), new KeyValuePair<string,string>("UserName", "test"), new KeyValuePair<string,string>("Password", "password"), }; request.Content = new FormUrlEncodedContent(nameValueCollection); // Act var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); } [Fact] public async Task AntiforgeryTokenGeneration_SetsDoNotCacheHeaders_OverridesExistingCachingHeaders() { // Arrange & Act var response = await Client.GetAsync("http://localhost/Antiforgery/AntiforgeryTokenAndResponseCaching"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var header = Assert.Single(response.Headers.GetValues("X-Frame-Options")); Assert.Equal("SAMEORIGIN", header); var setCookieHeader = response.Headers.GetValues("Set-Cookie").ToArray(); // Even though there are two forms there should only be one response cookie, // as for the second form, the cookie from the first token should be reused. Assert.Single(setCookieHeader); Assert.True(response.Headers.CacheControl.NoCache); var pragmaValue = Assert.Single(response.Headers.Pragma.ToArray()); Assert.Equal("no-cache", pragmaValue.Name); } [Fact] public async Task RequestWithoutAntiforgeryToken_SendsBadRequest() { // Arrange var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Antiforgery/Login"); // Act var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); } [Fact] public async Task RequestWithoutAntiforgeryToken_ExecutesResultFilter() { // Arrange var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Antiforgery/LoginWithRedirectResultFilter"); // Act var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); Assert.Equal("http://example.com/antiforgery-redirect", response.Headers.Location.AbsoluteUri); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; namespace System { [Serializable] [CLSCompliant(false)] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct UInt32 : IComparable, IConvertible, IFormattable, IComparable<uint>, IEquatable<uint>, ISpanFormattable { private readonly uint m_value; // Do not rename (binary serialization) public const uint MaxValue = (uint)0xffffffff; public const uint MinValue = 0U; // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type UInt32, this method throws an ArgumentException. // public int CompareTo(object? value) { if (value == null) { return 1; } // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. if (value is uint i) { if (m_value < i) return -1; if (m_value > i) return 1; return 0; } throw new ArgumentException(SR.Arg_MustBeUInt32); } public int CompareTo(uint value) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. if (m_value < value) return -1; if (m_value > value) return 1; return 0; } public override bool Equals(object? obj) { if (!(obj is uint)) { return false; } return m_value == ((uint)obj).m_value; } [NonVersionable] public bool Equals(uint obj) { return m_value == obj; } // The absolute value of the int contained. public override int GetHashCode() { return (int)m_value; } // The base 10 representation of the number with no extra padding. public override string ToString() { return Number.UInt32ToDecStr(m_value, -1); } public string ToString(IFormatProvider? provider) { return Number.FormatUInt32(m_value, null, provider); } public string ToString(string? format) { return Number.FormatUInt32(m_value, format, null); } public string ToString(string? format, IFormatProvider? provider) { return Number.FormatUInt32(m_value, format, provider); } public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider? provider = null) { return Number.TryFormatUInt32(m_value, format, provider, destination, out charsWritten); } [CLSCompliant(false)] public static uint Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseUInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } [CLSCompliant(false)] public static uint Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseUInt32(s, style, NumberFormatInfo.CurrentInfo); } [CLSCompliant(false)] public static uint Parse(string s, IFormatProvider? provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseUInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } [CLSCompliant(false)] public static uint Parse(string s, NumberStyles style, IFormatProvider? provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseUInt32(s, style, NumberFormatInfo.GetInstance(provider)); } [CLSCompliant(false)] public static uint Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider? provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.ParseUInt32(s, style, NumberFormatInfo.GetInstance(provider)); } [CLSCompliant(false)] public static bool TryParse(string? s, out uint result) { if (s == null) { result = 0; return false; } return Number.TryParseUInt32IntegerStyle(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result) == Number.ParsingStatus.OK; } [CLSCompliant(false)] public static bool TryParse(ReadOnlySpan<char> s, out uint result) { return Number.TryParseUInt32IntegerStyle(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result) == Number.ParsingStatus.OK; } [CLSCompliant(false)] public static bool TryParse(string? s, NumberStyles style, IFormatProvider? provider, out uint result) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { result = 0; return false; } return Number.TryParseUInt32(s, style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK; } [CLSCompliant(false)] public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider? provider, out uint result) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.TryParseUInt32(s, style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK; } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.UInt32; } bool IConvertible.ToBoolean(IFormatProvider? provider) { return Convert.ToBoolean(m_value); } char IConvertible.ToChar(IFormatProvider? provider) { return Convert.ToChar(m_value); } sbyte IConvertible.ToSByte(IFormatProvider? provider) { return Convert.ToSByte(m_value); } byte IConvertible.ToByte(IFormatProvider? provider) { return Convert.ToByte(m_value); } short IConvertible.ToInt16(IFormatProvider? provider) { return Convert.ToInt16(m_value); } ushort IConvertible.ToUInt16(IFormatProvider? provider) { return Convert.ToUInt16(m_value); } int IConvertible.ToInt32(IFormatProvider? provider) { return Convert.ToInt32(m_value); } uint IConvertible.ToUInt32(IFormatProvider? provider) { return m_value; } long IConvertible.ToInt64(IFormatProvider? provider) { return Convert.ToInt64(m_value); } ulong IConvertible.ToUInt64(IFormatProvider? provider) { return Convert.ToUInt64(m_value); } float IConvertible.ToSingle(IFormatProvider? provider) { return Convert.ToSingle(m_value); } double IConvertible.ToDouble(IFormatProvider? provider) { return Convert.ToDouble(m_value); } decimal IConvertible.ToDecimal(IFormatProvider? provider) { return Convert.ToDecimal(m_value); } DateTime IConvertible.ToDateTime(IFormatProvider? provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "UInt32", "DateTime")); } object IConvertible.ToType(Type type, IFormatProvider? provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
// // Copyright (c) 2004-2021 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. // namespace NLog.Targets.Wrappers { using System; using System.ComponentModel; using System.Threading; using NLog.Common; using NLog.Internal; /// <summary> /// Provides asynchronous, buffered execution of target writes. /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/AsyncWrapper-target">Documentation on NLog Wiki</seealso> /// <remarks> /// <p> /// Asynchronous target wrapper allows the logger code to execute more quickly, by queueing /// messages and processing them in a separate thread. You should wrap targets /// that spend a non-trivial amount of time in their Write() method with asynchronous /// target to speed up logging. /// </p> /// <p> /// Because asynchronous logging is quite a common scenario, NLog supports a /// shorthand notation for wrapping all targets with AsyncWrapper. Just add async="true" to /// the &lt;targets/&gt; element in the configuration file. /// </p> /// <code lang="XML"> /// <![CDATA[ /// <targets async="true"> /// ... your targets go here ... /// </targets> /// ]]></code> /// </remarks> /// <example> /// <p> /// To set up the target in the <a href="config.html">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/AsyncWrapper/NLog.config" /> /// <p> /// The above examples assume just one target and a single rule. See below for /// a programmatic configuration that's equivalent to the above config file: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/AsyncWrapper/Wrapping File/Example.cs" /> /// </example> [Target("AsyncWrapper", IsWrapper = true)] public class AsyncTargetWrapper : WrapperTargetBase { private readonly object _writeLockObject = new object(); private readonly object _timerLockObject = new object(); private Timer _lazyWriterTimer; private readonly ReusableAsyncLogEventList _reusableAsyncLogEventList = new ReusableAsyncLogEventList(200); private event EventHandler<LogEventDroppedEventArgs> _logEventDroppedEvent; private event EventHandler<LogEventQueueGrowEventArgs> _eventQueueGrowEvent; /// <summary> /// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class. /// </summary> public AsyncTargetWrapper() : this(null) { } /// <summary> /// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class. /// </summary> /// <param name="name">Name of the target.</param> /// <param name="wrappedTarget">The wrapped target.</param> public AsyncTargetWrapper(string name, Target wrappedTarget) : this(wrappedTarget) { Name = name; } /// <summary> /// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class. /// </summary> /// <param name="wrappedTarget">The wrapped target.</param> public AsyncTargetWrapper(Target wrappedTarget) : this(wrappedTarget, 10000, AsyncTargetWrapperOverflowAction.Discard) { } /// <summary> /// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class. /// </summary> /// <param name="wrappedTarget">The wrapped target.</param> /// <param name="queueLimit">Maximum number of requests in the queue.</param> /// <param name="overflowAction">The action to be taken when the queue overflows.</param> public AsyncTargetWrapper(Target wrappedTarget, int queueLimit, AsyncTargetWrapperOverflowAction overflowAction) { #if NETSTANDARD2_0 // NetStandard20 includes many optimizations for ConcurrentQueue: // - See: https://blogs.msdn.microsoft.com/dotnet/2017/06/07/performance-improvements-in-net-core/ // Net40 ConcurrencyQueue can seem to leak, because it doesn't clear properly on dequeue // - See: https://blogs.msdn.microsoft.com/pfxteam/2012/05/08/concurrentqueuet-holding-on-to-a-few-dequeued-elements/ _requestQueue = new ConcurrentRequestQueue(10000, AsyncTargetWrapperOverflowAction.Discard); #else _requestQueue = new AsyncRequestQueue(10000, AsyncTargetWrapperOverflowAction.Discard); #endif TimeToSleepBetweenBatches = 1; BatchSize = 200; FullBatchSizeWriteLimit = 5; WrappedTarget = wrappedTarget; QueueLimit = queueLimit; OverflowAction = overflowAction; } /// <summary> /// Gets or sets the number of log events that should be processed in a batch /// by the lazy writer thread. /// </summary> /// <docgen category='Buffering Options' order='100' /> [DefaultValue(200)] public int BatchSize { get; set; } /// <summary> /// Gets or sets the time in milliseconds to sleep between batches. (1 or less means trigger on new activity) /// </summary> /// <docgen category='Buffering Options' order='100' /> [DefaultValue(1)] public int TimeToSleepBetweenBatches { get; set; } /// <summary> /// Raise event when Target cannot store LogEvent. /// Event arg contains lost LogEvents /// </summary> public event EventHandler<LogEventDroppedEventArgs> LogEventDropped { add { if (_logEventDroppedEvent == null && _requestQueue != null ) { _requestQueue.LogEventDropped += OnRequestQueueDropItem; } _logEventDroppedEvent += value; } remove { _logEventDroppedEvent -= value; if (_logEventDroppedEvent == null && _requestQueue != null) { _requestQueue.LogEventDropped -= OnRequestQueueDropItem; } } } /// <summary> /// Raises when event queue grow. /// Queue can grow when <see cref="OverflowAction"/> was set to <see cref="AsyncTargetWrapperOverflowAction.Grow"/> /// </summary> public event EventHandler<LogEventQueueGrowEventArgs> EventQueueGrow { add { if (_eventQueueGrowEvent == null && _requestQueue != null) { _requestQueue.LogEventQueueGrow += OnRequestQueueGrow; } _eventQueueGrowEvent += value; } remove { _eventQueueGrowEvent -= value; if (_eventQueueGrowEvent == null && _requestQueue != null) { _requestQueue.LogEventQueueGrow -= OnRequestQueueGrow; } } } /// <summary> /// Gets or sets the action to be taken when the lazy writer thread request queue count /// exceeds the set limit. /// </summary> /// <docgen category='Buffering Options' order='100' /> [DefaultValue("Discard")] public AsyncTargetWrapperOverflowAction OverflowAction { get => _requestQueue.OnOverflow; set => _requestQueue.OnOverflow = value; } /// <summary> /// Gets or sets the limit on the number of requests in the lazy writer thread request queue. /// </summary> /// <docgen category='Buffering Options' order='100' /> [DefaultValue(10000)] public int QueueLimit { get => _requestQueue.RequestLimit; set => _requestQueue.RequestLimit = value; } /// <summary> /// Gets or sets the limit of full <see cref="BatchSize"/>s to write before yielding into <see cref="TimeToSleepBetweenBatches"/> /// Performance is better when writing many small batches, than writing a single large batch /// </summary> /// <docgen category='Buffering Options' order='100' /> [DefaultValue(5)] public int FullBatchSizeWriteLimit { get; set; } /// <summary> /// Gets or sets whether to use the locking queue, instead of a lock-free concurrent queue /// The locking queue is less concurrent when many logger threads, but reduces memory allocation /// </summary> /// <docgen category='Buffering Options' order='100' /> [DefaultValue(false)] public bool ForceLockingQueue { get => _forceLockingQueue ?? false; set => _forceLockingQueue = value; } private bool? _forceLockingQueue; /// <summary> /// Gets the queue of lazy writer thread requests. /// </summary> AsyncRequestQueueBase _requestQueue; /// <summary> /// Schedules a flush of pending events in the queue (if any), followed by flushing the WrappedTarget. /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> protected override void FlushAsync(AsyncContinuation asyncContinuation) { if (_flushEventsInQueueDelegate == null) _flushEventsInQueueDelegate = new AsyncHelpersTask(FlushEventsInQueue); AsyncHelpers.StartAsyncTask(_flushEventsInQueueDelegate.Value, asyncContinuation); } private AsyncHelpersTask? _flushEventsInQueueDelegate; /// <summary> /// Initializes the target by starting the lazy writer timer. /// </summary> protected override void InitializeTarget() { base.InitializeTarget(); if (!OptimizeBufferReuse && WrappedTarget != null && WrappedTarget.OptimizeBufferReuse) { OptimizeBufferReuse = GetType() == typeof(AsyncTargetWrapper); // Class not sealed, reduce breaking changes if (!OptimizeBufferReuse && !ForceLockingQueue) { ForceLockingQueue = true; // Avoid too much allocation, when wrapping a legacy target } } if (!ForceLockingQueue && OverflowAction == AsyncTargetWrapperOverflowAction.Block && BatchSize * 1.5m > QueueLimit) { ForceLockingQueue = true; // ConcurrentQueue does not perform well if constantly hitting QueueLimit } #if NET4_5 || NET4_0 if (_forceLockingQueue.HasValue && _forceLockingQueue.Value != (_requestQueue is AsyncRequestQueue)) { _requestQueue = ForceLockingQueue ? (AsyncRequestQueueBase)new AsyncRequestQueue(QueueLimit, OverflowAction) : new ConcurrentRequestQueue(QueueLimit, OverflowAction); } #endif if (BatchSize > QueueLimit && TimeToSleepBetweenBatches <= 1) { BatchSize = QueueLimit; // Avoid too much throttling } _requestQueue.Clear(); InternalLogger.Trace("AsyncWrapper(Name={0}): Start Timer", Name); _lazyWriterTimer = new Timer(ProcessPendingEvents, null, Timeout.Infinite, Timeout.Infinite); StartLazyWriterTimer(); } /// <summary> /// Shuts down the lazy writer timer. /// </summary> protected override void CloseTarget() { StopLazyWriterThread(); if (Monitor.TryEnter(_writeLockObject, 500)) { try { WriteEventsInQueue(int.MaxValue, "Closing Target"); } finally { Monitor.Exit(_writeLockObject); } } if (OverflowAction == AsyncTargetWrapperOverflowAction.Block) { _requestQueue.Clear(); // Try to eject any threads, that are blocked in the RequestQueue } base.CloseTarget(); } /// <summary> /// Starts the lazy writer thread which periodically writes /// queued log messages. /// </summary> protected virtual void StartLazyWriterTimer() { lock (_timerLockObject) { if (_lazyWriterTimer != null) { if (TimeToSleepBetweenBatches <= 1) { InternalLogger.Trace("AsyncWrapper(Name={0}): Throttled timer scheduled", Name); _lazyWriterTimer.Change(1, Timeout.Infinite); } else { _lazyWriterTimer.Change(TimeToSleepBetweenBatches, Timeout.Infinite); } } } } /// <summary> /// Attempts to start an instant timer-worker-thread which can write /// queued log messages. /// </summary> /// <returns>Returns true when scheduled a timer-worker-thread</returns> protected virtual bool StartInstantWriterTimer() { return StartTimerUnlessWriterActive(true); } private bool StartTimerUnlessWriterActive(bool instant) { bool lockTaken = false; try { lockTaken = Monitor.TryEnter(_writeLockObject); if (lockTaken) { // Lock taken means no other timer-worker-thread is trying to write, schedule timer now if (instant) { lock (_timerLockObject) { if (_lazyWriterTimer != null) { // Not optimal to schedule timer-worker-thread while holding lock, // as the newly scheduled timer-worker-thread will hammer into the writeLockObject _lazyWriterTimer.Change(0, Timeout.Infinite); return true; } } } else { StartLazyWriterTimer(); return true; } } } finally { // If not able to take lock, then it means timer-worker-thread is already active, // and timer-worker-thread will check RequestQueue after leaving writeLockObject if (lockTaken) Monitor.Exit(_writeLockObject); } return false; } /// <summary> /// Stops the lazy writer thread. /// </summary> protected virtual void StopLazyWriterThread() { lock (_timerLockObject) { var currentTimer = _lazyWriterTimer; if (currentTimer != null) { _lazyWriterTimer = null; currentTimer.WaitForDispose(TimeSpan.FromSeconds(1)); } } } /// <summary> /// Adds the log event to asynchronous queue to be processed by /// the lazy writer thread. /// </summary> /// <param name="logEvent">The log event.</param> /// <remarks> /// The <see cref="Target.PrecalculateVolatileLayouts"/> is called /// to ensure that the log event can be processed in another thread. /// </remarks> protected override void Write(AsyncLogEventInfo logEvent) { PrecalculateVolatileLayouts(logEvent.LogEvent); bool queueWasEmpty = _requestQueue.Enqueue(logEvent); if (queueWasEmpty) { if (TimeToSleepBetweenBatches == 0) StartInstantWriterTimer(); else if (TimeToSleepBetweenBatches <= 1) StartLazyWriterTimer(); } } /// <summary> /// Write to queue without locking <see cref="Target.SyncRoot"/> /// </summary> /// <param name="logEvent"></param> protected override void WriteAsyncThreadSafe(AsyncLogEventInfo logEvent) { try { Write(logEvent); } catch (Exception exception) { if (ExceptionMustBeRethrown(exception)) { throw; } logEvent.Continuation(exception); } } private void ProcessPendingEvents(object state) { if (_lazyWriterTimer == null) return; bool wroteFullBatchSize = false; try { lock (_writeLockObject) { int count = WriteEventsInQueue(BatchSize, "Timer"); if (count == BatchSize) wroteFullBatchSize = true; if (wroteFullBatchSize && TimeToSleepBetweenBatches <= 1) StartInstantWriterTimer(); // Found full batch, fast schedule to take next batch (within lock to avoid pile up) } } catch (Exception exception) { wroteFullBatchSize = false; // Something went wrong, lets throttle retry InternalLogger.Error(exception, "AsyncWrapper(Name={0}): Error in lazy writer timer procedure.", Name); if (exception.MustBeRethrownImmediately()) { throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior) } } finally { if (TimeToSleepBetweenBatches <= 1) { if (!wroteFullBatchSize && !_requestQueue.IsEmpty) { // If queue was not empty, then more might have arrived while writing the first batch // Do not use instant timer, so we can process in larger batches (faster) StartTimerUnlessWriterActive(false); } } else { StartLazyWriterTimer(); } } } private void FlushEventsInQueue(object state) { try { var asyncContinuation = state as AsyncContinuation; lock (_writeLockObject) { WriteEventsInQueue(int.MaxValue, "Flush Async"); if (asyncContinuation != null) base.FlushAsync(asyncContinuation); } if (TimeToSleepBetweenBatches <= 1 && !_requestQueue.IsEmpty) StartTimerUnlessWriterActive(false); } catch (Exception exception) { InternalLogger.Error(exception, "AsyncWrapper(Name={0}): Error in flush procedure.", Name); if (exception.MustBeRethrownImmediately()) { throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior) } } } private int WriteEventsInQueue(int batchSize, string reason) { if (WrappedTarget == null) { InternalLogger.Error("AsyncWrapper(Name={0}): WrappedTarget is NULL", Name); return 0; } int count = 0; for (int i = 0; i < FullBatchSizeWriteLimit; ++i) { if (!OptimizeBufferReuse || batchSize == int.MaxValue) { var logEvents = _requestQueue.DequeueBatch(batchSize); if (logEvents.Length > 0) { if (reason != null) InternalLogger.Trace("AsyncWrapper(Name={0}): Writing {1} events ({2})", Name, logEvents.Length, reason); WrappedTarget.WriteAsyncLogEvents(logEvents); } count = logEvents.Length; } else { using (var targetList = _reusableAsyncLogEventList.Allocate()) { var logEvents = targetList.Result; _requestQueue.DequeueBatch(batchSize, logEvents); if (logEvents.Count > 0) { if (reason != null) InternalLogger.Trace("AsyncWrapper(Name={0}): Writing {1} events ({2})", Name, logEvents.Count, reason); WrappedTarget.WriteAsyncLogEvents(logEvents); } count = logEvents.Count; } } if (count < batchSize) break; } return count; } private void OnRequestQueueDropItem(object sender, LogEventDroppedEventArgs logEventDroppedEventArgs) { _logEventDroppedEvent?.Invoke(this, logEventDroppedEventArgs); } private void OnRequestQueueGrow(object sender, LogEventQueueGrowEventArgs logEventQueueGrowEventArgs) { _eventQueueGrowEvent?.Invoke(this, logEventQueueGrowEventArgs); } } }
using System.Collections.Generic; using System.IO; using Xunit; using Moq; using System.Threading.Tasks; using System.Threading; using WireMock.Handlers; using WireMock.Owin.Mappers; using WireMock.ResponseBuilders; using WireMock.Types; using WireMock.Util; using WireMock.Owin; #if NET452 using Microsoft.Owin; using IResponse = Microsoft.Owin.IOwinResponse; using Response = Microsoft.Owin.OwinResponse; #else using Microsoft.AspNetCore.Http; using IResponse = Microsoft.AspNetCore.Http.HttpResponse; using Response = Microsoft.AspNetCore.Http.HttpResponse; using Microsoft.Extensions.Primitives; #endif namespace WireMock.Net.Tests.Owin.Mappers { public class OwinResponseMapperTests { private static readonly Task CompletedTask = Task.FromResult(true); private readonly OwinResponseMapper _sut; private readonly Mock<IResponse> _responseMock; private readonly Mock<Stream> _stream; private readonly Mock<IHeaderDictionary> _headers; private readonly Mock<IFileSystemHandler> _fileSystemHandlerMock; private readonly Mock<IWireMockMiddlewareOptions> _optionsMock; public OwinResponseMapperTests() { _stream = new Mock<Stream>(); _stream.SetupAllProperties(); _stream.Setup(s => s.WriteAsync(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<CancellationToken>())).Returns(CompletedTask); _fileSystemHandlerMock = new Mock<IFileSystemHandler>(); _fileSystemHandlerMock.SetupAllProperties(); _optionsMock = new Mock<IWireMockMiddlewareOptions>(); _optionsMock.SetupAllProperties(); _optionsMock.SetupGet(o => o.FileSystemHandler).Returns(_fileSystemHandlerMock.Object); _headers = new Mock<IHeaderDictionary>(); _headers.SetupAllProperties(); #if NET452 _headers.Setup(h => h.AppendValues(It.IsAny<string>(), It.IsAny<string[]>())); #else _headers.Setup(h => h.Add(It.IsAny<string>(), It.IsAny<StringValues>())); #endif _responseMock = new Mock<IResponse>(); _responseMock.SetupAllProperties(); _responseMock.SetupGet(r => r.Body).Returns(_stream.Object); _responseMock.SetupGet(r => r.Headers).Returns(_headers.Object); _sut = new OwinResponseMapper(_optionsMock.Object); } [Fact] public async Task OwinResponseMapper_MapAsync_Null() { // Act await _sut.MapAsync(null, _responseMock.Object).ConfigureAwait(false); } [Theory] [InlineData(300, 300)] [InlineData(500, 500)] public async Task OwinResponseMapper_MapAsync_Valid_StatusCode(object code, int expected) { // Arrange var responseMessage = new ResponseMessage { StatusCode = code }; // Act await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false); // Assert _responseMock.VerifySet(r => r.StatusCode = expected, Times.Once); } [Theory] [InlineData(0, 200)] [InlineData(-1, 200)] [InlineData(10000, 200)] [InlineData(300, 300)] public async Task OwinResponseMapper_MapAsync_Invalid_StatusCode_When_AllowOnlyDefinedHttpStatusCodeInResponseSet_Is_True(object code, int expected) { // Arrange _optionsMock.SetupGet(o => o.AllowOnlyDefinedHttpStatusCodeInResponse).Returns(true); var responseMessage = new ResponseMessage { StatusCode = code }; // Act await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false); // Assert _responseMock.VerifySet(r => r.StatusCode = expected, Times.Once); } [Fact] public async Task OwinResponseMapper_MapAsync_StatusCode_Is_Null() { // Arrange var responseMessage = new ResponseMessage { StatusCode = null }; // Act await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false); // Assert _responseMock.VerifySet(r => r.StatusCode = It.IsAny<int>(), Times.Never); } [Theory] [InlineData(0, 0)] [InlineData(-1, -1)] [InlineData(10000, 10000)] [InlineData(300, 300)] public async Task OwinResponseMapper_MapAsync_StatusCode_Is_NotInEnumRange(object code, int expected) { // Arrange var responseMessage = new ResponseMessage { StatusCode = code }; // Act await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false); // Assert _responseMock.VerifySet(r => r.StatusCode = expected, Times.Once); } [Fact] public async Task OwinResponseMapper_MapAsync_NoBody() { // Arrange var responseMessage = new ResponseMessage { Headers = new Dictionary<string, WireMockList<string>>() }; // Act await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false); // Assert _stream.Verify(s => s.WriteAsync(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<CancellationToken>()), Times.Never); } [Fact] public async Task OwinResponseMapper_MapAsync_Body() { // Arrange string body = "abcd"; var responseMessage = new ResponseMessage { Headers = new Dictionary<string, WireMockList<string>>(), BodyData = new BodyData { DetectedBodyType = BodyType.String, BodyAsString = body } }; // Act await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false); // Assert _stream.Verify(s => s.WriteAsync(new byte[] { 97, 98, 99, 100 }, 0, 4, It.IsAny<CancellationToken>()), Times.Once); } [Fact] public async Task OwinResponseMapper_MapAsync_BodyAsBytes() { // Arrange var bytes = new byte[] { 48, 49 }; var responseMessage = new ResponseMessage { Headers = new Dictionary<string, WireMockList<string>>(), BodyData = new BodyData { DetectedBodyType = BodyType.Bytes, BodyAsBytes = bytes } }; // Act await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false); // Assert _stream.Verify(s => s.WriteAsync(bytes, 0, bytes.Length, It.IsAny<CancellationToken>()), Times.Once); } [Fact] public async Task OwinResponseMapper_MapAsync_BodyAsJson() { // Arrange var json = new { t = "x", i = (string)null }; var responseMessage = new ResponseMessage { Headers = new Dictionary<string, WireMockList<string>>(), BodyData = new BodyData { DetectedBodyType = BodyType.Json, BodyAsJson = json, BodyAsJsonIndented = false } }; // Act await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false); // Assert _stream.Verify(s => s.WriteAsync(new byte[] { 123, 34, 116, 34, 58, 34, 120, 34, 125 }, 0, 9, It.IsAny<CancellationToken>()), Times.Once); } [Fact] public async Task OwinResponseMapper_MapAsync_SetResponseHeaders() { // Arrange var responseMessage = new ResponseMessage { Headers = new Dictionary<string, WireMockList<string>> { { "h", new WireMockList<string>("x", "y") } } }; // Act await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false); // Assert #if NET452 _headers.Verify(h => h.AppendValues("h", new string[] { "x", "y" }), Times.Once); #else var v = new StringValues(); _headers.Verify(h => h.TryGetValue("h", out v), Times.Once); #endif } [Fact] public async Task OwinResponseMapper_MapAsync_WithFault_EMPTY_RESPONSE() { // Arrange string body = "abc"; var responseMessage = new ResponseMessage { Headers = new Dictionary<string, WireMockList<string>>(), BodyData = new BodyData { DetectedBodyType = BodyType.String, BodyAsString = body }, FaultType = FaultType.EMPTY_RESPONSE }; // Act await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false); // Assert _stream.Verify(s => s.WriteAsync(new byte[0], 0, 0, It.IsAny<CancellationToken>()), Times.Once); } [Theory] [InlineData("abcd", BodyType.String)] [InlineData("", BodyType.String)] [InlineData(null, BodyType.None)] public async Task OwinResponseMapper_MapAsync_WithFault_MALFORMED_RESPONSE_CHUNK(string body, BodyType detected) { // Arrange var responseMessage = new ResponseMessage { Headers = new Dictionary<string, WireMockList<string>>(), BodyData = new BodyData { DetectedBodyType = detected, BodyAsString = body }, StatusCode = 100, FaultType = FaultType.MALFORMED_RESPONSE_CHUNK }; // Act await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false); // Assert _responseMock.VerifySet(r => r.StatusCode = 100, Times.Once); _stream.Verify(s => s.WriteAsync(It.IsAny<byte[]>(), 0, It.Is<int>(count => count >= 0), It.IsAny<CancellationToken>()), Times.Once); } } }
using System; using System.Collections.Generic; using System.Linq; using HaloSharp.Converter; using Newtonsoft.Json; namespace HaloSharp.Model.Halo5.Stats.Common { [Serializable] public class FlexibleStats : IEquatable<FlexibleStats> { [JsonProperty(PropertyName = "ImpulseStatCounts")] public List<StatCount> ImpulseStatCounts { get; set; } [JsonProperty(PropertyName = "ImpulseTimelapses")] public List<StatTimelapse> ImpulseTimelapses { get; set; } [JsonProperty(PropertyName = "MedalStatCounts")] public List<StatCount> MedalStatCounts { get; set; } [JsonProperty(PropertyName = "MedalTimelapses")] public List<StatTimelapse> MedalTimelapses { get; set; } public bool Equals(FlexibleStats other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return ImpulseStatCounts.OrderBy(isc => isc.Id).SequenceEqual(other.ImpulseStatCounts.OrderBy(isc => isc.Id)) && ImpulseTimelapses.OrderBy(it => it.Id).SequenceEqual(other.ImpulseTimelapses.OrderBy(it => it.Id)) && MedalStatCounts.OrderBy(msc => msc.Id).SequenceEqual(other.MedalStatCounts.OrderBy(msc => msc.Id)) && MedalTimelapses.OrderBy(mt => mt.Id).SequenceEqual(other.MedalTimelapses.OrderBy(mt => mt.Id)); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != typeof (FlexibleStats)) { return false; } return Equals((FlexibleStats) obj); } public override int GetHashCode() { unchecked { var hashCode = ImpulseStatCounts?.GetHashCode() ?? 0; hashCode = (hashCode*397) ^ (ImpulseTimelapses?.GetHashCode() ?? 0); hashCode = (hashCode*397) ^ (MedalStatCounts?.GetHashCode() ?? 0); hashCode = (hashCode*397) ^ (MedalTimelapses?.GetHashCode() ?? 0); return hashCode; } } public static bool operator ==(FlexibleStats left, FlexibleStats right) { return Equals(left, right); } public static bool operator !=(FlexibleStats left, FlexibleStats right) { return !Equals(left, right); } } [Serializable] public class StatTimelapse : IEquatable<StatTimelapse> { [JsonProperty(PropertyName = "Id")] public Guid Id { get; set; } [JsonProperty(PropertyName = "Timelapse")] [JsonConverter(typeof (TimeSpanConverter))] public TimeSpan Timelapse { get; set; } public bool Equals(StatTimelapse other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return Id.Equals(other.Id) && Timelapse.Equals(other.Timelapse); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != typeof (StatTimelapse)) { return false; } return Equals((StatTimelapse) obj); } public override int GetHashCode() { unchecked { return (Id.GetHashCode()*397) ^ Timelapse.GetHashCode(); } } public static bool operator ==(StatTimelapse left, StatTimelapse right) { return Equals(left, right); } public static bool operator !=(StatTimelapse left, StatTimelapse right) { return !Equals(left, right); } } [Serializable] public class StatCount : IEquatable<StatCount> { [JsonProperty(PropertyName = "Count")] public int Count { get; set; } [JsonProperty(PropertyName = "Id")] public Guid Id { get; set; } public bool Equals(StatCount other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return Count == other.Count && Id.Equals(other.Id); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != typeof (StatCount)) { return false; } return Equals((StatCount) obj); } public override int GetHashCode() { unchecked { return (Count*397) ^ Id.GetHashCode(); } } public static bool operator ==(StatCount left, StatCount right) { return Equals(left, right); } public static bool operator !=(StatCount left, StatCount right) { return !Equals(left, right); } } }
using System; using System.Globalization; using System.Linq; using System.Text; using GroupDocs.Viewer.Domain; using GroupDocs.Viewer.Domain.Containers; namespace MvcSample.Helpers { /// <summary> /// Class FileDataJsonSerializer. /// </summary> public class DocumentInfoJsonSerializer { /// <summary> /// The document info /// </summary> private readonly DocumentInfoContainer _documentInfo; /// <summary> /// The _options /// </summary> private readonly SerializationOptions _options; /// <summary> /// The _default culture /// </summary> private readonly CultureInfo _defaultCulture = CultureInfo.InvariantCulture; /// <summary> /// Two decimals places format /// </summary> private const string TwoDecimalPlacesFormat = "0.##"; /// <summary> /// Initializes a new instance of the <see cref="DocumentInfoContainer"/> class. /// </summary> /// <param name="documentInfo">The document info.</param> /// <param name="options">The options.</param> public DocumentInfoJsonSerializer(DocumentInfoContainer documentInfo, SerializationOptions options) { _documentInfo = documentInfo; _options = options; } /// <summary> /// Serializes this instance. /// </summary> /// <returns>System.String.</returns> public string Serialize() { if (_options.SupportListOfContentControls && _documentInfo.ContentControls.Any()) return SerializeWords(); var isCellsFileData = _documentInfo.Pages.Any(_ => !string.IsNullOrEmpty(_.Name)); if (isCellsFileData && _options.IsHtmlMode) return SerializeCells(); return SerializeDefault(); } /// <summary> /// Serializes the default. /// </summary> /// <returns>System.String.</returns> private string SerializeDefault() { StringBuilder json = new StringBuilder(); var maxWidth = 0; var maxHeight = 0; foreach (var pageData in _documentInfo.Pages) { if (pageData.Height > maxHeight) { maxHeight = pageData.Height; maxWidth = pageData.Width; } } json.Append("{\"pages\":["); int pageCount = _documentInfo.Pages.Count; for (int i = 0; i < pageCount; i++) { PageData pageData = _documentInfo.Pages[i]; bool needSeparator = i > 0; if (needSeparator) json.Append(","); AppendPage(pageData, json); bool includeRows = _options.UsePdf && pageData.Rows.Count > 0; if (includeRows) { json.Append(",\"rows\":["); for (int j = 0; j < pageData.Rows.Count; j++) { bool appendRowSeaparator = j != 0; if (appendRowSeaparator) json.Append(","); AppendRow(pageData.Rows[j], json); } json.Append("]"); // rows } json.Append("}"); // page } json.Append("]"); // pages json.Append(string.Format(",\"maxPageHeight\":{0},\"widthForMaxHeight\":{1}", maxHeight, maxWidth)); json.Append("}"); // document return json.ToString(); } /// <summary> /// Serializes cells. /// </summary> /// <returns>System.String.</returns> private string SerializeCells() { StringBuilder json = new StringBuilder(); json.Append("{\"sheets\":["); int pageCount = _documentInfo.Pages.Count; for (int i = 0; i < pageCount; i++) { PageData pageData = _documentInfo.Pages[i]; bool needSeparator = i > 0; if (needSeparator) json.Append(","); json.Append(string.Format("{{\"name\":\"{0}\"}}", pageData.Name)); } json.Append("]"); // pages json.Append("}"); // document return json.ToString(); } /// <summary> /// Serializes the specified words file data. /// </summary> /// <returns>System.String.</returns> private string SerializeWords() { StringBuilder json = new StringBuilder(); var maxWidth = 0; var maxHeight = 0; foreach (var pageData in _documentInfo.Pages) { if (pageData.Height > maxHeight) { maxHeight = pageData.Height; maxWidth = pageData.Width; } } json.Append("{\"pages\":["); int pageCount = _documentInfo.Pages.Count; for (int i = 0; i < pageCount; i++) { PageData pageData = _documentInfo.Pages[i]; bool needSeparator = pageData.Number >= 1; if (needSeparator) json.Append(","); AppendPage(pageData, json); json.Append("}"); // page } json.Append("]"); // pages if (_options.SupportListOfContentControls && _documentInfo.ContentControls.Any()) { json.Append(", \"contentControls\":["); bool needSeparator = false; foreach (ContentControl contentControl in _documentInfo.ContentControls) { if (needSeparator) json.Append(','); AppendContentControl(contentControl, json); needSeparator = true; } json.Append("]"); //contentControls } json.Append(string.Format(",\"maxPageHeight\":{0},\"widthForMaxHeight\":{1}", maxHeight, maxWidth)); json.Append("}"); //document return json.ToString(); } /// <summary> /// Appends the page. /// </summary> /// <param name="pageData">The page data.</param> /// <param name="json">The json.</param> private void AppendPage(PageData pageData, StringBuilder json) { if (pageData.Angle == 0) { json.Append(string.Format("{{\"w\":{0},\"h\":{1},\"number\":{2}", pageData.Width.ToString(_defaultCulture), pageData.Height.ToString(_defaultCulture), (pageData.Number).ToString(_defaultCulture))); } else { json.Append(string.Format("{{\"w\":{0},\"h\":{1},\"number\":{2},\"rotation\":{3}", pageData.Width.ToString(_defaultCulture), pageData.Height.ToString(_defaultCulture), (pageData.Number).ToString(_defaultCulture), pageData.Angle)); } } /// <summary> /// Appends the row. /// </summary> /// <param name="rowData">The row data.</param> /// <param name="json">The json.</param> private void AppendRow(RowData rowData, StringBuilder json) { string[] textCoordinates = new string[rowData.TextCoordinates.Count]; for (int i = 0; i < rowData.TextCoordinates.Count; i++) textCoordinates[i] = rowData.TextCoordinates[i].ToString(TwoDecimalPlacesFormat, _defaultCulture); string[] characterCoordinates = new string[rowData.CharacterCoordinates.Count]; for (int i = 0; i < rowData.CharacterCoordinates.Count; i++) characterCoordinates[i] = rowData.CharacterCoordinates[i].ToString(TwoDecimalPlacesFormat, _defaultCulture); json.Append(String.Format("{{\"l\":{0},\"t\":{1},\"w\":{2},\"h\":{3},\"c\":[{4}],\"s\":\"{5}\",\"ch\":[{6}]}}", rowData.LineLeft.ToString(TwoDecimalPlacesFormat, _defaultCulture), rowData.LineTop.ToString(TwoDecimalPlacesFormat, _defaultCulture), rowData.LineWidth.ToString(TwoDecimalPlacesFormat, _defaultCulture), rowData.LineHeight.ToString(TwoDecimalPlacesFormat, _defaultCulture), string.Join(",", textCoordinates), JsonEncode(rowData.Text), string.Join(",", characterCoordinates))); } /// <summary> /// Appends the content control. /// </summary> /// <param name="contentControl">The content control.</param> /// <param name="json">The json.</param> private void AppendContentControl(ContentControl contentControl, StringBuilder json) { json.Append(string.Format("{{\"title\":\"{0}\", \"startPage\":{1}, \"endPage\":{2}}}", JsonEncode(contentControl.Title), contentControl.StartPageNumber.ToString(_defaultCulture), contentControl.EndPageNumber.ToString(_defaultCulture))); } /// <summary> /// Jsons the encode. /// </summary> /// <param name="text">The text.</param> /// <returns>System.String.</returns> private string JsonEncode(string text) { if (string.IsNullOrEmpty(text)) return string.Empty; int i; int length = text.Length; StringBuilder stringBuilder = new StringBuilder(length + 4); for (i = 0; i < length; i += 1) { char c = text[i]; switch (c) { case '\\': case '"': case '/': stringBuilder.Append('\\'); stringBuilder.Append(c); break; case '\b': stringBuilder.Append("\\b"); break; case '\t': stringBuilder.Append("\\t"); break; case '\n': stringBuilder.Append("\\n"); break; case '\f': stringBuilder.Append("\\f"); break; case '\r': stringBuilder.Append("\\r"); break; default: if (c < ' ') { string t = "000" + Convert.ToByte(c).ToString("X"); stringBuilder.Append("\\u" + t.Substring(t.Length - 4)); } else { stringBuilder.Append(c); } break; } } return stringBuilder.ToString(); } } public class SerializationOptions { public bool UsePdf { get; set; } public bool IsHtmlMode { get; set; } public bool SupportListOfBookmarks { get; set; } public bool SupportListOfContentControls { get; set; } } }
/* * Copyright (c) 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.Runtime.InteropServices; namespace OpenMetaverse { /// <summary> /// An 8-bit color structure including an alpha channel /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Color4 : IComparable<Color4>, IEquatable<Color4> { /// <summary>Red</summary> public float R; /// <summary>Green</summary> public float G; /// <summary>Blue</summary> public float B; /// <summary>Alpha</summary> public float A; #region Constructors /// <summary> /// /// </summary> /// <param name="r"></param> /// <param name="g"></param> /// <param name="b"></param> /// <param name="a"></param> public Color4(byte r, byte g, byte b, byte a) { const float quanta = 1.0f / 255.0f; R = (float)r * quanta; G = (float)g * quanta; B = (float)b * quanta; A = (float)a * quanta; } public Color4(float r, float g, float b, float a) { // Quick check to see if someone is doing something obviously wrong // like using float values from 0.0 - 255.0 if (r > 1f || g > 1f || b > 1f || a > 1f) throw new ArgumentException( String.Format("Attempting to initialize Color4 with out of range values <{0},{1},{2},{3}>", r, g, b, a)); // Valid range is from 0.0 to 1.0 R = Utils.Clamp(r, 0f, 1f); G = Utils.Clamp(g, 0f, 1f); B = Utils.Clamp(b, 0f, 1f); A = Utils.Clamp(a, 0f, 1f); } /// <summary> /// Builds a color from a byte array /// </summary> /// <param name="byteArray">Byte array containing a 16 byte color</param> /// <param name="pos">Beginning position in the byte array</param> /// <param name="inverted">True if the byte array stores inverted values, /// otherwise false. For example the color black (fully opaque) inverted /// would be 0xFF 0xFF 0xFF 0x00</param> public Color4(byte[] byteArray, int pos, bool inverted) { R = G = B = A = 0f; FromBytes(byteArray, pos, inverted); } /// <summary> /// Returns the raw bytes for this vector /// </summary> /// <param name="byteArray">Byte array containing a 16 byte color</param> /// <param name="pos">Beginning position in the byte array</param> /// <param name="inverted">True if the byte array stores inverted values, /// otherwise false. For example the color black (fully opaque) inverted /// would be 0xFF 0xFF 0xFF 0x00</param> /// <param name="alphaInverted">True if the alpha value is inverted in /// addition to whatever the inverted parameter is. Setting inverted true /// and alphaInverted true will flip the alpha value back to non-inverted, /// but keep the other color bytes inverted</param> /// <returns>A 16 byte array containing R, G, B, and A</returns> public Color4(byte[] byteArray, int pos, bool inverted, bool alphaInverted) { R = G = B = A = 0f; FromBytes(byteArray, pos, inverted, alphaInverted); } /// <summary> /// Copy constructor /// </summary> /// <param name="color">Color to copy</param> public Color4(Color4 color) { R = color.R; G = color.G; B = color.B; A = color.A; } #endregion Constructors #region Public Methods /// <summary> /// IComparable.CompareTo implementation /// </summary> /// <remarks>Sorting ends up like this: |--Grayscale--||--Color--|. /// Alpha is only used when the colors are otherwise equivalent</remarks> public int CompareTo(Color4 color) { float thisHue = GetHue(); float thatHue = color.GetHue(); if (thisHue < 0f && thatHue < 0f) { // Both monochromatic if (R == color.R) { // Monochromatic and equal, compare alpha return A.CompareTo(color.A); } else { // Compare lightness return R.CompareTo(R); } } else { if (thisHue == thatHue) { // RGB is equal, compare alpha return A.CompareTo(color.A); } else { // Compare hues return thisHue.CompareTo(thatHue); } } } public void FromBytes(byte[] byteArray, int pos, bool inverted) { const float quanta = 1.0f / 255.0f; if (inverted) { R = (float)(255 - byteArray[pos]) * quanta; G = (float)(255 - byteArray[pos + 1]) * quanta; B = (float)(255 - byteArray[pos + 2]) * quanta; A = (float)(255 - byteArray[pos + 3]) * quanta; } else { R = (float)byteArray[pos] * quanta; G = (float)byteArray[pos + 1] * quanta; B = (float)byteArray[pos + 2] * quanta; A = (float)byteArray[pos + 3] * quanta; } } /// <summary> /// Builds a color from a byte array /// </summary> /// <param name="byteArray">Byte array containing a 16 byte color</param> /// <param name="pos">Beginning position in the byte array</param> /// <param name="inverted">True if the byte array stores inverted values, /// otherwise false. For example the color black (fully opaque) inverted /// would be 0xFF 0xFF 0xFF 0x00</param> /// <param name="alphaInverted">True if the alpha value is inverted in /// addition to whatever the inverted parameter is. Setting inverted true /// and alphaInverted true will flip the alpha value back to non-inverted, /// but keep the other color bytes inverted</param> public void FromBytes(byte[] byteArray, int pos, bool inverted, bool alphaInverted) { FromBytes(byteArray, pos, inverted); if (alphaInverted) A = 1.0f - A; } public byte[] GetBytes() { return GetBytes(false); } /// <summary> /// /// </summary> /// <returns></returns> public byte[] GetBytes(bool inverted) { byte[] byteArray = new byte[4]; byteArray[0] = Utils.FloatToByte(R, 0f, 1f); byteArray[1] = Utils.FloatToByte(G, 0f, 1f); byteArray[2] = Utils.FloatToByte(B, 0f, 1f); byteArray[3] = Utils.FloatToByte(A, 0f, 1f); if (inverted) { byteArray[0] = (byte)(255 - byteArray[0]); byteArray[1] = (byte)(255 - byteArray[1]); byteArray[2] = (byte)(255 - byteArray[2]); byteArray[3] = (byte)(255 - byteArray[3]); } return byteArray; } public byte[] GetFloatBytes() { byte[] bytes = new byte[16]; Buffer.BlockCopy(BitConverter.GetBytes(R), 0, bytes, 0, 4); Buffer.BlockCopy(BitConverter.GetBytes(G), 0, bytes, 4, 4); Buffer.BlockCopy(BitConverter.GetBytes(B), 0, bytes, 8, 4); Buffer.BlockCopy(BitConverter.GetBytes(A), 0, bytes, 12, 4); return bytes; } public float GetHue() { const float HUE_MAX = 360f; float max = Math.Max(Math.Max(R, G), B); float min = Math.Min(Math.Min(R, B), B); if (max == min) { // Achromatic, hue is undefined return -1f; } else { if (R == max) { float bDelta = (((max - B) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); float gDelta = (((max - G) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); return bDelta - gDelta; } else if (G == max) { float rDelta = (((max - R) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); float bDelta = (((max - B) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); return (HUE_MAX / 3f) + rDelta - bDelta; } else // B == max { float gDelta = (((max - G) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); float rDelta = (((max - R) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); return ((2f * HUE_MAX) / 3f) + gDelta - rDelta; } } } #endregion Public Methods #region Static Methods #endregion Static Methods #region Overrides public override string ToString() { return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}, {3}>", R, G, B, A); } public string ToRGBString() { return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}>", R, G, B); } public override bool Equals(object obj) { return (obj is Color4) ? this == (Color4)obj : false; } public bool Equals(Color4 other) { return this == other; } public override int GetHashCode() { return R.GetHashCode() ^ G.GetHashCode() ^ B.GetHashCode() ^ A.GetHashCode(); } #endregion Overrides #region Operators public static bool operator ==(Color4 lhs, Color4 rhs) { return (lhs.R == rhs.R) && (lhs.G == rhs.G) && (lhs.B == rhs.B) && (lhs.A == rhs.A); } public static bool operator !=(Color4 lhs, Color4 rhs) { return !(lhs == rhs); } #endregion Operators /// <summary>A Color4 with zero RGB values and full alpha (1.0)</summary> public readonly static Color4 Black = new Color4(0f, 0f, 0f, 1f); /// <summary>A Color4 with full RGB values (1.0) and full alpha (1.0)</summary> public readonly static Color4 White = new Color4(1f, 1f, 1f, 1f); } }
//--------------------------------------------------------------------------- // // <copyright file="PriorityBindingExpression.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: Defines PriorityBindingExpression object, which chooses a BindingExpression out // of a list of BindingExpressions in order of "priority" (and falls back // to the next BindingExpression as each BindingExpression fails) // // See spec at http://avalon/connecteddata/Specs/Data%20Binding.mht // //--------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.ObjectModel; // Collection<T> using System.Diagnostics; using System.Threading; using System.Windows.Controls; // ValidationStep using System.Windows.Threading; using System.Windows.Markup; using MS.Internal; using MS.Internal.Data; using MS.Utility; namespace System.Windows.Data { /// <summary> /// Describes a collection of BindingExpressions attached to a single property. /// These behave as "priority" BindingExpressions, meaning that the property /// receives its value from the first BindingExpression in the collection that /// can produce a legal value. /// </summary> public sealed class PriorityBindingExpression : BindingExpressionBase { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ private PriorityBindingExpression(PriorityBinding binding, BindingExpressionBase owner) : base(binding, owner) { } //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ /// <summary> Binding from which this expression was created </summary> public PriorityBinding ParentPriorityBinding { get { return (PriorityBinding)ParentBindingBase; } } /// <summary> List of inner BindingExpression </summary> public ReadOnlyCollection<BindingExpressionBase> BindingExpressions { get { return new ReadOnlyCollection<BindingExpressionBase>(MutableBindingExpressions); } } /// <summary> Returns the active BindingExpression (or null) </summary> public BindingExpressionBase ActiveBindingExpression { get { return (_activeIndex < 0) ? null : MutableBindingExpressions[_activeIndex]; } } /// <summary> /// HasValidationError returns true if any of the ValidationRules /// of any of its inner bindings failed its validation rule /// or the Multi-/PriorityBinding itself has a failing validation rule. /// </summary> public override bool HasValidationError { get { return (_activeIndex < 0) ? false : MutableBindingExpressions[_activeIndex].HasValidationError; } } //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ /// <summary> Force a data transfer from source to target </summary> public override void UpdateTarget() { BindingExpressionBase bindExpr = ActiveBindingExpression; if (bindExpr != null) { bindExpr.UpdateTarget(); } } /// <summary> Send the current value back to the source </summary> /// <remarks> Does nothing when binding's Mode is not TwoWay or OneWayToSource </remarks> public override void UpdateSource() { BindingExpressionBase bindExpr = ActiveBindingExpression; if (bindExpr != null) { bindExpr.UpdateSource(); } } #region Expression overrides /// <summary> /// Allows Expression to store set values /// </summary> /// <param name="d">DependencyObject being set</param> /// <param name="dp">Property being set</param> /// <param name="value">Value being set</param> /// <returns>true if Expression handled storing of the value</returns> internal override bool SetValue(DependencyObject d, DependencyProperty dp, object value) { bool result; BindingExpressionBase bindExpr = ActiveBindingExpression; if (bindExpr != null) { result = bindExpr.SetValue(d, dp, value); if (result) { // the active binding's value becomes the value of the priority binding Value = bindExpr.Value; AdoptProperties(bindExpr); NotifyCommitManager(); } } else { // If we couldn't find the active binding, just return true to keep the property // engine from removing the PriorityBinding. result = true; } return result; } #endregion Expression overrides //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ // Create a new BindingExpression from the given Binding description internal static PriorityBindingExpression CreateBindingExpression(DependencyObject d, DependencyProperty dp, PriorityBinding binding, BindingExpressionBase owner) { FrameworkPropertyMetadata fwMetaData = dp.GetMetadata(d.DependencyObjectType) as FrameworkPropertyMetadata; if ((fwMetaData != null && !fwMetaData.IsDataBindingAllowed) || dp.ReadOnly) throw new ArgumentException(SR.Get(SRID.PropertyNotBindable, dp.Name), "dp"); // create the BindingExpression PriorityBindingExpression bindExpr = new PriorityBindingExpression(binding, owner); return bindExpr; } //------------------------------------------------------ // // Protected Internal Properties // //------------------------------------------------------ /// <summary> /// Number of BindingExpressions that have been attached and are listening /// </summary> internal int AttentiveBindingExpressions { get { return (_activeIndex == NoActiveBindingExpressions) ? MutableBindingExpressions.Count : _activeIndex + 1; } } //------------------------------------------------------ // // Protected Internal Methods // //------------------------------------------------------ /// <summary> /// Attach a BindingExpression to the given target (element, property) /// </summary> /// <param name="d">DependencyObject being set</param> /// <param name="dp">Property being set</param> internal override bool AttachOverride(DependencyObject d, DependencyProperty dp) { if (!base.AttachOverride(d, dp)) return false; DependencyObject target = TargetElement; if (target == null) return false; SetStatus(BindingStatusInternal.Active); int count = ParentPriorityBinding.Bindings.Count; _activeIndex = NoActiveBindingExpressions; Debug.Assert(MutableBindingExpressions.Count == 0, "expect to encounter empty BindingExpression collection when attaching MultiBinding"); for (int i = 0; i < count; ++i) { AttachBindingExpression(i, false); // create new binding and have it added to end } return true; } /// <summary> sever all connections </summary> internal override void DetachOverride() { // Theoretically, we only need to detach number of AttentiveBindings, // but we'll traverse the whole list anyway and do aggressive clean-up. int count = MutableBindingExpressions.Count; for (int i = 0; i < count; ++i) { BindingExpressionBase b = MutableBindingExpressions[i]; if (b != null) b.Detach(); } ChangeSources(null); base.DetachOverride(); } /// <summary> /// Invalidate the given child expression. /// </summary> internal override void InvalidateChild(BindingExpressionBase bindingExpression) { // Prevent re-entrancy, because ChooseActiveBindingExpression() may // activate/deactivate a BindingExpression that indirectly calls this again. if (_isInInvalidateBinding) return; _isInInvalidateBinding = true; int index = MutableBindingExpressions.IndexOf(bindingExpression); DependencyObject target = TargetElement; if (target != null && 0 <= index && index < AttentiveBindingExpressions) { // Optimization: only look for new ActiveBindingExpression when necessary: // 1. it is a higher priority BindingExpression (or there's no ActiveBindingExpression), or // 2. the existing ActiveBindingExpression is broken if ( index != _activeIndex || (bindingExpression.StatusInternal != BindingStatusInternal.Active && !bindingExpression.UsingFallbackValue)) { ChooseActiveBindingExpression(target); } // update the value UsingFallbackValue = false; BindingExpressionBase bindExpr = ActiveBindingExpression; object newValue = (bindExpr != null) ? bindExpr.GetValue(target, TargetProperty) : UseFallbackValue(); ChangeValue(newValue, true); if (TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.Transfer)) { TraceData.Trace(TraceEventType.Warning, TraceData.PriorityTransfer( TraceData.Identify(this), TraceData.Identify(newValue), _activeIndex, TraceData.Identify(bindExpr))); } // don't invalidate during Attach. The property engine does it // already, and it would interfere with the on-demand activation // of style-defined BindingExpressions. if (!IsAttaching) { // recompute expression target.InvalidateProperty(TargetProperty); } } _isInInvalidateBinding = false; } /// <summary> /// Change the dependency sources for the given child expression. /// </summary> internal override void ChangeSourcesForChild(BindingExpressionBase bindingExpression, WeakDependencySource[] newSources) { int index = MutableBindingExpressions.IndexOf(bindingExpression); if (index >= 0) { WeakDependencySource[] combinedSources = CombineSources(index, MutableBindingExpressions, AttentiveBindingExpressions, newSources); ChangeSources(combinedSources); } } /// <summary> /// Replace the given child expression with a new one. /// </summary> internal override void ReplaceChild(BindingExpressionBase bindingExpression) { int index = MutableBindingExpressions.IndexOf(bindingExpression); DependencyObject target = TargetElement; if (index >= 0 && target != null) { // clean up the old BindingExpression bindingExpression.Detach(); // create a replacement BindingExpression and put it in the collection bindingExpression = AttachBindingExpression(index, true); } } // register the leaf bindings with the binding group internal override void UpdateBindingGroup(BindingGroup bg) { for (int i=0, n=MutableBindingExpressions.Count-1; i<n; ++i) { MutableBindingExpressions[i].UpdateBindingGroup(bg); } } /// <summary> /// Get the raw proposed value /// <summary> internal override object GetRawProposedValue() { BindingExpressionBase bindExpr = ActiveBindingExpression; if (bindExpr != null) { return bindExpr.GetRawProposedValue(); } return DependencyProperty.UnsetValue; } /// <summary> /// Get the converted proposed value /// <summary> internal override object ConvertProposedValue(object rawValue) { BindingExpressionBase bindExpr = ActiveBindingExpression; if (bindExpr != null) { return bindExpr.ConvertProposedValue(rawValue); } return DependencyProperty.UnsetValue; } /// <summary> /// Get the converted proposed value and inform the binding group /// <summary> internal override bool ObtainConvertedProposedValue(BindingGroup bindingGroup) { BindingExpressionBase bindExpr = ActiveBindingExpression; if (bindExpr != null) { return bindExpr.ObtainConvertedProposedValue(bindingGroup); } return true; } /// <summary> /// Update the source value /// <summary> internal override object UpdateSource(object convertedValue) { object result; BindingExpressionBase bindExpr = ActiveBindingExpression; if (bindExpr != null) { result = bindExpr.UpdateSource(convertedValue); if (bindExpr.StatusInternal == BindingStatusInternal.UpdateSourceError) { SetStatus(BindingStatusInternal.UpdateSourceError); } } else { result = DependencyProperty.UnsetValue; } return result; } /// <summary> /// Update the source value and inform the binding group /// <summary> internal override bool UpdateSource(BindingGroup bindingGroup) { bool result = true; BindingExpressionBase bindExpr = ActiveBindingExpression; if (bindExpr != null) { result = bindExpr.UpdateSource(bindingGroup); if (bindExpr.StatusInternal == BindingStatusInternal.UpdateSourceError) { SetStatus(BindingStatusInternal.UpdateSourceError); } } return result; } /// <summary> /// Store the value in the binding group /// </summary> internal override void StoreValueInBindingGroup(object value, BindingGroup bindingGroup) { BindingExpressionBase bindExpr = ActiveBindingExpression; if (bindExpr != null) { bindExpr.StoreValueInBindingGroup(value, bindingGroup); } } /// <summary> /// Run validation rules for the given step /// <summary> internal override bool Validate(object value, ValidationStep validationStep) { BindingExpressionBase bindExpr = ActiveBindingExpression; if (bindExpr != null) { return bindExpr.Validate(value, validationStep); } return true; } /// <summary> /// Run validation rules for the given step, and inform the binding group /// <summary> internal override bool CheckValidationRules(BindingGroup bindingGroup, ValidationStep validationStep) { BindingExpressionBase bindExpr = ActiveBindingExpression; if (bindExpr != null) { return bindExpr.CheckValidationRules(bindingGroup, validationStep); } return true; } /// <summary> /// Get the proposed value(s) that would be written to the source(s), applying /// conversion and checking UI-side validation rules. /// </summary> internal override bool ValidateAndConvertProposedValue(out Collection<ProposedValue> values) { Debug.Assert(NeedsValidation, "check NeedsValidation before calling this"); BindingExpressionBase bindExpr = ActiveBindingExpression; if (bindExpr != null) { return bindExpr.ValidateAndConvertProposedValue(out values); } values = null; return true; } // Return the object from which the given value was obtained, if possible internal override object GetSourceItem(object newValue) { BindingExpressionBase bindExpr = ActiveBindingExpression; if (bindExpr != null) { return bindExpr.GetSourceItem(newValue); } return true; } internal override void UpdateCommitState() { BindingExpressionBase bindExpr = ActiveBindingExpression; if (bindExpr != null) { AdoptProperties(bindExpr); } } //------------------------------------------------------ // // Private Properties // //------------------------------------------------------ /// <summary> /// expose a mutable version of the list of all BindingExpressions; /// derived internal classes need to be able to populate this list /// </summary> private Collection<BindingExpressionBase> MutableBindingExpressions { get { return _list; } } //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ // Create a BindingExpression for position i BindingExpressionBase AttachBindingExpression(int i, bool replaceExisting) { DependencyObject target = TargetElement; if (target == null) return null; BindingBase binding = ParentPriorityBinding.Bindings[i]; BindingExpressionBase bindExpr = binding.CreateBindingExpression(target, TargetProperty, this); if (replaceExisting) // replace exisiting or add as new binding? MutableBindingExpressions[i] = bindExpr; else MutableBindingExpressions.Add(bindExpr); bindExpr.Attach(target, TargetProperty); return bindExpr; } // Re-evaluate the choice of active BindingExpression void ChooseActiveBindingExpression(DependencyObject target) { int i, count = MutableBindingExpressions.Count; for (i = 0; i < count; ++i) { BindingExpressionBase bindExpr = MutableBindingExpressions[i]; // Try to activate the BindingExpression if it isn't already activate if (bindExpr.StatusInternal == BindingStatusInternal.Inactive) bindExpr.Activate(); if (bindExpr.StatusInternal == BindingStatusInternal.Active || bindExpr.UsingFallbackValue) break; } int newActiveIndex = (i < count) ? i : NoActiveBindingExpressions; // if active changes, adjust state if (newActiveIndex != _activeIndex) { int oldActiveIndex = _activeIndex; _activeIndex = newActiveIndex; // adopt the properties of the active binding AdoptProperties(ActiveBindingExpression); // tell the property engine the new list of sources WeakDependencySource[] newSources = CombineSources(-1, MutableBindingExpressions, AttentiveBindingExpressions, null); ChangeSources(newSources); // deactivate BindingExpressions that don't need to be attentive // if (newActiveIndex != NoActiveBindingExpressions) for (i = oldActiveIndex; i > newActiveIndex; --i) MutableBindingExpressions[i].Deactivate(); } } private void ChangeValue() { } internal override void HandlePropertyInvalidation(DependencyObject d, DependencyPropertyChangedEventArgs args) { DependencyProperty dp = args.Property; if (TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.Events)) { TraceData.Trace(TraceEventType.Warning, TraceData.GotPropertyChanged( TraceData.Identify(this), TraceData.Identify(d), dp.Name)); } for (int i=0; i<AttentiveBindingExpressions; ++i) { BindingExpressionBase bindExpr = MutableBindingExpressions[i]; DependencySource[] sources = bindExpr.GetSources(); if (sources != null) { for (int j=0; j<sources.Length; ++j) { DependencySource source = sources[j]; if (source.DependencyObject == d && source.DependencyProperty == dp) { bindExpr.OnPropertyInvalidation(d, args); break; } } } } } //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ const int NoActiveBindingExpressions = -1; // no BindingExpressions work, all are attentive const int UnknownActiveBindingExpression = -2; // need to determine active BindingExpression Collection<BindingExpressionBase> _list = new Collection<BindingExpressionBase>(); int _activeIndex = UnknownActiveBindingExpression; bool _isInInvalidateBinding = false; } }
// // Copyright (c) Microsoft. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Linq; using System.Collections.Generic; using Microsoft.Azure; using Microsoft.Azure.Management.Resources; using Xunit; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Net.Http; using System.Net; using Microsoft.Azure.Management.Resources.Models; using System.Runtime.Serialization.Formatters; namespace ResourceGroups.Tests { public class InMemoryDeploymentTests { public ResourceManagementClient GetResourceManagementClient(RecordedDelegatingHandler handler) { var token = new TokenCloudCredentials(Guid.NewGuid().ToString(), "abc123"); handler.IsPassThrough = false; return new ResourceManagementClient(token).WithHandler(handler); } [Fact] public void DeploymentTestsCreateValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.Created) { Content = new StringContent(@"{ 'id': 'foo', 'name':'myrealease-3.14', 'properties':{ 'provisioningState':'Succeeded', 'timestamp':'2014-01-05T12:30:43.00Z', 'mode':'Incremental', 'template': { 'api-version' : '123' }, 'templateLink': { 'uri': 'http://wa/template.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parametersLink': { /* use either one of parameters or parametersLink */ 'uri': 'http://wa/parameters.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parameters': { 'key' : { 'type':'string', 'value':'user' } }, 'outputs': { 'key' : { 'type':'string', 'value':'user' } } } }") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.Created }; var client = GetResourceManagementClient(handler); var dictionary = new Dictionary<string, object> { {"param1", "value1"}, {"param2", true}, {"param3", new Dictionary<string, object>() { {"param3_1", 123}, {"param3_2", "value3_2"}, }} }; var serializedDictionary = JsonConvert.SerializeObject(dictionary, new JsonSerializerSettings { TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple, TypeNameHandling = TypeNameHandling.None, Formatting = Formatting.Indented }); var parameters = new Deployment { Properties = new DeploymentProperties() { Template = "{'api-version':'123'}", TemplateLink = new TemplateLink { Uri = new Uri("http://abc/def/template.json"), ContentVersion = "1.0.0.0" }, Parameters = serializedDictionary, ParametersLink = new ParametersLink { Uri = new Uri("http://abc/def/template.json"), ContentVersion = "1.0.0.0" }, Mode = DeploymentMode.Incremental } }; var result = client.Deployments.CreateOrUpdate("foo", "myrealease-3.14", parameters); JObject json = JObject.Parse(handler.Request); // Validate headers Assert.Equal("application/json; charset=utf-8", handler.ContentHeaders.GetValues("Content-Type").First()); Assert.Equal(HttpMethod.Put, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); // Validate payload Assert.Equal("Incremental", json["properties"]["mode"].Value<string>()); Assert.Equal("http://abc/def/template.json", json["properties"]["templateLink"]["uri"].Value<string>()); Assert.Equal("1.0.0.0", json["properties"]["templateLink"]["contentVersion"].Value<string>()); Assert.Equal("1.0.0.0", json["properties"]["parametersLink"]["contentVersion"].Value<string>()); Assert.Equal("value1", json["properties"]["parameters"]["param1"].Value<string>()); Assert.Equal(true, json["properties"]["parameters"]["param2"].Value<bool>()); Assert.Equal(123, json["properties"]["parameters"]["param3"]["param3_1"].Value<int>()); Assert.Equal("value3_2", json["properties"]["parameters"]["param3"]["param3_2"].Value<string>()); Assert.Equal(123, json["properties"]["template"]["api-version"].Value<int>()); // Validate result Assert.Equal("foo", result.Deployment.Id); Assert.Equal("myrealease-3.14", result.Deployment.Name); Assert.Equal("Succeeded", result.Deployment.Properties.ProvisioningState); Assert.Equal(new DateTime(2014, 1, 5, 12, 30, 43), result.Deployment.Properties.Timestamp); Assert.Equal(DeploymentMode.Incremental, result.Deployment.Properties.Mode); Assert.Equal("http://wa/template.json", result.Deployment.Properties.TemplateLink.Uri.ToString()); Assert.Equal("1.0.0.0", result.Deployment.Properties.TemplateLink.ContentVersion); Assert.True(result.Deployment.Properties.Parameters.Contains("\"type\": \"string\"")); Assert.True(result.Deployment.Properties.Outputs.Contains("\"type\": \"string\"")); } [Fact] public void ListDeploymentOperationsReturnsMultipleObjects() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'value': [ { 'subscriptionId':'mysubid', 'resourceGroup': 'foo', 'deploymentName':'test-release-3', 'operationId': 'AEF2398', 'properties':{ 'targetResource':{ 'id': '/subscriptions/123abc/resourcegroups/foo/providers/ResourceProviderTestHost/TestResourceType/resource1', 'resourceName':'mySite1', 'resourceType': 'Microsoft.Web', }, 'provisioningState':'Succeeded', 'timestamp': '2014-02-25T23:08:21.8183932Z', 'correlationId': 'afb170c6-fe57-4b38-a43b-900fe09be4ca', 'statusCode': 'InternalServerError', 'statusMessage': 'InternalServerError', } } ], 'nextLink': 'https://wa.com/subscriptions/mysubid/resourcegroups/TestRG/deployments/test-release-3/operations?$skiptoken=983fknw' } ") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.DeploymentOperations.List("foo", "bar", null); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); // Validate response Assert.Equal(1, result.Operations.Count); Assert.Equal(HttpStatusCode.OK, result.StatusCode); Assert.Equal("AEF2398", result.Operations[0].OperationId); Assert.Equal("/subscriptions/123abc/resourcegroups/foo/providers/ResourceProviderTestHost/TestResourceType/resource1", result.Operations[0].Properties.TargetResource.Id); Assert.Equal("mySite1", result.Operations[0].Properties.TargetResource.ResourceName); Assert.Equal("Microsoft.Web", result.Operations[0].Properties.TargetResource.ResourceType); Assert.Equal("Succeeded", result.Operations[0].Properties.ProvisioningState); Assert.Equal("InternalServerError", result.Operations[0].Properties.StatusCode); Assert.Equal("\"InternalServerError\"", result.Operations[0].Properties.StatusMessage); Assert.Equal("https://wa.com/subscriptions/mysubid/resourcegroups/TestRG/deployments/test-release-3/operations?$skiptoken=983fknw", result.NextLink.ToString()); } [Fact] public void ListDeploymentOperationsReturnsEmptyArray() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'value': [], 'nextLink': 'https://wa.com/subscriptions/mysubid/resourcegroups/TestRG/deployments/test-release-3/operations?$skiptoken=983fknw' }") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.DeploymentOperations.List("foo", "bar", null); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); // Validate response Assert.Equal(0, result.Operations.Count); Assert.Equal(HttpStatusCode.OK, result.StatusCode); } [Fact] public void ListDeploymentOperationsWithRealPayloadReadsJsonInStatusMessage() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'value': [ { 'id': '/subscriptions/abcd1234/resourcegroups/foo/deployments/testdeploy/operations/334558C2218CAEB0', 'subscriptionId': 'abcd1234', 'resourceGroup': 'foo', 'deploymentName': 'testdeploy', 'operationId': '334558C2218CAEB0', 'properties': { 'provisioningState': 'Failed', 'timestamp': '2014-03-14T23:43:31.8688746Z', 'trackingId': '4f258f91-edd5-4d71-87c2-fac9a4b5cbbd', 'statusCode': 'Conflict', 'statusMessage': { 'Code': 'Conflict', 'Message': 'Website with given name ilygreTest4 already exists.', 'Target': null, 'Details': [ { 'Message': 'Website with given name ilygreTest4 already exists.' }, { 'Code': 'Conflict' }, { 'ErrorEntity': { 'Code': 'Conflict', 'Message': 'Website with given name ilygreTest4 already exists.', 'ExtendedCode': '54001', 'MessageTemplate': 'Website with given name {0} already exists.', 'Parameters': [ 'ilygreTest4' ], 'InnerErrors': null } } ], 'Innererror': null }, 'targetResource': { 'id': '/subscriptions/abcd1234/resourcegroups/foo/providers/Microsoft.Web/Sites/ilygreTest4', 'subscriptionId': 'abcd1234', 'resourceGroup': 'foo', 'resourceType': 'Microsoft.Web/Sites', 'resourceName': 'ilygreTest4' } } }, { 'id': '/subscriptions/abcd1234/resourcegroups/foo/deployments/testdeploy/operations/6B9A5A38C94E6 F14', 'subscriptionId': 'abcd1234', 'resourceGroup': 'foo', 'deploymentName': 'testdeploy', 'operationId': '6B9A5A38C94E6F14', 'properties': { 'provisioningState': 'Succeeded', 'timestamp': '2014-03-14T23:43:25.2101422Z', 'trackingId': '2ff7a8ad-abf3-47f6-8ce0-e4aae8c26065', 'statusCode': 'OK', 'statusMessage': null, 'targetResource': { 'id': '/subscriptions/abcd1234/resourcegroups/foo/providers/Microsoft.Web/serverFarms/ilygreTest4 Host', 'subscriptionId': 'abcd1234', 'resourceGroup': 'foo', 'resourceType': 'Microsoft.Web/serverFarms', 'resourceName': 'ilygreTest4Host' } } } ] }") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.DeploymentOperations.List("foo", "bar", null); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); Assert.True(JObject.Parse(result.Operations[0].Properties.StatusMessage).HasValues); } [Fact] public void ListDeploymentOperationsWorksWithNextLink() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'value': [ { 'subscriptionId':'mysubid', 'resourceGroup': 'foo', 'deploymentName':'test-release-3', 'operationId': 'AEF2398', 'properties':{ 'targetResource':{ 'subscriptionId':'mysubid', 'resourceGroup': 'TestRG', 'resourceName':'mySite1', 'resourceType': 'Microsoft.Web', }, 'provisioningState':'Succeeded', 'timestamp': '2014-02-25T23:08:21.8183932Z', 'correlationId': 'afb170c6-fe57-4b38-a43b-900fe09be4ca', 'statusCode': 'InternalServerError', 'statusMessage': 'InternalServerError', } } ], 'nextLink': 'https://wa.com/subscriptions/mysubid/resourcegroups/TestRG/deployments/test-release-3/operations?$skiptoken=983fknw' } ") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.DeploymentOperations.List("foo", "bar", null); response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'value': [] }") }; handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; client = GetResourceManagementClient(handler); result = client.DeploymentOperations.ListNext(result.NextLink); // Validate body Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); Assert.Equal("https://wa.com/subscriptions/mysubid/resourcegroups/TestRG/deployments/test-release-3/operations?$skiptoken=983fknw", handler.Uri.ToString()); // Validate response Assert.Equal(0, result.Operations.Count); Assert.Equal(null, result.NextLink); } [Fact] public void GetDeploymentOperationsReturnsValue() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'subscriptionId':'mysubid', 'resourceGroup': 'foo', 'deploymentName':'test-release-3', 'operationId': 'AEF2398', 'properties':{ 'targetResource':{ 'id':'/subscriptions/123abc/resourcegroups/foo/providers/ResourceProviderTestHost/TestResourceType/resource1', 'resourceName':'mySite1', 'resourceType': 'Microsoft.Web', }, 'provisioningState':'Succeeded', 'timestamp': '2014-02-25T23:08:21.8183932Z', 'correlationId': 'afb170c6-fe57-4b38-a43b-900fe09be4ca', 'statusCode': 'OK', 'statusMessage': 'OK', } }") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.DeploymentOperations.Get("foo", "bar", "123"); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); // Validate response Assert.Equal(HttpStatusCode.OK, result.StatusCode); Assert.Equal("AEF2398", result.Operation.OperationId); Assert.Equal("mySite1", result.Operation.Properties.TargetResource.ResourceName); Assert.Equal("/subscriptions/123abc/resourcegroups/foo/providers/ResourceProviderTestHost/TestResourceType/resource1", result.Operation.Properties.TargetResource.Id); Assert.Equal("Microsoft.Web", result.Operation.Properties.TargetResource.ResourceType); Assert.Equal("Succeeded", result.Operation.Properties.ProvisioningState); Assert.Equal("OK", result.Operation.Properties.StatusCode); Assert.Equal("\"OK\"", result.Operation.Properties.StatusMessage); } [Fact] public void DeploymentTestsCreateThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = GetResourceManagementClient(handler); Assert.Throws<ArgumentNullException>(() => client.Deployments.CreateOrUpdate(null, "bar", new Deployment())); Assert.Throws<ArgumentNullException>(() => client.Deployments.CreateOrUpdate("foo", null, new Deployment())); Assert.Throws<ArgumentNullException>(() => client.Deployments.CreateOrUpdate("foo", "bar", null)); Assert.Throws<ArgumentOutOfRangeException>(() => client.Deployments.CreateOrUpdate("~`123", "bar", new Deployment())); } [Fact] public void DeploymentTestsValidateCheckPayload() { var response = new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent(@"{ 'error': { 'code': 'InvalidTemplate', 'message': 'Deployment template validation failed.' } }") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.BadRequest }; var client = GetResourceManagementClient(handler); var dictionary = new Dictionary<string, object> { {"param1", "value1"}, {"param2", true}, {"param3", new Dictionary<string, object>() { {"param3_1", 123}, {"param3_2", "value3_2"}, }} }; var serializedDictionary = JsonConvert.SerializeObject(dictionary, new JsonSerializerSettings { TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple, TypeNameHandling = TypeNameHandling.None }); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Uri = new Uri("http://abc/def/template.json"), ContentVersion = "1.0.0.0", }, Parameters = serializedDictionary, Mode = DeploymentMode.Incremental } }; var result = client.Deployments.Validate("foo", "bar", parameters); JObject json = JObject.Parse(handler.Request); // Validate headers Assert.Equal("application/json; charset=utf-8", handler.ContentHeaders.GetValues("Content-Type").First()); Assert.Equal(HttpMethod.Post, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); // Validate payload Assert.Equal("Incremental", json["properties"]["mode"].Value<string>()); Assert.Equal("http://abc/def/template.json", json["properties"]["templateLink"]["uri"].Value<string>()); Assert.Equal("1.0.0.0", json["properties"]["templateLink"]["contentVersion"].Value<string>()); Assert.Equal("value1", json["properties"]["parameters"]["param1"].Value<string>()); Assert.Equal(true, json["properties"]["parameters"]["param2"].Value<bool>()); Assert.Equal(123, json["properties"]["parameters"]["param3"]["param3_1"].Value<int>()); Assert.Equal("value3_2", json["properties"]["parameters"]["param3"]["param3_2"].Value<string>()); } [Fact] public void DeploymentTestsValidateSimpleFailure() { var response = new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent(@"{ 'error': { 'code': 'InvalidTemplate', 'message': 'Deployment template validation failed: The template parameters hostingPlanName, siteMode, computeMode are not valid; they are not present.' } }") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.BadRequest }; var client = GetResourceManagementClient(handler); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Uri = new Uri("http://abc/def/template.json"), ContentVersion = "1.0.0.0", }, Mode = DeploymentMode.Incremental } }; var result = client.Deployments.Validate("foo", "bar", parameters); // Validate result Assert.False(result.IsValid); Assert.Equal("InvalidTemplate", result.Error.Code); Assert.Equal("Deployment template validation failed: The template parameters hostingPlanName, siteMode, computeMode are not valid; they are not present.", result.Error.Message); Assert.Null(result.Error.Target); Assert.Null(result.Error.Details); } [Fact] public void DeploymentTestsValidateComplexFailure() { var response = new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent(@"{ 'error': { 'code': 'InvalidTemplate', 'target': '', 'message': 'Deployment template validation failed: The template parameters hostingPlanName, siteMode, computeMode are not valid; they are not present.', 'details': [ { 'code': 'Error1', 'message': 'Deployment template validation failed.' }, { 'code': 'Error2', 'message': 'Deployment template validation failed.' } ] } }") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.BadRequest }; var client = GetResourceManagementClient(handler); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Uri = new Uri("http://abc/def/template.json"), ContentVersion = "1.0.0.0", }, Mode = DeploymentMode.Incremental } }; var result = client.Deployments.Validate("foo", "bar", parameters); JObject json = JObject.Parse(handler.Request); // Validate result Assert.False(result.IsValid); Assert.Equal("InvalidTemplate", result.Error.Code); Assert.Equal("Deployment template validation failed: The template parameters hostingPlanName, siteMode, computeMode are not valid; they are not present.", result.Error.Message); Assert.Equal("", result.Error.Target); Assert.True(result.Error.Details.Contains("Error1")); Assert.True(result.Error.Details.Contains("Error2")); } [Fact] public void DeploymentTestsValidateSuccess() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Uri = new Uri("http://abc/def/template.json"), ContentVersion = "1.0.0.0", }, Mode = DeploymentMode.Incremental } }; var result = client.Deployments.Validate("foo", "bar", parameters); JObject json = JObject.Parse(handler.Request); // Validate headers Assert.Equal("application/json; charset=utf-8", handler.ContentHeaders.GetValues("Content-Type").First()); Assert.Equal(HttpMethod.Post, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); // Validate result Assert.True(result.IsValid); Assert.Null(result.Error); } [Fact] public void DeploymentTestsValidateThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = GetResourceManagementClient(handler); Assert.Throws<ArgumentNullException>(() => client.Deployments.Validate(null, "bar", new Deployment())); Assert.Throws<ArgumentNullException>(() => client.Deployments.Validate("foo", "bar", null)); Assert.Throws<ArgumentOutOfRangeException>(() => client.Deployments.Validate("~`123", "bar", new Deployment())); } [Fact] public void DeploymentTestsCancelValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.NoContent); var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.NoContent, }; var client = GetResourceManagementClient(handler); var result = client.Deployments.Cancel("foo", "bar"); // Validate headers Assert.Equal(HttpStatusCode.NoContent, result.StatusCode); } [Fact] public void DeploymentTestsCancelThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = GetResourceManagementClient(handler); Assert.Throws<ArgumentNullException>(() => client.Deployments.Cancel(null, "bar")); Assert.Throws<ArgumentNullException>(() => client.Deployments.Cancel("foo", null)); } [Fact] public void DeploymentTestsGetValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'resourceGroup': 'foo', 'name':'myrealease-3.14', 'properties':{ 'provisioningState':'Succeeded', 'timestamp':'2014-01-05T12:30:43.00Z', 'mode':'Incremental', 'correlationId':'12345', 'templateLink': { 'uri': 'http://wa/template.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parametersLink': { /* use either one of parameters or parametersLink */ 'uri': 'http://wa/parameters.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parameters': { 'key' : { 'type':'string', 'value':'user' } }, 'outputs': { 'key' : { 'type':'string', 'value':'user' } } } }") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.Deployments.Get("foo", "bar"); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); // Validate result Assert.Equal("myrealease-3.14", result.Deployment.Name); Assert.Equal("Succeeded", result.Deployment.Properties.ProvisioningState); Assert.Equal("12345", result.Deployment.Properties.CorrelationId); Assert.Equal(new DateTime(2014, 1, 5, 12, 30, 43), result.Deployment.Properties.Timestamp); Assert.Equal(DeploymentMode.Incremental, result.Deployment.Properties.Mode); Assert.Equal("http://wa/template.json", result.Deployment.Properties.TemplateLink.Uri.ToString()); Assert.Equal("1.0.0.0", result.Deployment.Properties.TemplateLink.ContentVersion); Assert.True(result.Deployment.Properties.Parameters.Contains("\"type\": \"string\"")); Assert.True(result.Deployment.Properties.Outputs.Contains("\"type\": \"string\"")); } [Fact] public void DeploymentGetValidateThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = GetResourceManagementClient(handler); Assert.Throws<ArgumentNullException>(() => client.Deployments.Get(null, "bar")); Assert.Throws<ArgumentNullException>(() => client.Deployments.Get("foo", null)); Assert.Throws<ArgumentOutOfRangeException>(() => client.Deployments.Get("~`123", "bar")); } [Fact] public void DeploymentTestsListAllValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'value' : [ { 'resourceGroup': 'foo', 'name':'myrealease-3.14', 'properties':{ 'provisioningState':'Succeeded', 'timestamp':'2014-01-05T12:30:43.00Z', 'mode':'Incremental', 'templateLink': { 'uri': 'http://wa/template.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parametersLink': { /* use either one of parameters or parametersLink */ 'uri': 'http://wa/parameters.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parameters': { 'key' : { 'type':'string', 'value':'user' } }, 'outputs': { 'key' : { 'type':'string', 'value':'user' } } } }, { 'resourceGroup': 'bar', 'name':'myrealease-3.14', 'properties':{ 'provisioningState':'Succeeded', 'timestamp':'2014-01-05T12:30:43.00Z', 'mode':'Incremental', 'templateLink': { 'uri': 'http://wa/template.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parametersLink': { /* use either one of parameters or parametersLink */ 'uri': 'http://wa/parameters.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parameters': { 'key' : { 'type':'string', 'value':'user' } }, 'outputs': { 'key' : { 'type':'string', 'value':'user' } } } } ], 'nextLink': 'https://wa/subscriptions/subId/templateDeployments?$skiptoken=983fknw' }") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.Deployments.List("foo", new DeploymentListParameters()); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); // Validate result Assert.Equal("myrealease-3.14", result.Deployments[0].Name); Assert.Equal("Succeeded", result.Deployments[0].Properties.ProvisioningState); Assert.Equal(new DateTime(2014, 1, 5, 12, 30, 43), result.Deployments[0].Properties.Timestamp); Assert.Equal(DeploymentMode.Incremental, result.Deployments[0].Properties.Mode); Assert.Equal("http://wa/template.json", result.Deployments[0].Properties.TemplateLink.Uri.ToString()); Assert.Equal("1.0.0.0", result.Deployments[0].Properties.TemplateLink.ContentVersion); Assert.True(result.Deployments[0].Properties.Parameters.Contains("\"type\": \"string\"")); Assert.True(result.Deployments[0].Properties.Outputs.Contains("\"type\": \"string\"")); Assert.Equal("https://wa/subscriptions/subId/templateDeployments?$skiptoken=983fknw", result.NextLink.ToString()); } [Fact] public void DeploymentTestsListValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'value' : [ { 'resourceGroup': 'foo', 'name':'myrealease-3.14', 'properties':{ 'provisioningState':'Succeeded', 'timestamp':'2014-01-05T12:30:43.00Z', 'mode':'Incremental', 'templateLink': { 'uri': 'http://wa/template.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parametersLink': { /* use either one of parameters or parametersLink */ 'uri': 'http://wa/parameters.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parameters': { 'key' : { 'type':'string', 'value':'user' } }, 'outputs': { 'key' : { 'type':'string', 'value':'user' } } } }, { 'resourceGroup': 'bar', 'name':'myrealease-3.14', 'properties':{ 'provisioningState':'Succeeded', 'timestamp':'2014-01-05T12:30:43.00Z', 'mode':'Incremental', 'templateLink': { 'uri': 'http://wa/template.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parametersLink': { /* use either one of parameters or parametersLink */ 'uri': 'http://wa/parameters.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parameters': { 'key' : { 'type':'string', 'value':'user' } }, 'outputs': { 'key' : { 'type':'string', 'value':'user' } } } } ], 'nextLink': 'https://wa/subscriptions/subId/templateDeployments?$skiptoken=983fknw' }") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.Deployments.List("foo", new DeploymentListParameters { ProvisioningState = "Succeeded", Top = 10, }); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); Assert.True(handler.Uri.ToString().Contains("$top=10")); Assert.True(handler.Uri.ToString().Contains("$filter=provisioningState eq 'Succeeded'")); // Validate result Assert.Equal("myrealease-3.14", result.Deployments[0].Name); Assert.Equal("Succeeded", result.Deployments[0].Properties.ProvisioningState); Assert.Equal(new DateTime(2014, 1, 5, 12, 30, 43), result.Deployments[0].Properties.Timestamp); Assert.Equal(DeploymentMode.Incremental, result.Deployments[0].Properties.Mode); Assert.Equal("http://wa/template.json", result.Deployments[0].Properties.TemplateLink.Uri.ToString()); Assert.Equal("1.0.0.0", result.Deployments[0].Properties.TemplateLink.ContentVersion); Assert.True(result.Deployments[0].Properties.Parameters.Contains("\"type\": \"string\"")); Assert.True(result.Deployments[0].Properties.Outputs.Contains("\"type\": \"string\"")); Assert.Equal("https://wa/subscriptions/subId/templateDeployments?$skiptoken=983fknw", result.NextLink.ToString()); } [Fact] public void DeploymentTestsListForGroupValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'value' : [ { 'resourceGroup': 'foo', 'name':'myrealease-3.14', 'properties':{ 'provisioningState':'Succeeded', 'timestamp':'2014-01-05T12:30:43.00Z', 'mode':'Incremental', 'templateLink': { 'uri': 'http://wa/template.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parametersLink': { /* use either one of parameters or parametersLink */ 'uri': 'http://wa/parameters.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parameters': { 'key' : { 'type':'string', 'value':'user' } }, 'outputs': { 'key' : { 'type':'string', 'value':'user' } } } }, { 'resourceGroup': 'bar', 'name':'myrealease-3.14', 'properties':{ 'provisioningState':'Succeeded', 'timestamp':'2014-01-05T12:30:43.00Z', 'mode':'Incremental', 'templateLink': { 'uri': 'http://wa/template.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parametersLink': { /* use either one of parameters or parametersLink */ 'uri': 'http://wa/parameters.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parameters': { 'key' : { 'type':'string', 'value':'user' } }, 'outputs': { 'key' : { 'type':'string', 'value':'user' } } } } ], 'nextLink': 'https://wa/subscriptions/subId/templateDeployments?$skiptoken=983fknw' }") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.Deployments.List("foo", new DeploymentListParameters { ProvisioningState = "Succeeded", Top = 10, }); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); Assert.True(handler.Uri.ToString().Contains("$top=10")); Assert.True(handler.Uri.ToString().Contains("$filter=provisioningState eq 'Succeeded'")); Assert.True(handler.Uri.ToString().Contains("resourcegroups/foo/deployments")); // Validate result Assert.Equal("myrealease-3.14", result.Deployments[0].Name); Assert.Equal("Succeeded", result.Deployments[0].Properties.ProvisioningState); Assert.Equal(new DateTime(2014, 1, 5, 12, 30, 43), result.Deployments[0].Properties.Timestamp); Assert.Equal(DeploymentMode.Incremental, result.Deployments[0].Properties.Mode); Assert.Equal("http://wa/template.json", result.Deployments[0].Properties.TemplateLink.Uri.ToString()); Assert.Equal("1.0.0.0", result.Deployments[0].Properties.TemplateLink.ContentVersion); Assert.True(result.Deployments[0].Properties.Parameters.Contains("\"type\": \"string\"")); Assert.True(result.Deployments[0].Properties.Outputs.Contains("\"type\": \"string\"")); Assert.Equal("https://wa/subscriptions/subId/templateDeployments?$skiptoken=983fknw", result.NextLink.ToString()); } [Fact] public void DeploymentTestListDoesNotThrowExceptions() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("{'value' : []}") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.Deployments.List("foo", new DeploymentListParameters()); Assert.Empty(result.Deployments); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // namespace System.Threading { using System; using System.Security.Permissions; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Runtime; // After much discussion, we decided the Interlocked class doesn't need // any HPA's for synchronization or external threading. They hurt C#'s // codegen for the yield keyword, and arguably they didn't protect much. // Instead, they penalized people (and compilers) for writing threadsafe // code. public static class Interlocked { /****************************** * Increment * Implemented: int * long *****************************/ [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static int Increment(ref int location) { return Add(ref location, 1); } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static long Increment(ref long location) { return Add(ref location, 1); } /****************************** * Decrement * Implemented: int * long *****************************/ [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static int Decrement(ref int location) { return Add(ref location, -1); } public static long Decrement(ref long location) { return Add(ref location, -1); } /****************************** * Exchange * Implemented: int * long * float * double * Object * IntPtr *****************************/ [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Security.SecuritySafeCritical] public static extern int Exchange(ref int location1, int value); [MethodImplAttribute(MethodImplOptions.InternalCall)] [System.Security.SecuritySafeCritical] public static extern long Exchange(ref long location1, long value); [MethodImplAttribute(MethodImplOptions.InternalCall)] [System.Security.SecuritySafeCritical] public static extern float Exchange(ref float location1, float value); [MethodImplAttribute(MethodImplOptions.InternalCall)] [System.Security.SecuritySafeCritical] public static extern double Exchange(ref double location1, double value); [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Security.SecuritySafeCritical] public static extern Object Exchange(ref Object location1, Object value); [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Security.SecuritySafeCritical] public static extern IntPtr Exchange(ref IntPtr location1, IntPtr value); [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.InteropServices.ComVisible(false)] [System.Security.SecuritySafeCritical] public static T Exchange<T>(ref T location1, T value) where T : class { _Exchange(__makeref(location1), __makeref(value)); //Since value is a local we use trash its data on return // The Exchange replaces the data with new data // so after the return "value" contains the original location1 //See ExchangeGeneric for more details return value; } [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Security.SecuritySafeCritical] private static extern void _Exchange(TypedReference location1, TypedReference value); /****************************** * CompareExchange * Implemented: int * long * float * double * Object * IntPtr *****************************/ [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Security.SecuritySafeCritical] public static extern int CompareExchange(ref int location1, int value, int comparand); [MethodImplAttribute(MethodImplOptions.InternalCall)] [System.Security.SecuritySafeCritical] public static extern long CompareExchange(ref long location1, long value, long comparand); [MethodImplAttribute(MethodImplOptions.InternalCall)] [System.Security.SecuritySafeCritical] public static extern float CompareExchange(ref float location1, float value, float comparand); [MethodImplAttribute(MethodImplOptions.InternalCall)] [System.Security.SecuritySafeCritical] public static extern double CompareExchange(ref double location1, double value, double comparand); [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Security.SecuritySafeCritical] public static extern Object CompareExchange(ref Object location1, Object value, Object comparand); [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Security.SecuritySafeCritical] public static extern IntPtr CompareExchange(ref IntPtr location1, IntPtr value, IntPtr comparand); /***************************************************************** * CompareExchange<T> * * Notice how CompareExchange<T>() uses the __makeref keyword * to create two TypedReferences before calling _CompareExchange(). * This is horribly slow. Ideally we would like CompareExchange<T>() * to simply call CompareExchange(ref Object, Object, Object); * however, this would require casting a "ref T" into a "ref Object", * which is not legal in C#. * * Thus we opted to implement this in the JIT so that when it reads * the method body for CompareExchange<T>() it gets back the * following IL: * * ldarg.0 * ldarg.1 * ldarg.2 * call System.Threading.Interlocked::CompareExchange(ref Object, Object, Object) * ret * * See getILIntrinsicImplementationForInterlocked() in VM\JitInterface.cpp * for details. *****************************************************************/ [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.InteropServices.ComVisible(false)] [System.Security.SecuritySafeCritical] public static T CompareExchange<T>(ref T location1, T value, T comparand) where T : class { // _CompareExchange() passes back the value read from location1 via local named 'value' _CompareExchange(__makeref(location1), __makeref(value), comparand); return value; } [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Security.SecuritySafeCritical] private static extern void _CompareExchange(TypedReference location1, TypedReference value, Object comparand); // BCL-internal overload that returns success via a ref bool param, useful for reliable spin locks. [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Security.SecuritySafeCritical] internal static extern int CompareExchange(ref int location1, int value, int comparand, ref bool succeeded); /****************************** * Add * Implemented: int * long *****************************/ [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal static extern int ExchangeAdd(ref int location1, int value); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern long ExchangeAdd(ref long location1, long value); [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static int Add(ref int location1, int value) { return ExchangeAdd(ref location1, value) + value; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static long Add(ref long location1, long value) { return ExchangeAdd(ref location1, value) + value; } /****************************** * Read *****************************/ public static long Read(ref long location) { return Interlocked.CompareExchange(ref location,0,0); } public static void MemoryBarrier() { Thread.MemoryBarrier(); } } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; namespace Amazon.StorageGateway.Model { /// <summary> /// <para>Describes an iSCSI stored volume.</para> /// </summary> public class StorediSCSIVolume { private string volumeARN; private string volumeId; private string volumeType; private string volumeStatus; private long? volumeSizeInBytes; private double? volumeProgress; private string volumeDiskId; private string sourceSnapshotId; private bool? preservedExistingData; private VolumeiSCSIAttributes volumeiSCSIAttributes; /// <summary> /// The Amazon Resource Name (ARN) of the storage volume. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>50 - 500</description> /// </item> /// </list> /// </para> /// </summary> public string VolumeARN { get { return this.volumeARN; } set { this.volumeARN = value; } } /// <summary> /// Sets the VolumeARN property /// </summary> /// <param name="volumeARN">The value to set for the VolumeARN property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public StorediSCSIVolume WithVolumeARN(string volumeARN) { this.volumeARN = volumeARN; return this; } // Check to see if VolumeARN property is set internal bool IsSetVolumeARN() { return this.volumeARN != null; } /// <summary> /// The unique identifier of the volume, e.g. vol-AE4B946D. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>12 - 30</description> /// </item> /// </list> /// </para> /// </summary> public string VolumeId { get { return this.volumeId; } set { this.volumeId = value; } } /// <summary> /// Sets the VolumeId property /// </summary> /// <param name="volumeId">The value to set for the VolumeId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public StorediSCSIVolume WithVolumeId(string volumeId) { this.volumeId = volumeId; return this; } // Check to see if VolumeId property is set internal bool IsSetVolumeId() { return this.volumeId != null; } /// <summary> /// One of the <a>VolumeType</a> enumeration values describing the type of the volume. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Allowed Values</term> /// <description>STORED iSCSI, CACHED iSCSI</description> /// </item> /// </list> /// </para> /// </summary> public string VolumeType { get { return this.volumeType; } set { this.volumeType = value; } } /// <summary> /// Sets the VolumeType property /// </summary> /// <param name="volumeType">The value to set for the VolumeType property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public StorediSCSIVolume WithVolumeType(string volumeType) { this.volumeType = volumeType; return this; } // Check to see if VolumeType property is set internal bool IsSetVolumeType() { return this.volumeType != null; } /// <summary> /// One of the <a>VolumeStatus</a> values that indicates the state of the storage volume. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Allowed Values</term> /// <description>CREATING, AVAILABLE, RESTORING, BOOTSTRAPPING, IRRECOVERABLE, PASS THROUGH, RESTORE AND PASS THROUGH, DELETED, WORKING STORAGE NOT CONFIGURED, UPLOAD BUFFER NOT CONFIGURED</description> /// </item> /// </list> /// </para> /// </summary> public string VolumeStatus { get { return this.volumeStatus; } set { this.volumeStatus = value; } } /// <summary> /// Sets the VolumeStatus property /// </summary> /// <param name="volumeStatus">The value to set for the VolumeStatus property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public StorediSCSIVolume WithVolumeStatus(string volumeStatus) { this.volumeStatus = volumeStatus; return this; } // Check to see if VolumeStatus property is set internal bool IsSetVolumeStatus() { return this.volumeStatus != null; } /// <summary> /// The size of the volume in bytes. /// /// </summary> public long VolumeSizeInBytes { get { return this.volumeSizeInBytes ?? default(long); } set { this.volumeSizeInBytes = value; } } /// <summary> /// Sets the VolumeSizeInBytes property /// </summary> /// <param name="volumeSizeInBytes">The value to set for the VolumeSizeInBytes property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public StorediSCSIVolume WithVolumeSizeInBytes(long volumeSizeInBytes) { this.volumeSizeInBytes = volumeSizeInBytes; return this; } // Check to see if VolumeSizeInBytes property is set internal bool IsSetVolumeSizeInBytes() { return this.volumeSizeInBytes.HasValue; } /// <summary> /// Represents the percentage complete if the volume is restoring or bootstrapping that represents the percent of data transferred. This field /// does not appear in the response if the stored volume is not restoring or bootstrapping. /// /// </summary> public double VolumeProgress { get { return this.volumeProgress ?? default(double); } set { this.volumeProgress = value; } } /// <summary> /// Sets the VolumeProgress property /// </summary> /// <param name="volumeProgress">The value to set for the VolumeProgress property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public StorediSCSIVolume WithVolumeProgress(double volumeProgress) { this.volumeProgress = volumeProgress; return this; } // Check to see if VolumeProgress property is set internal bool IsSetVolumeProgress() { return this.volumeProgress.HasValue; } /// <summary> /// The disk ID of the local disk that was specified in the <a>CreateStorediSCSIVolume</a> operation. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 300</description> /// </item> /// </list> /// </para> /// </summary> public string VolumeDiskId { get { return this.volumeDiskId; } set { this.volumeDiskId = value; } } /// <summary> /// Sets the VolumeDiskId property /// </summary> /// <param name="volumeDiskId">The value to set for the VolumeDiskId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public StorediSCSIVolume WithVolumeDiskId(string volumeDiskId) { this.volumeDiskId = volumeDiskId; return this; } // Check to see if VolumeDiskId property is set internal bool IsSetVolumeDiskId() { return this.volumeDiskId != null; } /// <summary> /// If the stored volume was created from a snapshot, this field contains the snapshot ID used, e.g. snap-78e22663. Otherwise, this field is not /// included. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Pattern</term> /// <description>\Asnap-[0-9a-fA-F]{8}\z</description> /// </item> /// </list> /// </para> /// </summary> public string SourceSnapshotId { get { return this.sourceSnapshotId; } set { this.sourceSnapshotId = value; } } /// <summary> /// Sets the SourceSnapshotId property /// </summary> /// <param name="sourceSnapshotId">The value to set for the SourceSnapshotId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public StorediSCSIVolume WithSourceSnapshotId(string sourceSnapshotId) { this.sourceSnapshotId = sourceSnapshotId; return this; } // Check to see if SourceSnapshotId property is set internal bool IsSetSourceSnapshotId() { return this.sourceSnapshotId != null; } /// <summary> /// Indicates if when the stored volume was created, existing data on the underlying local disk was preserved. <i>Valid Values</i>: true, false /// /// </summary> public bool PreservedExistingData { get { return this.preservedExistingData ?? default(bool); } set { this.preservedExistingData = value; } } /// <summary> /// Sets the PreservedExistingData property /// </summary> /// <param name="preservedExistingData">The value to set for the PreservedExistingData property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public StorediSCSIVolume WithPreservedExistingData(bool preservedExistingData) { this.preservedExistingData = preservedExistingData; return this; } // Check to see if PreservedExistingData property is set internal bool IsSetPreservedExistingData() { return this.preservedExistingData.HasValue; } /// <summary> /// An <a>VolumeiSCSIAttributes</a> object that represents a collection of iSCSI attributes for one stored volume. /// /// </summary> public VolumeiSCSIAttributes VolumeiSCSIAttributes { get { return this.volumeiSCSIAttributes; } set { this.volumeiSCSIAttributes = value; } } /// <summary> /// Sets the VolumeiSCSIAttributes property /// </summary> /// <param name="volumeiSCSIAttributes">The value to set for the VolumeiSCSIAttributes property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public StorediSCSIVolume WithVolumeiSCSIAttributes(VolumeiSCSIAttributes volumeiSCSIAttributes) { this.volumeiSCSIAttributes = volumeiSCSIAttributes; return this; } // Check to see if VolumeiSCSIAttributes property is set internal bool IsSetVolumeiSCSIAttributes() { return this.volumeiSCSIAttributes != null; } } }
// 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.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB { public class PDBLambdaTests : CSharpPDBTestBase { [WorkItem(539898, "DevDiv")] [Fact] public void SequencePoints_Body() { var source = @" using System; delegate void D(); class C { public static void Main() { D d = () => Console.Write(1); d(); } } "; var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <lambda offset=""23"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""38"" document=""0"" /> <entry offset=""0x21"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""13"" document=""0"" /> <entry offset=""0x28"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""0"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x29""> <namespace name=""System"" /> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0x29"" attributes=""0"" /> </scope> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;Main&gt;b__0_0""> <customDebugInfo> <forward declaringType=""C"" methodName=""Main"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""21"" endLine=""8"" endColumn=""37"" document=""0"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact, WorkItem(543479, "DevDiv")] public void Nested() { var source = @" using System; class Test { public static int Main() { if (M(1) != 10) return 1; return 0; } static public int M(int p) { Func<int, int> f1 = delegate(int x) { int q = 2; Func<int, int> f2 = (y) => { return p + q + x + y; }; return f2(3); }; return f1(4); } } "; var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugExe); c.VerifyPdb(@" <symbols> <entryPoint declaringType=""Test"" methodName=""Main"" /> <methods> <method containingType=""Test"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""1"" offset=""12"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""0"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""10"" endLine=""7"" endColumn=""25"" document=""0"" /> <entry offset=""0xf"" hidden=""true"" document=""0"" /> <entry offset=""0x12"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""22"" document=""0"" /> <entry offset=""0x16"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""18"" document=""0"" /> <entry offset=""0x1a"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""0"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1c""> <namespace name=""System"" /> </scope> </method> <method containingType=""Test"" name=""M"" parameterNames=""p""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" /> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> <slot kind=""0"" offset=""26"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <closure offset=""0"" /> <closure offset=""56"" /> <lambda offset=""56"" closure=""0"" /> <lambda offset=""136"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""0"" /> <entry offset=""0xd"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""0"" /> <entry offset=""0xe"" startLine=""14"" startColumn=""9"" endLine=""22"" endColumn=""11"" document=""0"" /> <entry offset=""0x1b"" startLine=""23"" startColumn=""9"" endLine=""23"" endColumn=""22"" document=""0"" /> <entry offset=""0x25"" startLine=""24"" startColumn=""5"" endLine=""24"" endColumn=""6"" document=""0"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x27""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x27"" attributes=""0"" /> <local name=""f1"" il_index=""1"" il_start=""0x0"" il_end=""0x27"" attributes=""0"" /> </scope> </method> <method containingType=""Test+&lt;&gt;c__DisplayClass1_0"" name=""&lt;M&gt;b__0"" parameterNames=""x""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" /> <encLocalSlotMap> <slot kind=""30"" offset=""56"" /> <slot kind=""0"" offset=""110"" /> <slot kind=""21"" offset=""56"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""0"" /> <entry offset=""0x14"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""0"" /> <entry offset=""0x15"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""23"" document=""0"" /> <entry offset=""0x1c"" startLine=""17"" startColumn=""13"" endLine=""20"" endColumn=""15"" document=""0"" /> <entry offset=""0x29"" startLine=""21"" startColumn=""13"" endLine=""21"" endColumn=""26"" document=""0"" /> <entry offset=""0x33"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""0"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x35""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" /> <local name=""f2"" il_index=""1"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" /> </scope> </method> <method containingType=""Test+&lt;&gt;c__DisplayClass1_1"" name=""&lt;M&gt;b__1"" parameterNames=""y""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" /> <encLocalSlotMap> <slot kind=""21"" offset=""136"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""14"" document=""0"" /> <entry offset=""0x1"" startLine=""19"" startColumn=""17"" endLine=""19"" endColumn=""38"" document=""0"" /> <entry offset=""0x1f"" startLine=""20"" startColumn=""13"" endLine=""20"" endColumn=""14"" document=""0"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact, WorkItem(543479, "DevDiv")] public void InitialSequencePoints() { var source = @" class Test { void Foo(int p) { System.Func<int> f1 = () => p; f1(); } } "; // Specifically note the sequence points at 0x0 in Test.Main, Test.M, and the lambda bodies. var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <methods> <method containingType=""Test"" name=""Foo"" parameterNames=""p""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> <slot kind=""0"" offset=""28"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""0"" /> <lambda offset=""39"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""0"" /> <entry offset=""0xd"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""0"" /> <entry offset=""0xe"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""39"" document=""0"" /> <entry offset=""0x1b"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""14"" document=""0"" /> <entry offset=""0x22"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""0"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x23""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x23"" attributes=""0"" /> <local name=""f1"" il_index=""1"" il_start=""0x0"" il_end=""0x23"" attributes=""0"" /> </scope> </method> <method containingType=""Test+&lt;&gt;c__DisplayClass0_0"" name=""&lt;Foo&gt;b__0""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Foo"" parameterNames=""p"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""37"" endLine=""6"" endColumn=""38"" document=""0"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact, WorkItem(543479, "DevDiv")] public void Nested_InitialSequencePoints() { var source = @" using System; class Test { public static int Main() { if (M(1) != 10) // can't step into M() at all return 1; return 0; } static public int M(int p) { Func<int, int> f1 = delegate(int x) { int q = 2; Func<int, int> f2 = (y) => { return p + q + x + y; }; return f2(3); }; return f1(4); } } "; // Specifically note the sequence points at 0x0 in Test.Main, Test.M, and the lambda bodies. var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <methods> <method containingType=""Test"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""1"" offset=""11"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""0"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""24"" document=""0"" /> <entry offset=""0xf"" hidden=""true"" document=""0"" /> <entry offset=""0x12"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""22"" document=""0"" /> <entry offset=""0x16"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""18"" document=""0"" /> <entry offset=""0x1a"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""0"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1c""> <namespace name=""System"" /> </scope> </method> <method containingType=""Test"" name=""M"" parameterNames=""p""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" /> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> <slot kind=""0"" offset=""26"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <closure offset=""0"" /> <closure offset=""56"" /> <lambda offset=""56"" closure=""0"" /> <lambda offset=""122"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""0"" /> <entry offset=""0xd"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""0"" /> <entry offset=""0xe"" startLine=""14"" startColumn=""9"" endLine=""19"" endColumn=""11"" document=""0"" /> <entry offset=""0x1b"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""22"" document=""0"" /> <entry offset=""0x25"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""0"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x27""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x27"" attributes=""0"" /> <local name=""f1"" il_index=""1"" il_start=""0x0"" il_end=""0x27"" attributes=""0"" /> </scope> </method> <method containingType=""Test+&lt;&gt;c__DisplayClass1_0"" name=""&lt;M&gt;b__0"" parameterNames=""x""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" /> <encLocalSlotMap> <slot kind=""30"" offset=""56"" /> <slot kind=""0"" offset=""110"" /> <slot kind=""21"" offset=""56"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""0"" /> <entry offset=""0x14"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""0"" /> <entry offset=""0x15"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""23"" document=""0"" /> <entry offset=""0x1c"" startLine=""17"" startColumn=""13"" endLine=""17"" endColumn=""66"" document=""0"" /> <entry offset=""0x29"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""26"" document=""0"" /> <entry offset=""0x33"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""0"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x35""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" /> <local name=""f2"" il_index=""1"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" /> </scope> </method> <method containingType=""Test+&lt;&gt;c__DisplayClass1_1"" name=""&lt;M&gt;b__1"" parameterNames=""y""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" /> <encLocalSlotMap> <slot kind=""21"" offset=""122"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""17"" startColumn=""40"" endLine=""17"" endColumn=""41"" document=""0"" /> <entry offset=""0x1"" startLine=""17"" startColumn=""42"" endLine=""17"" endColumn=""63"" document=""0"" /> <entry offset=""0x1f"" startLine=""17"" startColumn=""64"" endLine=""17"" endColumn=""65"" document=""0"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void FieldAndPropertyInitializers() { var source = @" using System; class B { public B(Func<int> f) { } } class C : B { Func<int> FI = () => 1; static Func<int> FS = () => 2; Func<int> P { get; } = () => FS(); public C() : base(() => 3) {} } "; var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); c.VerifyPdb(@" <symbols> <methods> <method containingType=""B"" name="".ctor"" parameterNames=""f""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""26"" document=""0"" /> <entry offset=""0x7"" startLine=""6"" startColumn=""27"" endLine=""6"" endColumn=""28"" document=""0"" /> <entry offset=""0x8"" startLine=""6"" startColumn=""29"" endLine=""6"" endColumn=""30"" document=""0"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9""> <namespace name=""System"" /> </scope> </method> <method containingType=""C"" name=""get_P""> <sequencePoints> <entry offset=""0x0"" startLine=""13"" startColumn=""19"" endLine=""13"" endColumn=""23"" document=""0"" /> </sequencePoints> </method> <method containingType=""C"" name="".ctor""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> <encLambdaMap> <methodOrdinal>5</methodOrdinal> <lambda offset=""-2"" /> <lambda offset=""-28"" /> <lambda offset=""-19"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""28"" document=""0"" /> <entry offset=""0x25"" startLine=""13"" startColumn=""28"" endLine=""13"" endColumn=""38"" document=""0"" /> <entry offset=""0x4a"" startLine=""14"" startColumn=""18"" endLine=""14"" endColumn=""31"" document=""0"" /> <entry offset=""0x70"" startLine=""14"" startColumn=""32"" endLine=""14"" endColumn=""33"" document=""0"" /> <entry offset=""0x71"" startLine=""14"" startColumn=""33"" endLine=""14"" endColumn=""34"" document=""0"" /> </sequencePoints> </method> <method containingType=""C"" name="".cctor""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> <encLambdaMap> <methodOrdinal>6</methodOrdinal> <lambda offset=""-1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""35"" document=""0"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;.ctor&gt;b__5_0""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""14"" startColumn=""29"" endLine=""14"" endColumn=""30"" document=""0"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;.ctor&gt;b__5_1""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""26"" endLine=""11"" endColumn=""27"" document=""0"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;.ctor&gt;b__5_2""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""13"" startColumn=""34"" endLine=""13"" endColumn=""38"" document=""0"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;.cctor&gt;b__6_0""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""12"" startColumn=""33"" endLine=""12"" endColumn=""34"" document=""0"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void ClosuresInCtor() { var source = @" using System; class B { public B(Func<int> f) { } } class C : B { Func<int> f, g, h; public C(int a, int b) : base(() => a) { int c = 1; f = () => b; g = () => f(); h = () => c; } } "; var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); c.VerifyPdb(@" <symbols> <methods> <method containingType=""B"" name="".ctor"" parameterNames=""f""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""26"" document=""0"" /> <entry offset=""0x7"" startLine=""6"" startColumn=""27"" endLine=""6"" endColumn=""28"" document=""0"" /> <entry offset=""0x8"" startLine=""6"" startColumn=""29"" endLine=""6"" endColumn=""30"" document=""0"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9""> <namespace name=""System"" /> </scope> </method> <method containingType=""C"" name="".ctor"" parameterNames=""a, b""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> <encLocalSlotMap> <slot kind=""30"" offset=""-1"" /> <slot kind=""30"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>3</methodOrdinal> <closure offset=""-1"" /> <closure offset=""0"" /> <lambda offset=""-2"" closure=""0"" /> <lambda offset=""41"" closure=""0"" /> <lambda offset=""63"" closure=""this"" /> <lambda offset=""87"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""0"" /> <entry offset=""0x27"" hidden=""true"" document=""0"" /> <entry offset=""0x2d"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""0"" /> <entry offset=""0x2e"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""19"" document=""0"" /> <entry offset=""0x35"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""21"" document=""0"" /> <entry offset=""0x47"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""23"" document=""0"" /> <entry offset=""0x59"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""21"" document=""0"" /> <entry offset=""0x6b"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""0"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x6c""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x6c"" attributes=""0"" /> <scope startOffset=""0x27"" endOffset=""0x6b""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""1"" il_start=""0x27"" il_end=""0x6b"" attributes=""0"" /> </scope> </scope> </method> <method containingType=""C"" name=""&lt;.ctor&gt;b__3_2""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""17"" startColumn=""19"" endLine=""17"" endColumn=""22"" document=""0"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c__DisplayClass3_0"" name=""&lt;.ctor&gt;b__0""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""13"" startColumn=""41"" endLine=""13"" endColumn=""42"" document=""0"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c__DisplayClass3_0"" name=""&lt;.ctor&gt;b__1""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""16"" startColumn=""19"" endLine=""16"" endColumn=""20"" document=""0"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c__DisplayClass3_1"" name=""&lt;.ctor&gt;b__3""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""18"" startColumn=""19"" endLine=""18"" endColumn=""20"" document=""0"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void Queries1() { var source = @" using System.Linq; class C { public void M() { int c = 1; var x = from a in new[] { 1, 2, 3 } let b = a + c where b > 10 select b * 10; } } "; var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); c.VerifyPdb(@" <symbols> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> <slot kind=""0"" offset=""35"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""0"" /> <lambda offset=""92"" closure=""0"" /> <lambda offset=""121"" /> <lambda offset=""152"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""0"" /> <entry offset=""0x6"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" /> <entry offset=""0x7"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""19"" document=""0"" /> <entry offset=""0xe"" startLine=""9"" startColumn=""9"" endLine=""12"" endColumn=""31"" document=""0"" /> <entry offset=""0x79"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""0"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x7a""> <namespace name=""System.Linq"" /> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x7a"" attributes=""0"" /> <local name=""x"" il_index=""1"" il_start=""0x0"" il_end=""0x7a"" attributes=""0"" /> </scope> </method> <method containingType=""C+&lt;&gt;c__DisplayClass0_0"" name=""&lt;M&gt;b__0"" parameterNames=""a""> <customDebugInfo> <forward declaringType=""C"" methodName=""M"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""17"" endLine=""10"" endColumn=""30"" document=""0"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;M&gt;b__0_1"" parameterNames=""&lt;&gt;h__TransparentIdentifier0""> <customDebugInfo> <forward declaringType=""C"" methodName=""M"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""23"" endLine=""11"" endColumn=""29"" document=""0"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;M&gt;b__0_2"" parameterNames=""&lt;&gt;h__TransparentIdentifier0""> <customDebugInfo> <forward declaringType=""C"" methodName=""M"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""12"" startColumn=""24"" endLine=""12"" endColumn=""30"" document=""0"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void Queries_GroupBy1() { var source = @" using System.Linq; class C { void F() { var result = from/*0*/ a in new[] { 1, 2, 3 } join/*1*/ b in new[] { 5 } on a + 1 equals b - 1 group/*2*/ new { a, b = a + 5 } by new { c = a + 4 } into d select/*3*/ d.Key; } } "; var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); c.VerifyPdb(@" <symbols> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <lambda offset=""109"" /> <lambda offset=""122"" /> <lambda offset=""79"" /> <lambda offset=""185"" /> <lambda offset=""161"" /> <lambda offset=""244"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""11"" endColumn=""40"" document=""0"" /> <entry offset=""0xe6"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""0"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xe7""> <namespace name=""System.Linq"" /> <local name=""result"" il_index=""0"" il_start=""0x0"" il_end=""0xe7"" attributes=""0"" /> </scope> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;F&gt;b__0_0"" parameterNames=""a""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""52"" endLine=""9"" endColumn=""57"" document=""0"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;F&gt;b__0_1"" parameterNames=""b""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""65"" endLine=""9"" endColumn=""70"" document=""0"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;F&gt;b__0_2"" parameterNames=""a, b""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""22"" endLine=""9"" endColumn=""70"" document=""0"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;F&gt;b__0_3"" parameterNames=""&lt;&gt;h__TransparentIdentifier0""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""57"" endLine=""10"" endColumn=""74"" document=""0"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;F&gt;b__0_4"" parameterNames=""&lt;&gt;h__TransparentIdentifier0""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""33"" endLine=""10"" endColumn=""53"" document=""0"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;F&gt;b__0_5"" parameterNames=""d""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""34"" endLine=""11"" endColumn=""39"" document=""0"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void ForEachStatement_Array() { string source = @" using System; class C { void G(Func<int, int> f) {} void F() { foreach (int x0 in new[] { 1 }) // Group #0 { // Group #1 int x1 = 0; G(a => x0); G(a => x1); } } }"; var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); // note that the two closures have a different syntax offset c.VerifyPdb("C.F", @" <symbols> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""f"" /> <encLocalSlotMap> <slot kind=""6"" offset=""41"" /> <slot kind=""8"" offset=""41"" /> <slot kind=""30"" offset=""41"" /> <slot kind=""30"" offset=""108"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <closure offset=""41"" /> <closure offset=""108"" /> <lambda offset=""259"" closure=""0"" /> <lambda offset=""287"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""0"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""16"" document=""0"" /> <entry offset=""0x2"" startLine=""10"" startColumn=""28"" endLine=""10"" endColumn=""39"" document=""0"" /> <entry offset=""0xf"" hidden=""true"" document=""0"" /> <entry offset=""0x11"" hidden=""true"" document=""0"" /> <entry offset=""0x17"" startLine=""10"" startColumn=""18"" endLine=""10"" endColumn=""24"" document=""0"" /> <entry offset=""0x20"" hidden=""true"" document=""0"" /> <entry offset=""0x26"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""0"" /> <entry offset=""0x27"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""24"" document=""0"" /> <entry offset=""0x2e"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""24"" document=""0"" /> <entry offset=""0x41"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""24"" document=""0"" /> <entry offset=""0x54"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""0"" /> <entry offset=""0x55"" hidden=""true"" document=""0"" /> <entry offset=""0x59"" startLine=""10"" startColumn=""25"" endLine=""10"" endColumn=""27"" document=""0"" /> <entry offset=""0x5f"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""0"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x60""> <scope startOffset=""0x11"" endOffset=""0x55""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""2"" il_start=""0x11"" il_end=""0x55"" attributes=""0"" /> <scope startOffset=""0x20"" endOffset=""0x55""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""3"" il_start=""0x20"" il_end=""0x55"" attributes=""0"" /> </scope> </scope> </scope> </method> </methods> </symbols> "); } [Fact] public void ForEachStatement_MultidimensionalArray() { string source = @" using System; class C { void G(Func<int, int> f) {} void F() { foreach (int x0 in new[,] { { 1 } }) // Group #0 { // Group #1 int x1 = 0; G(a => x0); G(a => x1); } } }"; var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); // note that the two closures have a different syntax offset c.VerifyPdb("C.F", @" <symbols> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""f"" /> <encLocalSlotMap> <slot kind=""6"" offset=""41"" /> <slot kind=""7"" offset=""41"" /> <slot kind=""7"" offset=""41"" ordinal=""1"" /> <slot kind=""8"" offset=""41"" /> <slot kind=""8"" offset=""41"" ordinal=""1"" /> <slot kind=""30"" offset=""41"" /> <slot kind=""30"" offset=""113"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <closure offset=""41"" /> <closure offset=""113"" /> <lambda offset=""269"" closure=""0"" /> <lambda offset=""297"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""0"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""16"" document=""0"" /> <entry offset=""0x2"" startLine=""10"" startColumn=""28"" endLine=""10"" endColumn=""44"" document=""0"" /> <entry offset=""0x2b"" hidden=""true"" document=""0"" /> <entry offset=""0x36"" hidden=""true"" document=""0"" /> <entry offset=""0x38"" hidden=""true"" document=""0"" /> <entry offset=""0x3f"" startLine=""10"" startColumn=""18"" endLine=""10"" endColumn=""24"" document=""0"" /> <entry offset=""0x4f"" hidden=""true"" document=""0"" /> <entry offset=""0x56"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""0"" /> <entry offset=""0x57"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""24"" document=""0"" /> <entry offset=""0x5f"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""24"" document=""0"" /> <entry offset=""0x73"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""24"" document=""0"" /> <entry offset=""0x87"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""0"" /> <entry offset=""0x88"" hidden=""true"" document=""0"" /> <entry offset=""0x8e"" startLine=""10"" startColumn=""25"" endLine=""10"" endColumn=""27"" document=""0"" /> <entry offset=""0x93"" hidden=""true"" document=""0"" /> <entry offset=""0x97"" startLine=""10"" startColumn=""25"" endLine=""10"" endColumn=""27"" document=""0"" /> <entry offset=""0x9b"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""0"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9c""> <scope startOffset=""0x38"" endOffset=""0x88""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""5"" il_start=""0x38"" il_end=""0x88"" attributes=""0"" /> <scope startOffset=""0x4f"" endOffset=""0x88""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""6"" il_start=""0x4f"" il_end=""0x88"" attributes=""0"" /> </scope> </scope> </scope> </method> </methods> </symbols> "); } [Fact] public void ForEachStatement_String() { string source = @" using System; class C { void G(Func<int, int> f) {} void F() { foreach (int x0 in ""1"") // Group #0 { // Group #1 int x1 = 0; G(a => x0); G(a => x1); } } }"; var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); // note that the two closures have a different syntax offset c.VerifyPdb("C.F", @" <symbols> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""f"" /> <encLocalSlotMap> <slot kind=""6"" offset=""41"" /> <slot kind=""8"" offset=""41"" /> <slot kind=""30"" offset=""41"" /> <slot kind=""30"" offset=""100"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <closure offset=""41"" /> <closure offset=""100"" /> <lambda offset=""245"" closure=""0"" /> <lambda offset=""273"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""0"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""16"" document=""0"" /> <entry offset=""0x2"" startLine=""10"" startColumn=""28"" endLine=""10"" endColumn=""31"" document=""0"" /> <entry offset=""0xa"" hidden=""true"" document=""0"" /> <entry offset=""0xc"" hidden=""true"" document=""0"" /> <entry offset=""0x12"" startLine=""10"" startColumn=""18"" endLine=""10"" endColumn=""24"" document=""0"" /> <entry offset=""0x1f"" hidden=""true"" document=""0"" /> <entry offset=""0x25"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""0"" /> <entry offset=""0x26"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""24"" document=""0"" /> <entry offset=""0x2d"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""24"" document=""0"" /> <entry offset=""0x40"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""24"" document=""0"" /> <entry offset=""0x53"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""0"" /> <entry offset=""0x54"" hidden=""true"" document=""0"" /> <entry offset=""0x58"" startLine=""10"" startColumn=""25"" endLine=""10"" endColumn=""27"" document=""0"" /> <entry offset=""0x61"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""0"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x62""> <scope startOffset=""0xc"" endOffset=""0x54""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""2"" il_start=""0xc"" il_end=""0x54"" attributes=""0"" /> <scope startOffset=""0x1f"" endOffset=""0x54""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""3"" il_start=""0x1f"" il_end=""0x54"" attributes=""0"" /> </scope> </scope> </scope> </method> </methods> </symbols> "); } [Fact] public void ForEachStatement_Enumerable() { string source = @" using System; using System.Collections.Generic; class C { void G(Func<int, int> f) {} void F() { foreach (int x0 in new List<int>()) // Group #0 { // Group #1 int x1 = 0; G(a => x0); G(a => x1); } } }"; var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); // note that the two closures have a different syntax offset c.VerifyPdb("C.F", @" <symbols> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""f"" /> <encLocalSlotMap> <slot kind=""5"" offset=""41"" /> <slot kind=""30"" offset=""41"" /> <slot kind=""30"" offset=""112"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <closure offset=""41"" /> <closure offset=""112"" /> <lambda offset=""268"" closure=""0"" /> <lambda offset=""296"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""0"" /> <entry offset=""0x1"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""16"" document=""0"" /> <entry offset=""0x2"" startLine=""11"" startColumn=""28"" endLine=""11"" endColumn=""43"" document=""0"" /> <entry offset=""0xd"" hidden=""true"" document=""0"" /> <entry offset=""0xf"" hidden=""true"" document=""0"" /> <entry offset=""0x15"" startLine=""11"" startColumn=""18"" endLine=""11"" endColumn=""24"" document=""0"" /> <entry offset=""0x22"" hidden=""true"" document=""0"" /> <entry offset=""0x28"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""0"" /> <entry offset=""0x29"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""24"" document=""0"" /> <entry offset=""0x30"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""24"" document=""0"" /> <entry offset=""0x43"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""24"" document=""0"" /> <entry offset=""0x56"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""0"" /> <entry offset=""0x57"" startLine=""11"" startColumn=""25"" endLine=""11"" endColumn=""27"" document=""0"" /> <entry offset=""0x62"" hidden=""true"" document=""0"" /> <entry offset=""0x71"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""0"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x72""> <scope startOffset=""0xf"" endOffset=""0x57""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""1"" il_start=""0xf"" il_end=""0x57"" attributes=""0"" /> <scope startOffset=""0x22"" endOffset=""0x57""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""2"" il_start=""0x22"" il_end=""0x57"" attributes=""0"" /> </scope> </scope> </scope> </method> </methods> </symbols> "); } [Fact] public void ForStatement1() { string source = @" using System; class C { bool G(Func<int, int> f) => true; void F() { for (int x0 = 0, x1 = 0; G(a => x0) && G(a => x1);) { int x2 = 0; G(a => x2); } } }"; var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); // note that the two closures have a different syntax offset c.VerifyPdb("C.F", @" <symbols> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""f"" /> <encLocalSlotMap> <slot kind=""30"" offset=""41"" /> <slot kind=""30"" offset=""102"" /> <slot kind=""1"" offset=""41"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <closure offset=""102"" /> <closure offset=""41"" /> <lambda offset=""149"" closure=""0"" /> <lambda offset=""73"" closure=""1"" /> <lambda offset=""87"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""0"" /> <entry offset=""0x1"" hidden=""true"" document=""0"" /> <entry offset=""0x7"" startLine=""10"" startColumn=""14"" endLine=""10"" endColumn=""24"" document=""0"" /> <entry offset=""0xe"" startLine=""10"" startColumn=""26"" endLine=""10"" endColumn=""32"" document=""0"" /> <entry offset=""0x15"" hidden=""true"" document=""0"" /> <entry offset=""0x17"" hidden=""true"" document=""0"" /> <entry offset=""0x1d"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""0"" /> <entry offset=""0x1e"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""24"" document=""0"" /> <entry offset=""0x25"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""24"" document=""0"" /> <entry offset=""0x38"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""0"" /> <entry offset=""0x39"" startLine=""10"" startColumn=""34"" endLine=""10"" endColumn=""58"" document=""0"" /> <entry offset=""0x63"" hidden=""true"" document=""0"" /> <entry offset=""0x66"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""0"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x67""> <scope startOffset=""0x1"" endOffset=""0x66""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x1"" il_end=""0x66"" attributes=""0"" /> <scope startOffset=""0x17"" endOffset=""0x39""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""1"" il_start=""0x17"" il_end=""0x39"" attributes=""0"" /> </scope> </scope> </scope> </method> </methods> </symbols> "); } [Fact] public void SwitchStatement1() { var source = @" using System; class C { bool G(Func<int> f) => true; int a = 1; void F() { int x2 = 1; G(() => x2); switch (a) { case 1: int x0 = 1; G(() => x0); break; case 2: int x1 = 1; G(() => x1); break; } } } "; var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); c.VerifyPdb("C.F", @" <symbols> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""f"" /> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> <slot kind=""30"" offset=""86"" /> <slot kind=""1"" offset=""86"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>2</methodOrdinal> <closure offset=""0"" /> <closure offset=""86"" /> <lambda offset=""48"" closure=""0"" /> <lambda offset=""183"" closure=""1"" /> <lambda offset=""289"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""0"" /> <entry offset=""0x6"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""0"" /> <entry offset=""0x7"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""20"" document=""0"" /> <entry offset=""0xe"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""21"" document=""0"" /> <entry offset=""0x21"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""19"" document=""0"" /> <entry offset=""0x2e"" hidden=""true"" document=""0"" /> <entry offset=""0x3a"" startLine=""18"" startColumn=""17"" endLine=""18"" endColumn=""28"" document=""0"" /> <entry offset=""0x41"" startLine=""19"" startColumn=""17"" endLine=""19"" endColumn=""29"" document=""0"" /> <entry offset=""0x54"" startLine=""20"" startColumn=""17"" endLine=""20"" endColumn=""23"" document=""0"" /> <entry offset=""0x56"" startLine=""23"" startColumn=""17"" endLine=""23"" endColumn=""28"" document=""0"" /> <entry offset=""0x5d"" startLine=""24"" startColumn=""17"" endLine=""24"" endColumn=""29"" document=""0"" /> <entry offset=""0x70"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""23"" document=""0"" /> <entry offset=""0x72"" startLine=""27"" startColumn=""5"" endLine=""27"" endColumn=""6"" document=""0"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x73""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x73"" attributes=""0"" /> <scope startOffset=""0x21"" endOffset=""0x72""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""1"" il_start=""0x21"" il_end=""0x72"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols> "); } [Fact] public void UsingStatement1() { string source = @" using System; class C { static bool G<T>(Func<T> f) => true; static int F(object a, object b) => 1; static IDisposable D() => null; static void F() { using (IDisposable x0 = D(), y0 = D()) { int x1 = 1; G(() => x0); G(() => y0); G(() => x1); } } }"; var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); // note that the two closures have a different syntax offset c.VerifyPdb("C.F", @" <symbols> <methods> <method containingType=""C"" name=""F"" parameterNames=""a, b""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""f"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""41"" endLine=""7"" endColumn=""42"" document=""0"" /> </sequencePoints> </method> <method containingType=""C"" name=""F""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""f"" /> <encLocalSlotMap> <slot kind=""30"" offset=""41"" /> <slot kind=""30"" offset=""89"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>3</methodOrdinal> <closure offset=""41"" /> <closure offset=""89"" /> <lambda offset=""147"" closure=""0"" /> <lambda offset=""173"" closure=""0"" /> <lambda offset=""199"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""0"" /> <entry offset=""0x1"" hidden=""true"" document=""0"" /> <entry offset=""0x7"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""36"" document=""0"" /> <entry offset=""0x12"" startLine=""12"" startColumn=""38"" endLine=""12"" endColumn=""46"" document=""0"" /> <entry offset=""0x1d"" hidden=""true"" document=""0"" /> <entry offset=""0x23"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""0"" /> <entry offset=""0x24"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""24"" document=""0"" /> <entry offset=""0x2b"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""25"" document=""0"" /> <entry offset=""0x3d"" startLine=""17"" startColumn=""13"" endLine=""17"" endColumn=""25"" document=""0"" /> <entry offset=""0x4f"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""25"" document=""0"" /> <entry offset=""0x61"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""0"" /> <entry offset=""0x64"" hidden=""true"" document=""0"" /> <entry offset=""0x79"" hidden=""true"" document=""0"" /> <entry offset=""0x7b"" hidden=""true"" document=""0"" /> <entry offset=""0x90"" startLine=""20"" startColumn=""5"" endLine=""20"" endColumn=""6"" document=""0"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x91""> <scope startOffset=""0x1"" endOffset=""0x90""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x1"" il_end=""0x90"" attributes=""0"" /> <scope startOffset=""0x1d"" endOffset=""0x62""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""1"" il_start=""0x1d"" il_end=""0x62"" attributes=""0"" /> </scope> </scope> </scope> </method> </methods> </symbols> "); } } }
using CoherentNoise.Interpolation; using UnityEngine; namespace CoherentNoise.Generation { /// <summary> /// This is the same noise as <see cref="GradientNoise"/>, but it does not change in Z direction. This is more efficient if you're only interested in 2D noise anyway. /// </summary> public class GradientNoise2D : Generator { // 256 random vectors private static readonly float[] Vectors = new[] { -0.731431341826129f, 0.68191509163123f, 0.850826255327452f, -0.525447126974223f, 0.951901184669578f, -0.306405180479466f, 0.847375274477774f, -0.530994486038901f, 0.848652296864435f, 0.528951112132982f, 0.367039509662365f, 0.930205352783358f, 0.993031254071925f, -0.117851297983264f, -0.671151386173851f, -0.741320319994615f, -0.520675077759241f, -0.853754919986063f, 0.797453600237253f, -0.603380274344997f, 0.261253746745916f, 0.965270158976864f, -0.4665434272427f, 0.884498293099899f, 0.988416259834662f, -0.151767247107068f, 0.243393593738193f, 0.96992760478667f, 0.366768847231788f, -0.93031210499502f, 0.411298702005218f, -0.911500618611322f, 0.207341022783915f, -0.978268726000643f, -0.738546389576949f, 0.674202662737885f, -0.394654589200276f, -0.918829557221121f, -0.571211615051746f, 0.820802833103039f, -0.322822891839912f, -0.946459391893871f, 0.297290895653234f, -0.95478695181789f, 0.955458211448602f, -0.295126424054909f, 0.144935573935015f, 0.989441094460973f, -0.472190238715513f, 0.881496669569311f, -0.999147653977811f, -0.0412791176097179f, -0.0566039180894319f, -0.998396712963802f, 0.838467522782852f, 0.544951569626502f, 0.748568021004782f, -0.663058004950535f, -0.527875842628975f, 0.849321549690545f, 0.357699899706583f, 0.933836592638081f, 0.349221591518296f, -0.93704016990598f, 0.989238396385076f, 0.146312662191223f, 0.333538104376736f, -0.942736619066414f, 0.234353839405063f, 0.972151365763638f, 0.62765151947276f, 0.778494425223158f, -0.179494348130198f, 0.983759004527692f, -0.659780814342818f, 0.751458100645091f, -0.718415278792677f, -0.69561446735763f, -0.998033869930316f, -0.0626769054111391f, 0.673068523904019f, -0.739580125564272f, -0.739350670868863f, 0.673320566658826f, -0.933271553810173f, 0.359171556291344f, -0.662381939929279f, 0.749166313748507f, -0.0801366250317778f, -0.996783888979209f, 0.29025385297949f, -0.956949685631675f, -0.54032917870841f, -0.841453729349568f, -0.692344483921232f, -0.721567124794252f, -0.887159876903364f, 0.461462190014316f, -0.991828148906124f, 0.12758104497711f, 0.0810979161066969f, -0.99670613924223f, -0.539198809344358f, 0.842178510769318f, 0.969429412401646f, 0.245370361638484f, 0.955780929362972f, 0.294079606681682f, 0.806781534755456f, 0.590849858405357f, -0.868531510457536f, -0.495633952975733f, 0.968002263782507f, -0.250941461922778f, -0.165205532592608f, -0.986259160667617f, -0.868192204140243f, -0.496228069208208f, -0.86976358662251f, -0.493468644784598f, -0.949489840940752f, 0.313797772379451f, 0.768401205829135f, -0.63996842647144f, -0.010864092537854f, -0.999940984005221f, -0.450260656290424f, 0.892897161714f, -0.278209506633843f, -0.960520416450662f, -0.813261464544128f, 0.581898436402385f, -0.332109371842527f, 0.943240883939178f, 0.472751027063131f, 0.881196043120233f, 0.999956668864357f, -0.00930915644399175f, -0.494039763195941f, -0.869439309199497f, -0.970522733594673f, -0.241009592290273f, -0.87192758761998f, 0.489634845519804f, 0.0615978842377382f, -0.998101047318073f, 0.451468040192217f, 0.892287290442377f, -0.991514020949566f, 0.129999793309158f, -0.398591252415884f, 0.91712867881096f, -0.620385451531012f, 0.784297068417741f, -0.853977038819679f, -0.520310692921809f, -0.997873589794849f, 0.0651789750605269f, -0.980602996956203f, -0.196004495766075f, 0.574603098739222f, -0.818432207894633f, 0.75959965603487f, 0.650390930557697f, -0.492380199527919f, -0.870380226747395f, -0.82704446775552f, 0.562136503311241f, -0.889333633567567f, -0.457258885321551f, 0.593585750865447f, -0.80477074770987f, 0.108623796903932f, -0.994082929511504f, 0.988522764008209f, -0.151071986276644f, -0.287923414140447f, -0.957653438144357f, -0.685374918424191f, -0.728190374280678f, 0.41221156255193f, 0.911088155832626f, -0.94058787072448f, -0.339550375417241f, 0.199921957079754f, -0.979811824320058f, 0.968115378066659f, 0.250504720017107f, 0.927955147115966f, 0.372691890092857f, 0.990494594580402f, -0.137551656140541f, -0.665248455869535f, -0.746622054297353f, 0.740918725496693f, 0.671594700848924f, -0.535308586961631f, -0.844656567324935f, -0.514854957391123f, 0.857277302189778f, -0.999030092148431f, 0.0440326581289129f, -0.996926870958181f, 0.078337819484146f, -0.685597302598936f, -0.727981001585249f, 0.0370788877945427f, -0.999312341602924f, 0.931843510698615f, -0.362860402315931f, -0.558733566868429f, 0.829347213930621f, -0.873792759466752f, -0.486298481905381f, 0.656607252062933f, -0.754232667376828f, -0.909439904334537f, -0.415835376566243f, 0.220309287650761f, -0.975430068110889f, 0.150100056956946f, 0.988670811191228f, -0.696084180859879f, 0.717960175188451f, 0.100570876625785f, 0.994929896412165f, 0.948614809804062f, 0.316433156638814f, -0.095898219566003f, -0.99539114496969f, -0.517140931402395f, 0.855900261168475f, 0.178670325099743f, 0.98390899728011f, -0.55311824063568f, 0.833102761894408f, -0.00785321536084002f, -0.999969163028789f, 0.60785753484444f, -0.79404610529417f, -0.666794850491482f, -0.745241321558354f, -0.470794948080833f, 0.882242663251764f, -0.979996510123714f, 0.199014673191053f, -0.678566382235446f, 0.734539083303195f, -0.995784759576747f, 0.0917208405689818f, 0.994696809022833f, -0.102850659306556f, -0.654067480988245f, -0.756436203730158f, -0.19039516442027f, -0.981707533517686f, 0.751490328435529f, 0.659744106656407f, -0.999970965068827f, -0.00762030309888781f, -0.419586283036086f, -0.90771545711636f, 0.0670745569756537f, 0.99774796607486f, 0.896625085774033f, -0.442790532374742f, 0.569636620454938f, 0.821896660558173f, 0.971021303456385f, 0.238992945991848f, -0.636951463831028f, 0.770903906283728f, -0.994251716281941f, 0.107067850778906f, 0.851524792305273f, -0.524314340915315f, -0.974653098085159f, 0.223721564434458f, 0.117674170632817f, 0.99305225923205f, -0.127312138335695f, 0.991862701906062f, 0.821092992312965f, -0.570794444589767f, -0.836180971630179f, 0.548453628562716f, 0.87069175612852f, -0.491829102239623f, -0.822815382334055f, 0.568308759913537f, 0.367191064113784f, -0.93014553830838f, -0.432424566542929f, 0.901670113872119f, -0.120396019190764f, -0.992725943331299f, -0.3421907211692f, 0.939630517994016f, -0.160896503013349f, -0.986971283937925f, 0.0416336791557611f, -0.999132942485611f, -0.254051840030241f, 0.967190603023648f, -0.677392585218673f, 0.73562169998632f, 0.34530489954395f, -0.93849055741171f, -0.295575835287478f, -0.955319279400405f, 0.509185809941917f, 0.860656616168024f, 0.992575229930708f, 0.121632285713957f, -0.0695072162716299f, 0.997581448748005f, -0.12858035933064f, 0.991699093069265f, 0.964222198214983f, -0.26509536485851f, -0.261898801454652f, -0.965095341298784f, 0.643768799332641f, -0.765220055282015f, -0.00416655784368122f, -0.999991319860195f, 0.912582290418183f, 0.408893095093452f, 0.792974195036607f, 0.609255222387174f, 0.996512185806037f, -0.0834473698811023f, -0.942032506564994f, 0.335521618640103f, 0.87501841362795f, 0.484089636133666f, 0.996750481408581f, 0.0805510882096704f, -0.706268410606012f, 0.707944158941973f, 0.605807660050887f, -0.795611135557861f, -0.363735385957895f, 0.931502318302033f, 0.725481460068661f, -0.688241709791439f, -0.993945757112509f, -0.109871888661487f, -0.86497235799957f, -0.501819509282633f, -0.122120972824683f, -0.99251522305522f, 0.877538967058075f, -0.479505329787529f, -0.951156090447505f, -0.308710368476048f, 0.975779852778161f, -0.218754837460183f, -0.450956996122408f, -0.892545678185859f, -0.522868702172098f, -0.85241323329056f, 0.829680964911082f, -0.558237849365497f, -0.85729089961775f, 0.514832315839429f, -0.772060653910783f, 0.635548854678265f, -0.0340187744669282f, -0.999421193983682f, -0.771337193085491f, 0.636426692214426f, 0.688529247409745f, -0.725208573764382f, 0.725163768716788f, 0.688576436236722f, -0.953544545407338f, 0.301252053808622f, 0.700121129056667f, -0.714024092484573f, -0.538455441479676f, 0.842653984468671f, 0.175916570766405f, 0.984405079288902f, -0.629451420142488f, -0.777039837898036f, -0.999089702483185f, -0.0426587200002751f, -0.989208833301989f, -0.146512402605778f, -0.840952814021566f, 0.541108459173583f, 0.567368358566675f, 0.823464113181235f, -0.538825044596127f, 0.842417694090041f, 0.390786645379538f, -0.920481285954803f, -0.867369426459715f, 0.497664825000668f, -0.657989855099474f, 0.75302679274125f, 0.0581096991068076f, 0.99831020372914f, -0.199969945117378f, -0.979802031560331f, 0.90688443354178f, -0.42137943020466f, 0.687773009975965f, -0.725925813529593f, -0.945838294573846f, 0.324638137805216f, -0.849970814157478f, 0.526829778088211f, 0.592467340459703f, -0.805594470244556f, 0.172273677799394f, 0.985049125646772f, 0.98426493623182f, -0.176698996331532f, 0.034140955127593f, 0.999417027663115f, -0.981643122917266f, 0.190726975620226f, -0.286049508934714f, 0.958214839395743f, -0.827152526975724f, -0.561977488087979f, -0.278190812296812f, 0.960525830966372f, 0.321460297459343f, -0.946923057675412f, -0.945857146313334f, 0.324583207772671f, -0.632326502652004f, 0.774702003381871f, -0.439701356430231f, 0.898144040315035f, -0.22390420389053f, -0.974611157067344f, 0.746644533423535f, 0.665223226224665f, -0.452095562270814f, 0.891969507648684f, -0.688536038333179f, -0.725202126249263f, 0.640330654773997f, 0.768099376745421f, 0.976846035149785f, 0.213943505655453f, -0.676632036881798f, -0.736321320257121f, -0.494860655167783f, -0.868972342463736f, -0.695461545706562f, 0.718563315542507f, 0.999317517145356f, -0.036939138138857f, 0.455862157059439f, 0.89005038832704f, -0.886588243870148f, -0.46255949436937f, -0.876783747283401f, -0.480884872396375f, -0.0875369808558837f, -0.996161270569498f, -0.95522819915781f, -0.295870051768894f, -0.375385680884685f, 0.92686870191346f, -0.881356571543301f, 0.472451684087843f, 0.381051321883982f, 0.924553887066876f, -0.994403519779731f, 0.105648662318475f, -0.992363799194351f, -0.123345409515526f, -0.292273975672636f, 0.956334629271842f, 0.990902635025559f, -0.134580711468633f, 0.9921551088401f, 0.12501295933818f, 0.803208245899664f, -0.59569834120869f, -0.99177139673035f, 0.128021469400765f, -0.689705032139782f, -0.724090442307494f, 0.689287927077946f, -0.724487510992831f, 0.892950706269959f, -0.45015445812741f, 0.957331229025545f, 0.288992937513079f, 0.236962773414951f, 0.971518730656025f, -0.179255393539833f, -0.983802573632982f, 0.971055948286095f, -0.238852141079356f, 0.279177248306704f, -0.960239586784411f, 0.993534534390401f, 0.113530299804277f, 0.809612558438491f, 0.586964654147659f, -0.316558440259375f, 0.948573009262098f, 0.969151231077369f, 0.246466815821563f, }; private readonly int m_Seed; private readonly SCurve m_SCurve; /// <summary> /// Create new generator with specified seed /// </summary> /// <param name="seed">noise seed</param> public GradientNoise2D(int seed) : this(seed, null) { } /// <summary> /// Create new generator with specified seed and interpolation algorithm. Different interpolation algorithms can make noise smoother at the expense of speed. /// </summary> /// <param name="seed">noise seed</param> /// <param name="sCurve">Interpolator to use. Can be null, in which case default will be used</param> public GradientNoise2D(int seed, SCurve sCurve) { m_Seed = seed; m_SCurve = sCurve; } /// <summary> /// Noise period. Used for repeating (seamless) noise. /// When Period &gt;0 resulting noise pattern repeats exactly every Period, for all coordinates. /// </summary> public int Period { get; set; } private SCurve SCurve { get { return m_SCurve ?? SCurve.Default; } } #region Implementation of Noise /// <summary> /// Returns noise value at given point. /// </summary> /// <param name="x">X coordinate</param> /// <param name="y">Y coordinate</param> /// <param name="z">Z coordinate</param> /// <returns>Noise value</returns> public override float GetValue(float x, float y, float z) { int ix = Mathf.FloorToInt(x); int iy = Mathf.FloorToInt(y); // interpolate the coordinates instead of values - this way we need only 4 calls instead of 7 float xs = SCurve.Interpolate(x - ix); float ys = SCurve.Interpolate(y - iy); // THEN we can use linear interp to find our value - triliear actually float n0 = GetNoise(x, y, ix, iy); float n1 = GetNoise(x, y, ix + 1, iy); float ix0 = Mathf.Lerp(n0, n1, xs); n0 = GetNoise(x, y, ix, iy + 1); n1 = GetNoise(x, y, ix + 1, iy + 1); float ix1 = Mathf.Lerp(n0, n1, xs); return Mathf.Lerp(ix0, ix1, ys); } Vector2 GetRandomVector(int x, int y) { if (Period > 0) { // make periodic lattice. Repeat every Period cells x = x % Period; if (x < 0) x += Period; y = y % Period; if (y < 0) y += Period; } int vectorIndex = ( Constants.MultiplierX * x + Constants.MultiplierY * y + Constants.MultiplierSeed * m_Seed) & 0x7fffffff; vectorIndex = (((vectorIndex >> Constants.ValueShift) ^ vectorIndex) & 0xff) * 2; return new Vector2(Vectors[vectorIndex], Vectors[vectorIndex + 1]); } private float GetNoise(float x, float y, int ix, int iy) { var gradient = GetRandomVector(ix, iy); return Vector2.Dot(gradient, new Vector2(x - ix, y - iy)) * 2.12f; // scale to [-1,1] } #endregion } }
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using NUnit.Framework; using ZXing.Common; namespace ZXing.QrCode.Internal.Test { /// <summary> /// <author>[email protected] (Satoru Takabayashi) - creator</author> /// <author>[email protected] (Chris Mysen) - ported from C++</author> /// </summary> [TestFixture] public sealed class MatrixUtilTestCase { [Test] public void testToString() { ByteMatrix array = new ByteMatrix(3, 3); array.set(0, 0, 0); array.set(1, 0, 1); array.set(2, 0, 0); array.set(0, 1, 1); array.set(1, 1, 0); array.set(2, 1, 1); array.set(0, 2, 2); array.set(1, 2, 2); array.set(2, 2, 2); String expected = " 0 1 0\n" + " 1 0 1\n" + " \n"; Assert.AreEqual(expected, array.ToString()); } [Test] public void testClearMatrix() { ByteMatrix matrix = new ByteMatrix(2, 2); MatrixUtil.clearMatrix(matrix); Assert.AreEqual(2, matrix[0, 0]); Assert.AreEqual(2, matrix[1, 0]); Assert.AreEqual(2, matrix[0, 1]); Assert.AreEqual(2, matrix[1, 1]); } [Test] public void testEmbedBasicPatterns() { { // Version 1. String expected = " 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1\n" + " 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1\n" + " 1 0 1 1 1 0 1 0 0 1 0 1 1 1 0 1\n" + " 1 0 1 1 1 0 1 0 0 1 0 1 1 1 0 1\n" + " 1 0 1 1 1 0 1 0 0 1 0 1 1 1 0 1\n" + " 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1\n" + " 1 1 1 1 1 1 1 0 1 0 1 0 1 0 1 1 1 1 1 1 1\n" + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" + " 1 \n" + " 0 \n" + " 1 \n" + " 0 \n" + " 1 \n" + " 0 0 0 0 0 0 0 0 1 \n" + " 1 1 1 1 1 1 1 0 \n" + " 1 0 0 0 0 0 1 0 \n" + " 1 0 1 1 1 0 1 0 \n" + " 1 0 1 1 1 0 1 0 \n" + " 1 0 1 1 1 0 1 0 \n" + " 1 0 0 0 0 0 1 0 \n" + " 1 1 1 1 1 1 1 0 \n"; ByteMatrix matrix = new ByteMatrix(21, 21); MatrixUtil.clearMatrix(matrix); MatrixUtil.embedBasicPatterns(Version.getVersionForNumber(1), matrix); Assert.AreEqual(expected, matrix.ToString()); } { // Version 2. Position adjustment pattern should apppear at right // bottom corner. String expected = " 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1\n" + " 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1\n" + " 1 0 1 1 1 0 1 0 0 1 0 1 1 1 0 1\n" + " 1 0 1 1 1 0 1 0 0 1 0 1 1 1 0 1\n" + " 1 0 1 1 1 0 1 0 0 1 0 1 1 1 0 1\n" + " 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1\n" + " 1 1 1 1 1 1 1 0 1 0 1 0 1 0 1 0 1 0 1 1 1 1 1 1 1\n" + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" + " 1 \n" + " 0 \n" + " 1 \n" + " 0 \n" + " 1 \n" + " 0 \n" + " 1 \n" + " 0 \n" + " 1 1 1 1 1 1 \n" + " 0 0 0 0 0 0 0 0 1 1 0 0 0 1 \n" + " 1 1 1 1 1 1 1 0 1 0 1 0 1 \n" + " 1 0 0 0 0 0 1 0 1 0 0 0 1 \n" + " 1 0 1 1 1 0 1 0 1 1 1 1 1 \n" + " 1 0 1 1 1 0 1 0 \n" + " 1 0 1 1 1 0 1 0 \n" + " 1 0 0 0 0 0 1 0 \n" + " 1 1 1 1 1 1 1 0 \n"; ByteMatrix matrix = new ByteMatrix(25, 25); MatrixUtil.clearMatrix(matrix); MatrixUtil.embedBasicPatterns(Version.getVersionForNumber(2), matrix); Assert.AreEqual(expected, matrix.ToString()); } } [Test] public void testEmbedTypeInfo() { // Type info bits = 100000011001110. String expected = " 0 \n" + " 1 \n" + " 1 \n" + " 1 \n" + " 0 \n" + " 0 \n" + " \n" + " 1 \n" + " 1 0 0 0 0 0 0 1 1 1 0 0 1 1 1 0\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " 0 \n" + " 0 \n" + " 0 \n" + " 0 \n" + " 0 \n" + " 0 \n" + " 1 \n"; ByteMatrix matrix = new ByteMatrix(21, 21); MatrixUtil.clearMatrix(matrix); MatrixUtil.embedTypeInfo(ErrorCorrectionLevel.M, 5, matrix); Assert.AreEqual(expected, matrix.ToString()); } [Test] public void testEmbedVersionInfo() { // Version info bits = 000111 110010 010100 String expected = " 0 0 1 \n" + " 0 1 0 \n" + " 0 1 0 \n" + " 0 1 1 \n" + " 1 1 1 \n" + " 0 0 0 \n" + " \n" + " \n" + " \n" + " \n" + " 0 0 0 0 1 0 \n" + " 0 1 1 1 1 0 \n" + " 1 0 0 1 1 0 \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n"; // Actually, version 7 QR Code has 45x45 matrix but we use 21x21 here // since 45x45 matrix is too big to depict. ByteMatrix matrix = new ByteMatrix(21, 21); MatrixUtil.clearMatrix(matrix); MatrixUtil.maybeEmbedVersionInfo(Version.getVersionForNumber(7), matrix); Assert.AreEqual(expected, matrix.ToString()); } [Test] public void testEmbedDataBits() { // Cells other than basic patterns should be filled with zero. String expected = " 1 1 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 1\n" + " 1 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 1\n" + " 1 0 1 1 1 0 1 0 0 0 0 0 0 0 1 0 1 1 1 0 1\n" + " 1 0 1 1 1 0 1 0 0 0 0 0 0 0 1 0 1 1 1 0 1\n" + " 1 0 1 1 1 0 1 0 0 0 0 0 0 0 1 0 1 1 1 0 1\n" + " 1 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 1\n" + " 1 1 1 1 1 1 1 0 1 0 1 0 1 0 1 1 1 1 1 1 1\n" + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" + " 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" + " 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" + " 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" + " 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0\n" + " 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" + " 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" + " 1 0 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" + " 1 0 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" + " 1 0 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" + " 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" + " 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n"; BitArray bits = new BitArray(); ByteMatrix matrix = new ByteMatrix(21, 21); MatrixUtil.clearMatrix(matrix); MatrixUtil.embedBasicPatterns(Version.getVersionForNumber(1), matrix); MatrixUtil.embedDataBits(bits, -1, matrix); Assert.AreEqual(expected, matrix.ToString()); } [Test] public void testBuildMatrix() { // From http://www.swetake.com/qr/qr7.html String expected = " 1 1 1 1 1 1 1 0 0 1 1 0 0 0 1 1 1 1 1 1 1\n" + " 1 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 1\n" + " 1 0 1 1 1 0 1 0 0 0 0 1 0 0 1 0 1 1 1 0 1\n" + " 1 0 1 1 1 0 1 0 0 1 1 0 0 0 1 0 1 1 1 0 1\n" + " 1 0 1 1 1 0 1 0 1 1 0 0 1 0 1 0 1 1 1 0 1\n" + " 1 0 0 0 0 0 1 0 0 0 1 1 1 0 1 0 0 0 0 0 1\n" + " 1 1 1 1 1 1 1 0 1 0 1 0 1 0 1 1 1 1 1 1 1\n" + " 0 0 0 0 0 0 0 0 1 1 0 1 1 0 0 0 0 0 0 0 0\n" + " 0 0 1 1 0 0 1 1 1 0 0 1 1 1 1 0 1 0 0 0 0\n" + " 1 0 1 0 1 0 0 0 0 0 1 1 1 0 0 1 0 1 1 1 0\n" + " 1 1 1 1 0 1 1 0 1 0 1 1 1 0 0 1 1 1 0 1 0\n" + " 1 0 1 0 1 1 0 1 1 1 0 0 1 1 1 0 0 1 0 1 0\n" + " 0 0 1 0 0 1 1 1 0 0 0 0 0 0 1 0 1 1 1 1 1\n" + " 0 0 0 0 0 0 0 0 1 1 0 1 0 0 0 0 0 1 0 1 1\n" + " 1 1 1 1 1 1 1 0 1 1 1 1 0 0 0 0 1 0 1 1 0\n" + " 1 0 0 0 0 0 1 0 0 0 0 1 0 1 1 1 0 0 0 0 0\n" + " 1 0 1 1 1 0 1 0 0 1 0 0 1 1 0 0 1 0 0 1 1\n" + " 1 0 1 1 1 0 1 0 1 1 0 1 0 0 0 0 0 1 1 1 0\n" + " 1 0 1 1 1 0 1 0 1 1 1 1 0 0 0 0 1 1 1 0 0\n" + " 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 1 0 0\n" + " 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 0 1 0 0 1 0\n"; int[] bytes = {32, 65, 205, 69, 41, 220, 46, 128, 236, 42, 159, 74, 221, 244, 169, 239, 150, 138, 70, 237, 85, 224, 96, 74, 219 , 61}; BitArray bits = new BitArray(); foreach (char c in bytes) { bits.appendBits(c, 8); } ByteMatrix matrix = new ByteMatrix(21, 21); MatrixUtil.buildMatrix(bits, ErrorCorrectionLevel.H, Version.getVersionForNumber(1), // Version 1 3, // Mask pattern 3 matrix); Assert.AreEqual(expected, matrix.ToString()); } [Test] public void testFindMSBSet() { Assert.AreEqual(0, MatrixUtil.findMSBSet(0)); Assert.AreEqual(1, MatrixUtil.findMSBSet(1)); Assert.AreEqual(8, MatrixUtil.findMSBSet(0x80)); Assert.AreEqual(32, MatrixUtil.findMSBSet(-2147483648 /*0x80000000*/)); } [Test] public void testCalculateBCHCode() { // Encoding of type information. // From Appendix C in JISX0510:2004 (p 65) Assert.AreEqual(0xdc, MatrixUtil.calculateBCHCode(5, 0x537)); // From http://www.swetake.com/qr/qr6.html Assert.AreEqual(0x1c2, MatrixUtil.calculateBCHCode(0x13, 0x537)); // From http://www.swetake.com/qr/qr11.html Assert.AreEqual(0x214, MatrixUtil.calculateBCHCode(0x1b, 0x537)); // Encofing of version information. // From Appendix D in JISX0510:2004 (p 68) Assert.AreEqual(0xc94, MatrixUtil.calculateBCHCode(7, 0x1f25)); Assert.AreEqual(0x5bc, MatrixUtil.calculateBCHCode(8, 0x1f25)); Assert.AreEqual(0xa99, MatrixUtil.calculateBCHCode(9, 0x1f25)); Assert.AreEqual(0x4d3, MatrixUtil.calculateBCHCode(10, 0x1f25)); Assert.AreEqual(0x9a6, MatrixUtil.calculateBCHCode(20, 0x1f25)); Assert.AreEqual(0xd75, MatrixUtil.calculateBCHCode(30, 0x1f25)); Assert.AreEqual(0xc69, MatrixUtil.calculateBCHCode(40, 0x1f25)); } // We don't test a lot of cases in this function since we've already // tested them in TEST(calculateBCHCode). [Test] public void testMakeVersionInfoBits() { // From Appendix D in JISX0510:2004 (p 68) BitArray bits = new BitArray(); MatrixUtil.makeVersionInfoBits(Version.getVersionForNumber(7), bits); Assert.AreEqual(" ...XXXXX ..X..X.X ..", bits.ToString()); } // We don't test a lot of cases in this function since we've already // tested them in TEST(calculateBCHCode). [Test] public void testMakeTypeInfoInfoBits() { // From Appendix C in JISX0510:2004 (p 65) BitArray bits = new BitArray(); MatrixUtil.makeTypeInfoBits(ErrorCorrectionLevel.M, 5, bits); Assert.AreEqual(" X......X X..XXX.", bits.ToString()); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Linq; using System.Windows.Forms; using bv.common; using bv.common.Configuration; using bv.common.Core; using bv.common.Enums; using bv.common.win; using bv.winclient.Core; using DevExpress.XtraTab; using eidss.avr.BaseComponents; using eidss.avr.BaseComponents.Views; using eidss.avr.db.AvrEventArgs.AvrEventArgs; using eidss.avr.db.Common; using eidss.avr.db.DBService; using eidss.avr.db.DBService.DataSource; using eidss.avr.Handlers.AvrEventArgs; using eidss.model.Avr.Commands; using eidss.model.Avr.Commands.Layout; using eidss.model.Avr.Commands.Refresh; using eidss.model.AVR.Db; using eidss.model.Avr.Tree; using eidss.model.Core; using eidss.model.Reports.OperationContext; using eidss.model.Resources; using LayoutEventArgs = eidss.avr.db.AvrEventArgs.AvrEventArgs.LayoutEventArgs; namespace eidss.avr.LayoutForm { public partial class LayoutDetailPanel : BaseAvrDetailPresenterPanel, ILayoutDetailView { private readonly List<XtraTabPage> m_TabPageViewHistory = new List<XtraTabPage>(); private readonly List<XtraTabPage> m_TabPageMapHistory = new List<XtraTabPage>(); private LayoutDetailPresenter m_LayoutDetailPresenter; public event EventHandler<TabSelectionEventArgs> LayoutTabChanged; public event EventHandler<CopyLayoutEventArgs> CopyLayoutCreating; public event EventHandler<PivotFieldPopupMenuEventArgs> PivotFieldMouseRightClick; public LayoutDetailPanel() { try { m_LayoutDetailPresenter = (LayoutDetailPresenter) BaseAvrPresenter; InitializeComponent(); if (IsDesignMode() || bv.common.Configuration.BaseSettings.ScanFormsMode) { return; } pivotForm.UseParentDataset = true; RegisterChildObject(pivotForm, RelatedPostOrder.SkipPost); pivotForm.PivotGrid.PivotFieldMouseRightClick += OnPivotGridOnPivotFieldMouseRightClick; viewForm.UseParentDataset = false; RegisterChildObject(viewForm, RelatedPostOrder.PostLast); pivotInfo.UseParentDataset = true; RegisterChildObject(pivotInfo, RelatedPostOrder.SkipPost); LayoutTabChanged += LayoutDetail_LayoutTabChanged; LookupTableNames = new[] {"Layout"}; } catch (Exception ex) { if (BaseSettings.ThrowExceptionOnError) { throw; } ErrorForm.ShowError(ex); } } /// <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) { try { m_TabPageViewHistory.Clear(); m_TabPageMapHistory.Clear(); LayoutTabChanged -= LayoutDetail_LayoutTabChanged; if (pivotForm != null) { if (pivotForm.PivotGrid != null) { pivotForm.PivotGrid.PivotFieldMouseRightClick -= OnPivotGridOnPivotFieldMouseRightClick; } UnRegisterChildObject(pivotForm); pivotForm = null; } if (pivotInfo != null) { UnRegisterChildObject(pivotInfo); pivotInfo = null; } if (viewForm != null) { UnRegisterChildObject(viewForm); viewForm = null; } if (m_LayoutDetailPresenter != null) { m_LayoutDetailPresenter.SharedPresenter.UnregisterView(this); m_LayoutDetailPresenter.Dispose(); m_LayoutDetailPresenter = null; } if (disposing && (components != null)) { components.Dispose(); } } finally { base.Dispose(disposing); } } #region Properties [Browsable(true), DefaultValue(false)] public override bool ReadOnly { get { return base.ReadOnly; } set { if (IsDesignMode()) { return; } base.ReadOnly = value; if (!IsViewPageSelected) { var args = new TabPageChangingEventArgs(tabControl.SelectedTabPage, tabControl.SelectedTabPage); tabControl_SelectedPageChanging(this, args); } cmdCancelChanges.Visible = GetButtonVisibility(DefaultButtonType.Save); cmdSave.Visible = GetButtonVisibility(DefaultButtonType.Save); cmdDelete.Visible = GetButtonVisibility("ShowDeleteButtonOnDetailForm", DefaultButtonType.Delete); cmdNew.Visible = GetButtonVisibility("ShowNewButtonOnDetailForm", DefaultButtonType.New); ArrangeButtons(cmdSave.Top, "BottomButtons", cmdSave.Height, Height - cmdSave.Height - 8); } } [Browsable(false)] public IPivotDetailView PivotDetailView { get { return pivotForm; } } [Browsable(false)] internal string SelectedTabPageName { get { return (tabControl.SelectedTabPage != null) ? tabControl.SelectedTabPage.Name : string.Empty; } } [Browsable(false)] private Layout_DB LayoutDbService { get { return m_LayoutDetailPresenter.LayoutDbService; } } [Browsable(false)] internal bool IsViewPageSelected { get { return tabControl.SelectedTabPage == tabPageView; } } #endregion #region Base Methods public override object GetKey(string tableName = null, string keyFieldName = null) { return pivotForm == null ? null : (object) pivotForm.LayoutId; } public bool LayoutPost(PostType postType = PostType.FinalPosting) { return m_LayoutDetailPresenter.SharedPresenter.SharedModel.ParentForm.Post(postType); } /// <summary> /// Don't Call this method directly!!! It should be called when parent form performs post. Use LayoutPost() instead. /// </summary> /// <param name="postType"></param> /// <returns></returns> public override bool Post(PostType postType = PostType.FinalPosting) { m_LayoutDetailPresenter.PrepareDbService(); m_LayoutDetailPresenter.PrepareLayoutSearchFieldsBeforePost(pivotForm.PivotGrid.AvrFields.ToList()); return base.Post(postType); } public override void Merge(DataSet ds) { if (!(ds is LayoutDetailDataSet)) { throw new ArgumentException(string.Format("dataset must be of type {0}", typeof (LayoutDetailDataSet))); } if (baseDataSet.Tables.Count == 0) { baseDataSet = new LayoutDetailDataSet(); } if (!(baseDataSet is LayoutDetailDataSet)) { throw new AvrDbException(string.Format("dataset must be of type {0}", typeof (LayoutDetailDataSet))); } base.Merge(ds); } protected override void DefineBinding() { if (!SharedPresenter.ContextKeeper.ContainsContext(ContextValue.NewLayoutClicking)) { m_LayoutDetailPresenter.NewClicked = false; } m_TabPageViewHistory.Add(tabPagePivotGrid); m_TabPageMapHistory.Add(tabPagePivotGrid); } #endregion #region Raise Events private string RaiseCopyLayoutCreating(string disabledCriteria) { if (CopyLayoutCreating == null) { return string.Empty; } var args = new CopyLayoutEventArgs(pivotForm.PivotGrid, disabledCriteria); CopyLayoutCreating.SafeRaise(this, args); return args.DisabledCriteria; } #endregion #region Event Handlers private void OnPivotGridOnPivotFieldMouseRightClick(object sender, PivotFieldPopupMenuEventArgs args) { PivotFieldMouseRightClick.SafeRaise(sender, args); } public void OnLayoutSelected(LayoutEventArgs e) { try { object id = e.LayoutId; LoadData(ref id); pivotForm.UpdateCustomizationFormEnabling(); pivotForm.CustomizationFormEnabled &= ((e.LayoutId > 0) || (m_LayoutDetailPresenter.NewClicked)); if ((e.LayoutId > 0 && m_LayoutDetailPresenter.SharedPresenter.SharedModel.StandardReports) || tabControl.SelectedTabPage == tabPageView) { pivotForm.RaisePivotGridDataLoadedCommand(); } } catch (Exception ex) { if (BaseSettings.ThrowExceptionOnError) { throw; } ErrorForm.ShowError(ex); } } // public void ProcessAfterPost(object sender, PostHandler handler) // { // try // { // if (m_LayoutDetailPresenter.IsNewObject) // { // pivotForm.SetChanged(true); // } // if (m_LayoutDetailPresenter.ParentHasChanges()) // { // m_LayoutDetailPresenter.LayoutDbService.OnAfterPost += handler; // cmdSave_Click(sender, EventArgs.Empty); // } // else // { // handler(sender, new PostEventArgs((int) PostType.FinalPosting, false)); // } // } // finally // { // m_LayoutDetailPresenter.LayoutDbService.OnAfterPost -= handler; // } // } #endregion #region Button Methods private bool GetButtonVisibility(DefaultButtonType buttonType) { return Permissions.GetButtonVisibility(buttonType); } private bool GetButtonVisibility(string configAttributeName, DefaultButtonType buttonType) { return Config.GetBoolSetting(configAttributeName) && Permissions.GetButtonVisibility(buttonType); } private void cmdSave_Click(object sender, EventArgs e) { ProcessAfterPost(null); } private void cmdNew_Click(object sender, EventArgs e) { if (LockHandler()) { try { using (SharedPresenter.ContextKeeper.CreateNewContext(ContextValue.NewLayoutClicking)) { bool isPost = e is AvrPostNeededEventArgs && !((AvrPostNeededEventArgs) e).PostNeeded ? Permissions.CanInsert : Permissions.CanInsert && LayoutPost(); if (isPost) { m_LayoutDetailPresenter.NewClicked = true; State = BusinessObjectState.NewObject | BusinessObjectState.IntermediateObject; tabControl.SelectedTabPage = tabPagePivotInfo; m_LayoutDetailPresenter.SharedPresenter.SharedModel.SelectedLayoutId = -1; object id = null; LoadData(ref id); DefineBinding(); } else { SelectLastFocusedControl(); } } } finally { UnlockHandler(); } } } private void cmdDelete_Click(object sender, EventArgs e) { object key = GetKey("Layout", "idflLayout"); if (!(key is long)) { throw new AvrException(string.Format("LayoutDetail key {0} is not long", key)); } RaiseSendCommand(new QueryLayoutDeleteCommand(sender, (long) key, AvrTreeElementType.Layout)); } private void cmdCancel_Click(object sender, EventArgs e) { if (LockHandler()) { try { DataEventManager.Flush(); if (HasChanges() == false) { return; } string msg = m_LayoutDetailPresenter.IsNewObject ? EidssMessages.Get("msgConfirmClearForm", "Clear the form content?") : EidssMessages.Get("msgConfirmCancelChangesForm", "Return the form to the last saved state?"); if (MessageForm.Show(msg, "", MessageBoxButtons.YesNo) != DialogResult.Yes) { SelectLastFocusedControl(); return; } object idToLoad = (m_LayoutDetailPresenter.IsNewObject) ? null : LayoutDbService.ID; LoadData(ref idToLoad); DefineBinding(); if (tabControl.SelectedTabPage == tabPageView) { pivotForm.RaisePivotGridDataLoadedCommand(); } } finally { UnlockHandler(); } } } private void cmdCopy_Click(object sender, EventArgs e) { if (LockHandler()) { try { if (LayoutPost() && Permissions.CanInsert) { m_LayoutDetailPresenter.NewClicked = true; if (ReadOnly) { ReadOnly = false; } using (pivotForm.PivotGrid.BeginTransaction()) { string oldCriteria = !ReferenceEquals(pivotForm.FilterCriteria, null) ? pivotForm.FilterCriteria.ToString() : string.Empty; string newCriteria = RaiseCopyLayoutCreating(oldCriteria); if (!pivotForm.ApplyFilter) { pivotForm.PivotGrid.CriteriaString = newCriteria; } pivotForm.ClearCacheDataRowColumnAreaFields(); pivotForm.SetInnerFilterCriteria(); pivotForm.InitFilterControl(pivotForm.FilterCriteria); if (!pivotForm.ApplyFilter) { pivotForm.PivotGrid.Criteria = null; } } pivotForm.RefreshPivotData(); RaiseSendCommand(new QueryLayoutCommand(this, QueryLayoutOperation.AddCopyPrefixForLayoutNames)); } } finally { UnlockHandler(); } } } private void cmdClose_Click(object sender, EventArgs e) { ProcessAfterPost(() => { Hide(); RaiseSendCommand(new QueryLayoutCloseCommand(sender)); }); } private void RefreshQueryAfterPost() { // before refreshing query dispose old pivot datasource AvrPivotGridData oldDataSource = pivotForm.DataSource; if (oldDataSource != null) { pivotForm.DataSource = new AvrPivotGridData(oldDataSource.ClonedPivotData); oldDataSource.Dispose(); } RaiseSendCommand(new ExecQueryCommand(this)); object id = m_LayoutDetailPresenter.LayoutDbService.ID; LoadData(ref id); if (IsViewPageSelected) { pivotForm.RaisePivotGridDataLoadedCommand(); } } private void PublishUnpublishAfterPost(bool isPublish) { if (UserConfirmPublishUnpublish(AvrTreeElementType.Layout, isPublish)) { object id = m_LayoutDetailPresenter.LayoutDbService.ID; m_LayoutDetailPresenter.LayoutDbService.PublishUnpublish((long) id, AvrTreeElementType.Layout, isPublish); LoadData(ref id); } } private void ProcessAfterPost(Action handler) { if (LockHandler()) { try { bool isNewObject = m_LayoutDetailPresenter.IsNewObject; if (isNewObject) { pivotForm.SetChanged(); } if (LayoutPost()) { if (handler != null) { handler(); } } else { SelectLastFocusedControl(); } } finally { UnlockHandler(); } } } #endregion #region Command handlers public void ProcessQueryLayoutCommand(QueryLayoutCommand queryLayoutCommand) { queryLayoutCommand.State = CommandState.Pending; switch (queryLayoutCommand.Operation) { case QueryLayoutOperation.CopyQueryLayout: cmdCopy_Click(this, EventArgs.Empty); break; case QueryLayoutOperation.NewLayout: cmdNew_Click(this, new AvrPostNeededEventArgs(false)); break; case QueryLayoutOperation.Publish: ProcessAfterPost(() => PublishUnpublishAfterPost(true)); break; case QueryLayoutOperation.Unpublish: ProcessAfterPost(() => PublishUnpublishAfterPost(false)); break; case QueryLayoutOperation.RefreshQuery: ProcessAfterPost(RefreshQueryAfterPost); break; // case LayoutOperation.UseArchiveChanged: // cmdUseArchive_Changed(this, EventArgs.Empty); // break; default: queryLayoutCommand.State = CommandState.Unprocessed; break; } if (queryLayoutCommand.State == CommandState.Pending) { queryLayoutCommand.State = CommandState.Processed; } } #endregion #region TabControl Handlers public void SelectInfoTabWithoutRefresh() { m_TabPageViewHistory.Clear(); tabControl.SelectedTabPage = tabPagePivotInfo; } public void SelectViewTabWithoutRefresh() { m_TabPageViewHistory.Clear(); tabControl.SelectedTabPage = tabPageView; } private void LayoutDetail_LayoutTabChanged(object sender, TabSelectionEventArgs e) { cmdNew.Enabled = e.NewEnabled && AvrPermissions.InsertPermission; cmdCopy.Enabled = e.CopyEnabled && AvrPermissions.InsertPermission; cmdDelete.Enabled = e.LayoutDeleteEnabled && AvrPermissions.DeletePermission; cmdSave.Enabled = e.SaveEnabled && AvrPermissions.UpdatePermission; cmdCancelChanges.Enabled = e.CancelEnabled && AvrPermissions.UpdatePermission; cmdClose.Enabled = true; } private void tabControl_SelectedPageChanging(object sender, TabPageChangingEventArgs e) { try { if (IsDesignMode()) { return; } TabPageChanging(e); PrepareEventLayoutTabChange(e); } catch (Exception ex) { if (BaseSettings.ThrowExceptionOnError) { throw; } ErrorForm.ShowError(ex); } } private void TabPageChanging(TabPageChangingEventArgs e) { if (IsDesignMode()) { return; } if (e.Page == tabPagePivotGrid) { pivotForm.Visible = (m_LayoutDetailPresenter.SharedPresenter.SharedModel.SelectedQueryId > 0); if (pivotForm.Visible) { pivotForm.PivotGrid.Select(); } } if (e.Page == tabPagePivotInfo) { pivotInfo.Visible = true; } if (e.Page == tabPageView) { viewForm.Visible = true; if (m_TabPageViewHistory.Contains(tabPagePivotGrid)) { m_TabPageViewHistory.Clear(); pivotForm.RaisePivotGridDataLoadedCommand(); } } m_TabPageViewHistory.Add(e.Page); m_TabPageMapHistory.Add(e.Page); } private void PrepareEventLayoutTabChange(TabPageChangingEventArgs e) { if (!e.Cancel) { TabSelectionEventArgs args = TabSelectionEventArgs.GridArgs; if (e.Page == tabPageView) { args &= TabSelectionEventArgs.ReportArgs; } if (m_LayoutDetailPresenter.StandardReports) { args &= TabSelectionEventArgs.ReportArgs; } if (ReadOnly) { args &= TabSelectionEventArgs.ReadOnlyGridArgs; } if (m_LayoutDetailPresenter.SharedPresenter.SharedModel.SelectedQueryId < 0) { args &= TabSelectionEventArgs.EmptyQueryArgs; } LayoutTabChanged.SafeRaise(this, args); } } #endregion } }
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.3 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculus.com/licenses/LICENSE-3.3 Unless required by applicable law or agreed to in writing, the Oculus VR SDK distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ************************************************************************************/ using System; using System.Runtime.InteropServices; // Internal C# wrapper for OVRPlugin. internal static class OVRPlugin { public static readonly System.Version wrapperVersion = OVRP_1_13_0.version; private static System.Version _version; public static System.Version version { get { if (_version == null) { try { string pluginVersion = OVRP_1_1_0.ovrp_GetVersion(); if (pluginVersion != null) { // Truncate unsupported trailing version info for System.Version. Original string is returned if not present. pluginVersion = pluginVersion.Split('-')[0]; _version = new System.Version(pluginVersion); } else { _version = _versionZero; } } catch { _version = _versionZero; } // Unity 5.1.1f3-p3 have OVRPlugin version "0.5.0", which isn't accurate. if (_version == OVRP_0_5_0.version) _version = OVRP_0_1_0.version; if (_version > _versionZero && _version < OVRP_1_3_0.version) throw new PlatformNotSupportedException("Oculus Utilities version " + wrapperVersion + " is too new for OVRPlugin version " + _version.ToString () + ". Update to the latest version of Unity."); } return _version; } } private static System.Version _nativeSDKVersion; public static System.Version nativeSDKVersion { get { if (_nativeSDKVersion == null) { try { string sdkVersion = string.Empty; if (version >= OVRP_1_1_0.version) sdkVersion = OVRP_1_1_0.ovrp_GetNativeSDKVersion(); else sdkVersion = _versionZero.ToString(); if (sdkVersion != null) { // Truncate unsupported trailing version info for System.Version. Original string is returned if not present. sdkVersion = sdkVersion.Split('-')[0]; _nativeSDKVersion = new System.Version(sdkVersion); } else { _nativeSDKVersion = _versionZero; } } catch { _nativeSDKVersion = _versionZero; } } return _nativeSDKVersion; } } [StructLayout(LayoutKind.Sequential)] private struct GUID { public int a; public short b; public short c; public byte d0; public byte d1; public byte d2; public byte d3; public byte d4; public byte d5; public byte d6; public byte d7; } public enum Bool { False = 0, True } public enum Eye { None = -1, Left = 0, Right = 1, Count = 2 } public enum Tracker { None = -1, Zero = 0, One = 1, Two = 2, Three = 3, Count, } public enum Node { None = -1, EyeLeft = 0, EyeRight = 1, EyeCenter = 2, HandLeft = 3, HandRight = 4, TrackerZero = 5, TrackerOne = 6, TrackerTwo = 7, TrackerThree = 8, Head = 9, Count, } public enum Controller { None = 0, LTouch = 0x00000001, RTouch = 0x00000002, Touch = LTouch | RTouch, Remote = 0x00000004, Gamepad = 0x00000010, Touchpad = 0x08000000, LTrackedRemote = 0x01000000, RTrackedRemote = 0x02000000, Active = unchecked((int)0x80000000), All = ~None, } public enum TrackingOrigin { EyeLevel = 0, FloorLevel = 1, Count, } public enum RecenterFlags { Default = 0, Controllers = 0x40000000, IgnoreAll = unchecked((int)0x80000000), Count, } public enum BatteryStatus { Charging = 0, Discharging, Full, NotCharging, Unknown, } public enum EyeTextureFormat { Default = 0, R16G16B16A16_FP = 2, R11G11B10_FP = 3, } public enum PlatformUI { None = -1, GlobalMenu = 0, ConfirmQuit, GlobalMenuTutorial, } public enum SystemRegion { Unspecified = 0, Japan, China, } public enum SystemHeadset { None = 0, GearVR_R320, // Note4 Innovator GearVR_R321, // S6 Innovator GearVR_R322, // Commercial 1 GearVR_R323, // Commercial 2 (USB Type C) Rift_DK1 = 0x1000, Rift_DK2, Rift_CV1, } public enum OverlayShape { Quad = 0, Cylinder = 1, Cubemap = 2, OffcenterCubemap = 4, } public enum Step { Render = -1, Physics = 0, } private const int OverlayShapeFlagShift = 4; private enum OverlayFlag { None = unchecked((int)0x00000000), OnTop = unchecked((int)0x00000001), HeadLocked = unchecked((int)0x00000002), // Using the 5-8 bits for shapes, total 16 potential shapes can be supported 0x000000[0]0 -> 0x000000[F]0 ShapeFlag_Quad = unchecked((int)OverlayShape.Quad << OverlayShapeFlagShift), ShapeFlag_Cylinder = unchecked((int)OverlayShape.Cylinder << OverlayShapeFlagShift), ShapeFlag_Cubemap = unchecked((int)OverlayShape.Cubemap << OverlayShapeFlagShift), ShapeFlag_OffcenterCubemap = unchecked((int)OverlayShape.OffcenterCubemap << OverlayShapeFlagShift), ShapeFlagRangeMask = unchecked((int)0xF << OverlayShapeFlagShift), } [StructLayout(LayoutKind.Sequential)] public struct Vector2f { public float x; public float y; } [StructLayout(LayoutKind.Sequential)] public struct Vector3f { public float x; public float y; public float z; } [StructLayout(LayoutKind.Sequential)] public struct Quatf { public float x; public float y; public float z; public float w; } [StructLayout(LayoutKind.Sequential)] public struct Posef { public Quatf Orientation; public Vector3f Position; } [StructLayout(LayoutKind.Sequential)] public struct PoseStatef { public Posef Pose; public Vector3f Velocity; public Vector3f Acceleration; public Vector3f AngularVelocity; public Vector3f AngularAcceleration; double Time; } [StructLayout(LayoutKind.Sequential)] public struct ControllerState2 { public uint ConnectedControllers; public uint Buttons; public uint Touches; public uint NearTouches; public float LIndexTrigger; public float RIndexTrigger; public float LHandTrigger; public float RHandTrigger; public Vector2f LThumbstick; public Vector2f RThumbstick; public Vector2f LTouchpad; public Vector2f RTouchpad; public ControllerState2(ControllerState cs) { ConnectedControllers = cs.ConnectedControllers; Buttons = cs.Buttons; Touches = cs.Touches; NearTouches = cs.NearTouches; LIndexTrigger = cs.LIndexTrigger; RIndexTrigger = cs.RIndexTrigger; LHandTrigger = cs.LHandTrigger; RHandTrigger = cs.RHandTrigger; LThumbstick = cs.LThumbstick; RThumbstick = cs.RThumbstick; LTouchpad = new Vector2f() { x = 0.0f, y = 0.0f }; RTouchpad = new Vector2f() { x = 0.0f, y = 0.0f }; } } [StructLayout(LayoutKind.Sequential)] public struct ControllerState { public uint ConnectedControllers; public uint Buttons; public uint Touches; public uint NearTouches; public float LIndexTrigger; public float RIndexTrigger; public float LHandTrigger; public float RHandTrigger; public Vector2f LThumbstick; public Vector2f RThumbstick; } [StructLayout(LayoutKind.Sequential)] public struct HapticsBuffer { public IntPtr Samples; public int SamplesCount; } [StructLayout(LayoutKind.Sequential)] public struct HapticsState { public int SamplesAvailable; public int SamplesQueued; } [StructLayout(LayoutKind.Sequential)] public struct HapticsDesc { public int SampleRateHz; public int SampleSizeInBytes; public int MinimumSafeSamplesQueued; public int MinimumBufferSamplesCount; public int OptimalBufferSamplesCount; public int MaximumBufferSamplesCount; } [StructLayout(LayoutKind.Sequential)] public struct AppPerfFrameStats { public int HmdVsyncIndex; public int AppFrameIndex; public int AppDroppedFrameCount; public float AppMotionToPhotonLatency; public float AppQueueAheadTime; public float AppCpuElapsedTime; public float AppGpuElapsedTime; public int CompositorFrameIndex; public int CompositorDroppedFrameCount; public float CompositorLatency; public float CompositorCpuElapsedTime; public float CompositorGpuElapsedTime; public float CompositorCpuStartToGpuEndElapsedTime; public float CompositorGpuEndToVsyncElapsedTime; } public const int AppPerfFrameStatsMaxCount = 5; [StructLayout(LayoutKind.Sequential)] public struct AppPerfStats { [MarshalAs(UnmanagedType.ByValArray, SizeConst=AppPerfFrameStatsMaxCount)] public AppPerfFrameStats[] FrameStats; public int FrameStatsCount; public Bool AnyFrameStatsDropped; public float AdaptiveGpuPerformanceScale; } [StructLayout(LayoutKind.Sequential)] public struct Sizei { public int w; public int h; } [StructLayout(LayoutKind.Sequential)] public struct Frustumf { public float zNear; public float zFar; public float fovX; public float fovY; } public enum BoundaryType { OuterBoundary = 0x0001, PlayArea = 0x0100, } [StructLayout(LayoutKind.Sequential)] public struct BoundaryTestResult { public Bool IsTriggering; public float ClosestDistance; public Vector3f ClosestPoint; public Vector3f ClosestPointNormal; } [StructLayout(LayoutKind.Sequential)] public struct BoundaryLookAndFeel { public Colorf Color; } [StructLayout(LayoutKind.Sequential)] public struct BoundaryGeometry { public BoundaryType BoundaryType; [MarshalAs(UnmanagedType.ByValArray, SizeConst=256)] public Vector3f[] Points; public int PointsCount; } [StructLayout(LayoutKind.Sequential)] public struct Colorf { public float r; public float g; public float b; public float a; } public static bool initialized { get { return OVRP_1_1_0.ovrp_GetInitialized() == OVRPlugin.Bool.True; } } public static bool chromatic { get { if (version >= OVRP_1_7_0.version) return OVRP_1_7_0.ovrp_GetAppChromaticCorrection() == OVRPlugin.Bool.True; #if UNITY_ANDROID && !UNITY_EDITOR return false; #else return true; #endif } set { if (version >= OVRP_1_7_0.version) OVRP_1_7_0.ovrp_SetAppChromaticCorrection(ToBool(value)); } } public static bool monoscopic { get { return OVRP_1_1_0.ovrp_GetAppMonoscopic() == OVRPlugin.Bool.True; } set { OVRP_1_1_0.ovrp_SetAppMonoscopic(ToBool(value)); } } public static bool rotation { get { return OVRP_1_1_0.ovrp_GetTrackingOrientationEnabled() == Bool.True; } set { OVRP_1_1_0.ovrp_SetTrackingOrientationEnabled(ToBool(value)); } } public static bool position { get { return OVRP_1_1_0.ovrp_GetTrackingPositionEnabled() == Bool.True; } set { OVRP_1_1_0.ovrp_SetTrackingPositionEnabled(ToBool(value)); } } public static bool useIPDInPositionTracking { get { if (version >= OVRP_1_6_0.version) return OVRP_1_6_0.ovrp_GetTrackingIPDEnabled() == OVRPlugin.Bool.True; return true; } set { if (version >= OVRP_1_6_0.version) OVRP_1_6_0.ovrp_SetTrackingIPDEnabled(ToBool(value)); } } public static bool positionSupported { get { return OVRP_1_1_0.ovrp_GetTrackingPositionSupported() == Bool.True; } } public static bool positionTracked { get { return OVRP_1_1_0.ovrp_GetNodePositionTracked(Node.EyeCenter) == Bool.True; } } public static bool powerSaving { get { return OVRP_1_1_0.ovrp_GetSystemPowerSavingMode() == Bool.True; } } public static bool hmdPresent { get { return OVRP_1_1_0.ovrp_GetNodePresent(Node.EyeCenter) == Bool.True; } } public static bool userPresent { get { return OVRP_1_1_0.ovrp_GetUserPresent() == Bool.True; } } public static bool headphonesPresent { get { return OVRP_1_3_0.ovrp_GetSystemHeadphonesPresent() == OVRPlugin.Bool.True; } } public static int recommendedMSAALevel { get { if (version >= OVRP_1_6_0.version) return OVRP_1_6_0.ovrp_GetSystemRecommendedMSAALevel (); else return 2; } } public static SystemRegion systemRegion { get { if (version >= OVRP_1_5_0.version) return OVRP_1_5_0.ovrp_GetSystemRegion(); else return SystemRegion.Unspecified; } } private static Guid _cachedAudioOutGuid; private static string _cachedAudioOutString; public static string audioOutId { get { try { IntPtr ptr = OVRP_1_1_0.ovrp_GetAudioOutId(); if (ptr != IntPtr.Zero) { GUID nativeGuid = (GUID)Marshal.PtrToStructure(ptr, typeof(OVRPlugin.GUID)); Guid managedGuid = new Guid( nativeGuid.a, nativeGuid.b, nativeGuid.c, nativeGuid.d0, nativeGuid.d1, nativeGuid.d2, nativeGuid.d3, nativeGuid.d4, nativeGuid.d5, nativeGuid.d6, nativeGuid.d7); if (managedGuid != _cachedAudioOutGuid) { _cachedAudioOutGuid = managedGuid; _cachedAudioOutString = _cachedAudioOutGuid.ToString(); } return _cachedAudioOutString; } } catch {} return string.Empty; } } private static Guid _cachedAudioInGuid; private static string _cachedAudioInString; public static string audioInId { get { try { IntPtr ptr = OVRP_1_1_0.ovrp_GetAudioInId(); if (ptr != IntPtr.Zero) { GUID nativeGuid = (GUID)Marshal.PtrToStructure(ptr, typeof(OVRPlugin.GUID)); Guid managedGuid = new Guid( nativeGuid.a, nativeGuid.b, nativeGuid.c, nativeGuid.d0, nativeGuid.d1, nativeGuid.d2, nativeGuid.d3, nativeGuid.d4, nativeGuid.d5, nativeGuid.d6, nativeGuid.d7); if (managedGuid != _cachedAudioInGuid) { _cachedAudioInGuid = managedGuid; _cachedAudioInString = _cachedAudioInGuid.ToString(); } return _cachedAudioInString; } } catch {} return string.Empty; } } public static bool hasVrFocus { get { return OVRP_1_1_0.ovrp_GetAppHasVrFocus() == Bool.True; } } public static bool shouldQuit { get { return OVRP_1_1_0.ovrp_GetAppShouldQuit() == Bool.True; } } public static bool shouldRecenter { get { return OVRP_1_1_0.ovrp_GetAppShouldRecenter() == Bool.True; } } public static string productName { get { return OVRP_1_1_0.ovrp_GetSystemProductName(); } } public static string latency { get { return OVRP_1_1_0.ovrp_GetAppLatencyTimings(); } } public static float eyeDepth { get { return OVRP_1_1_0.ovrp_GetUserEyeDepth(); } set { OVRP_1_1_0.ovrp_SetUserEyeDepth(value); } } public static float eyeHeight { get { return OVRP_1_1_0.ovrp_GetUserEyeHeight(); } set { OVRP_1_1_0.ovrp_SetUserEyeHeight(value); } } public static float batteryLevel { get { return OVRP_1_1_0.ovrp_GetSystemBatteryLevel(); } } public static float batteryTemperature { get { return OVRP_1_1_0.ovrp_GetSystemBatteryTemperature(); } } public static int cpuLevel { get { return OVRP_1_1_0.ovrp_GetSystemCpuLevel(); } set { OVRP_1_1_0.ovrp_SetSystemCpuLevel(value); } } public static int gpuLevel { get { return OVRP_1_1_0.ovrp_GetSystemGpuLevel(); } set { OVRP_1_1_0.ovrp_SetSystemGpuLevel(value); } } public static int vsyncCount { get { return OVRP_1_1_0.ovrp_GetSystemVSyncCount(); } set { OVRP_1_2_0.ovrp_SetSystemVSyncCount(value); } } public static float systemVolume { get { return OVRP_1_1_0.ovrp_GetSystemVolume(); } } public static float ipd { get { return OVRP_1_1_0.ovrp_GetUserIPD(); } set { OVRP_1_1_0.ovrp_SetUserIPD(value); } } public static bool occlusionMesh { get { return OVRP_1_3_0.ovrp_GetEyeOcclusionMeshEnabled() == Bool.True; } set { OVRP_1_3_0.ovrp_SetEyeOcclusionMeshEnabled(ToBool(value)); } } public static BatteryStatus batteryStatus { get { return OVRP_1_1_0.ovrp_GetSystemBatteryStatus(); } } public static Frustumf GetEyeFrustum(Eye eyeId) { return OVRP_1_1_0.ovrp_GetNodeFrustum((Node)eyeId); } public static Sizei GetEyeTextureSize(Eye eyeId) { return OVRP_0_1_0.ovrp_GetEyeTextureSize(eyeId); } public static Posef GetTrackerPose(Tracker trackerId) { return GetNodePose((Node)((int)trackerId + (int)Node.TrackerZero), Step.Render); } public static Frustumf GetTrackerFrustum(Tracker trackerId) { return OVRP_1_1_0.ovrp_GetNodeFrustum((Node)((int)trackerId + (int)Node.TrackerZero)); } public static bool ShowUI(PlatformUI ui) { return OVRP_1_1_0.ovrp_ShowSystemUI(ui) == Bool.True; } public static bool SetOverlayQuad(bool onTop, bool headLocked, IntPtr leftTexture, IntPtr rightTexture, IntPtr device, Posef pose, Vector3f scale, int layerIndex=0, OverlayShape shape=OverlayShape.Quad) { if (version >= OVRP_1_6_0.version) { uint flags = (uint)OverlayFlag.None; if (onTop) flags |= (uint)OverlayFlag.OnTop; if (headLocked) flags |= (uint)OverlayFlag.HeadLocked; if (shape == OverlayShape.Cylinder || shape == OverlayShape.Cubemap) { #if UNITY_ANDROID if (version >= OVRP_1_7_0.version) flags |= (uint)(shape) << OverlayShapeFlagShift; else #else if (shape == OverlayShape.Cubemap && version >= OVRP_1_10_0.version) flags |= (uint)(shape) << OverlayShapeFlagShift; else #endif return false; } if (shape == OverlayShape.OffcenterCubemap) { #if UNITY_ANDROID if (version >= OVRP_1_11_0.version) flags |= (uint)(shape) << OverlayShapeFlagShift; else #endif return false; } return OVRP_1_6_0.ovrp_SetOverlayQuad3(flags, leftTexture, rightTexture, device, pose, scale, layerIndex) == Bool.True; } if (layerIndex != 0) return false; return OVRP_0_1_1.ovrp_SetOverlayQuad2(ToBool(onTop), ToBool(headLocked), leftTexture, device, pose, scale) == Bool.True; } public static bool UpdateNodePhysicsPoses(int frameIndex, double predictionSeconds) { if (version >= OVRP_1_8_0.version) return OVRP_1_8_0.ovrp_Update2((int)Step.Physics, frameIndex, predictionSeconds) == Bool.True; return false; } public static Posef GetNodePose(Node nodeId, Step stepId) { if (version >= OVRP_1_12_0.version) return OVRP_1_12_0.ovrp_GetNodePoseState (stepId, nodeId).Pose; if (version >= OVRP_1_8_0.version && stepId == Step.Physics) return OVRP_1_8_0.ovrp_GetNodePose2(0, nodeId); return OVRP_0_1_2.ovrp_GetNodePose(nodeId); } public static Vector3f GetNodeVelocity(Node nodeId, Step stepId) { if (version >= OVRP_1_12_0.version) return OVRP_1_12_0.ovrp_GetNodePoseState (stepId, nodeId).Velocity; if (version >= OVRP_1_8_0.version && stepId == Step.Physics) return OVRP_1_8_0.ovrp_GetNodeVelocity2(0, nodeId).Position; return OVRP_0_1_3.ovrp_GetNodeVelocity(nodeId).Position; } public static Vector3f GetNodeAngularVelocity(Node nodeId, Step stepId) { if (version >= OVRP_1_12_0.version) return OVRP_1_12_0.ovrp_GetNodePoseState(stepId, nodeId).AngularVelocity; return new Vector3f(); //TODO: Convert legacy quat to vec3? } public static Vector3f GetNodeAcceleration(Node nodeId, Step stepId) { if (version >= OVRP_1_12_0.version) return OVRP_1_12_0.ovrp_GetNodePoseState (stepId, nodeId).Acceleration; if (version >= OVRP_1_8_0.version && stepId == Step.Physics) return OVRP_1_8_0.ovrp_GetNodeAcceleration2(0, nodeId).Position; return OVRP_0_1_3.ovrp_GetNodeAcceleration(nodeId).Position; } public static Vector3f GetNodeAngularAcceleration(Node nodeId, Step stepId) { if (version >= OVRP_1_12_0.version) return OVRP_1_12_0.ovrp_GetNodePoseState(stepId, nodeId).AngularAcceleration; return new Vector3f(); //TODO: Convert legacy quat to vec3? } public static bool GetNodePresent(Node nodeId) { return OVRP_1_1_0.ovrp_GetNodePresent(nodeId) == Bool.True; } public static bool GetNodeOrientationTracked(Node nodeId) { return OVRP_1_1_0.ovrp_GetNodeOrientationTracked(nodeId) == Bool.True; } public static bool GetNodePositionTracked(Node nodeId) { return OVRP_1_1_0.ovrp_GetNodePositionTracked(nodeId) == Bool.True; } public static ControllerState GetControllerState(uint controllerMask) { return OVRP_1_1_0.ovrp_GetControllerState(controllerMask); } public static ControllerState2 GetControllerState2(uint controllerMask) { if (version >= OVRP_1_12_0.version) { return OVRP_1_12_0.ovrp_GetControllerState2(controllerMask); } return new ControllerState2(OVRP_1_1_0.ovrp_GetControllerState(controllerMask)); } public static bool SetControllerVibration(uint controllerMask, float frequency, float amplitude) { return OVRP_0_1_2.ovrp_SetControllerVibration(controllerMask, frequency, amplitude) == Bool.True; } public static HapticsDesc GetControllerHapticsDesc(uint controllerMask) { if (version >= OVRP_1_6_0.version) { return OVRP_1_6_0.ovrp_GetControllerHapticsDesc(controllerMask); } else { return new HapticsDesc(); } } public static HapticsState GetControllerHapticsState(uint controllerMask) { if (version >= OVRP_1_6_0.version) { return OVRP_1_6_0.ovrp_GetControllerHapticsState(controllerMask); } else { return new HapticsState(); } } public static bool SetControllerHaptics(uint controllerMask, HapticsBuffer hapticsBuffer) { if (version >= OVRP_1_6_0.version) { return OVRP_1_6_0.ovrp_SetControllerHaptics(controllerMask, hapticsBuffer) == Bool.True; } else { return false; } } public static float GetEyeRecommendedResolutionScale() { if (version >= OVRP_1_6_0.version) { return OVRP_1_6_0.ovrp_GetEyeRecommendedResolutionScale(); } else { return 1.0f; } } public static float GetAppCpuStartToGpuEndTime() { if (version >= OVRP_1_6_0.version) { return OVRP_1_6_0.ovrp_GetAppCpuStartToGpuEndTime(); } else { return 0.0f; } } public static bool GetBoundaryConfigured() { if (version >= OVRP_1_8_0.version) { return OVRP_1_8_0.ovrp_GetBoundaryConfigured() == OVRPlugin.Bool.True; } else { return false; } } public static BoundaryTestResult TestBoundaryNode(Node nodeId, BoundaryType boundaryType) { if (version >= OVRP_1_8_0.version) { return OVRP_1_8_0.ovrp_TestBoundaryNode(nodeId, boundaryType); } else { return new BoundaryTestResult(); } } public static BoundaryTestResult TestBoundaryPoint(Vector3f point, BoundaryType boundaryType) { if (version >= OVRP_1_8_0.version) { return OVRP_1_8_0.ovrp_TestBoundaryPoint(point, boundaryType); } else { return new BoundaryTestResult(); } } public static bool SetBoundaryLookAndFeel(BoundaryLookAndFeel lookAndFeel) { if (version >= OVRP_1_8_0.version) { return OVRP_1_8_0.ovrp_SetBoundaryLookAndFeel(lookAndFeel) == OVRPlugin.Bool.True; } else { return false; } } public static bool ResetBoundaryLookAndFeel() { if (version >= OVRP_1_8_0.version) { return OVRP_1_8_0.ovrp_ResetBoundaryLookAndFeel() == OVRPlugin.Bool.True; } else { return false; } } public static BoundaryGeometry GetBoundaryGeometry(BoundaryType boundaryType) { if (version >= OVRP_1_8_0.version) { return OVRP_1_8_0.ovrp_GetBoundaryGeometry(boundaryType); } else { return new BoundaryGeometry(); } } public static bool GetBoundaryGeometry2(BoundaryType boundaryType, IntPtr points, ref int pointsCount) { if (version >= OVRP_1_9_0.version) { return OVRP_1_9_0.ovrp_GetBoundaryGeometry2(boundaryType, points, ref pointsCount) == OVRPlugin.Bool.True; } else { pointsCount = 0; return false; } } public static AppPerfStats GetAppPerfStats() { if (version >= OVRP_1_9_0.version) { return OVRP_1_9_0.ovrp_GetAppPerfStats(); } else { return new AppPerfStats(); } } public static bool ResetAppPerfStats() { if (version >= OVRP_1_9_0.version) { return OVRP_1_9_0.ovrp_ResetAppPerfStats() == OVRPlugin.Bool.True; } else { return false; } } public static float GetAppFramerate() { if (version >= OVRP_1_12_0.version) { return OVRP_1_12_0.ovrp_GetAppFramerate(); } else { return 0.0f; } } public static EyeTextureFormat GetDesiredEyeTextureFormat() { if (version >= OVRP_1_11_0.version ) { uint eyeTextureFormatValue = (uint) OVRP_1_11_0.ovrp_GetDesiredEyeTextureFormat(); // convert both R8G8B8A8 and R8G8B8A8_SRGB to R8G8B8A8 here for avoid confusing developers if (eyeTextureFormatValue == 1) eyeTextureFormatValue = 0; return (EyeTextureFormat)eyeTextureFormatValue; } else { return EyeTextureFormat.Default; } } public static bool SetDesiredEyeTextureFormat(EyeTextureFormat value) { if (version >= OVRP_1_11_0.version) { return OVRP_1_11_0.ovrp_SetDesiredEyeTextureFormat(value) == OVRPlugin.Bool.True; } else { return false; } } public static Vector3f GetBoundaryDimensions(BoundaryType boundaryType) { if (version >= OVRP_1_8_0.version) { return OVRP_1_8_0.ovrp_GetBoundaryDimensions(boundaryType); } else { return new Vector3f(); } } public static bool GetBoundaryVisible() { if (version >= OVRP_1_8_0.version) { return OVRP_1_8_0.ovrp_GetBoundaryVisible() == OVRPlugin.Bool.True; } else { return false; } } public static bool SetBoundaryVisible(bool value) { if (version >= OVRP_1_8_0.version) { return OVRP_1_8_0.ovrp_SetBoundaryVisible(ToBool(value)) == OVRPlugin.Bool.True; } else { return false; } } public static SystemHeadset GetSystemHeadsetType() { if (version >= OVRP_1_9_0.version) return OVRP_1_9_0.ovrp_GetSystemHeadsetType(); return SystemHeadset.None; } public static Controller GetActiveController() { if (version >= OVRP_1_9_0.version) return OVRP_1_9_0.ovrp_GetActiveController(); return Controller.None; } public static Controller GetConnectedControllers() { if (version >= OVRP_1_9_0.version) return OVRP_1_9_0.ovrp_GetConnectedControllers(); return Controller.None; } private static Bool ToBool(bool b) { return (b) ? OVRPlugin.Bool.True : OVRPlugin.Bool.False; } public static TrackingOrigin GetTrackingOriginType() { return OVRP_1_0_0.ovrp_GetTrackingOriginType(); } public static bool SetTrackingOriginType(TrackingOrigin originType) { return OVRP_1_0_0.ovrp_SetTrackingOriginType(originType) == Bool.True; } public static Posef GetTrackingCalibratedOrigin() { return OVRP_1_0_0.ovrp_GetTrackingCalibratedOrigin(); } public static bool SetTrackingCalibratedOrigin() { return OVRP_1_2_0.ovrpi_SetTrackingCalibratedOrigin() == Bool.True; } public static bool RecenterTrackingOrigin(RecenterFlags flags) { return OVRP_1_0_0.ovrp_RecenterTrackingOrigin((uint)flags) == Bool.True; } private const string pluginName = "OVRPlugin"; private static Version _versionZero = new System.Version(0, 0, 0); private static class OVRP_0_1_0 { public static readonly System.Version version = new System.Version(0, 1, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Sizei ovrp_GetEyeTextureSize(Eye eyeId); } private static class OVRP_0_1_1 { public static readonly System.Version version = new System.Version(0, 1, 1); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetOverlayQuad2(Bool onTop, Bool headLocked, IntPtr texture, IntPtr device, Posef pose, Vector3f scale); } private static class OVRP_0_1_2 { public static readonly System.Version version = new System.Version(0, 1, 2); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Posef ovrp_GetNodePose(Node nodeId); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetControllerVibration(uint controllerMask, float frequency, float amplitude); } private static class OVRP_0_1_3 { public static readonly System.Version version = new System.Version(0, 1, 3); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Posef ovrp_GetNodeVelocity(Node nodeId); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Posef ovrp_GetNodeAcceleration(Node nodeId); } private static class OVRP_0_5_0 { public static readonly System.Version version = new System.Version(0, 5, 0); } private static class OVRP_1_0_0 { public static readonly System.Version version = new System.Version(1, 0, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern TrackingOrigin ovrp_GetTrackingOriginType(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetTrackingOriginType(TrackingOrigin originType); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Posef ovrp_GetTrackingCalibratedOrigin(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_RecenterTrackingOrigin(uint flags); } private static class OVRP_1_1_0 { public static readonly System.Version version = new System.Version(1, 1, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetInitialized(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_GetVersion")] private static extern IntPtr _ovrp_GetVersion(); public static string ovrp_GetVersion() { return Marshal.PtrToStringAnsi(_ovrp_GetVersion()); } [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_GetNativeSDKVersion")] private static extern IntPtr _ovrp_GetNativeSDKVersion(); public static string ovrp_GetNativeSDKVersion() { return Marshal.PtrToStringAnsi(_ovrp_GetNativeSDKVersion()); } [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr ovrp_GetAudioOutId(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr ovrp_GetAudioInId(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetEyeTextureScale(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetEyeTextureScale(float value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetTrackingOrientationSupported(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetTrackingOrientationEnabled(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetTrackingOrientationEnabled(Bool value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetTrackingPositionSupported(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetTrackingPositionEnabled(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetTrackingPositionEnabled(Bool value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetNodePresent(Node nodeId); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetNodeOrientationTracked(Node nodeId); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetNodePositionTracked(Node nodeId); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Frustumf ovrp_GetNodeFrustum(Node nodeId); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern ControllerState ovrp_GetControllerState(uint controllerMask); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern int ovrp_GetSystemCpuLevel(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetSystemCpuLevel(int value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern int ovrp_GetSystemGpuLevel(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetSystemGpuLevel(int value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetSystemPowerSavingMode(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetSystemDisplayFrequency(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern int ovrp_GetSystemVSyncCount(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetSystemVolume(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern BatteryStatus ovrp_GetSystemBatteryStatus(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetSystemBatteryLevel(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetSystemBatteryTemperature(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_GetSystemProductName")] private static extern IntPtr _ovrp_GetSystemProductName(); public static string ovrp_GetSystemProductName() { return Marshal.PtrToStringAnsi(_ovrp_GetSystemProductName()); } [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_ShowSystemUI(PlatformUI ui); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetAppMonoscopic(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetAppMonoscopic(Bool value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetAppHasVrFocus(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetAppShouldQuit(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetAppShouldRecenter(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_GetAppLatencyTimings")] private static extern IntPtr _ovrp_GetAppLatencyTimings(); public static string ovrp_GetAppLatencyTimings() { return Marshal.PtrToStringAnsi(_ovrp_GetAppLatencyTimings()); } [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetUserPresent(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetUserIPD(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetUserIPD(float value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetUserEyeDepth(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetUserEyeDepth(float value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetUserEyeHeight(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetUserEyeHeight(float value); } private static class OVRP_1_2_0 { public static readonly System.Version version = new System.Version(1, 2, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetSystemVSyncCount(int vsyncCount); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrpi_SetTrackingCalibratedOrigin(); } private static class OVRP_1_3_0 { public static readonly System.Version version = new System.Version(1, 3, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetEyeOcclusionMeshEnabled(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetEyeOcclusionMeshEnabled(Bool value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetSystemHeadphonesPresent(); } private static class OVRP_1_5_0 { public static readonly System.Version version = new System.Version(1, 5, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern SystemRegion ovrp_GetSystemRegion(); } private static class OVRP_1_6_0 { public static readonly System.Version version = new System.Version(1, 6, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetTrackingIPDEnabled(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetTrackingIPDEnabled(Bool value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern HapticsDesc ovrp_GetControllerHapticsDesc(uint controllerMask); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern HapticsState ovrp_GetControllerHapticsState(uint controllerMask); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetControllerHaptics(uint controllerMask, HapticsBuffer hapticsBuffer); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetOverlayQuad3(uint flags, IntPtr textureLeft, IntPtr textureRight, IntPtr device, Posef pose, Vector3f scale, int layerIndex); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetEyeRecommendedResolutionScale(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetAppCpuStartToGpuEndTime(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern int ovrp_GetSystemRecommendedMSAALevel(); } private static class OVRP_1_7_0 { public static readonly System.Version version = new System.Version(1, 7, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetAppChromaticCorrection(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetAppChromaticCorrection(Bool value); } private static class OVRP_1_8_0 { public static readonly System.Version version = new System.Version(1, 8, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetBoundaryConfigured(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern BoundaryTestResult ovrp_TestBoundaryNode(Node nodeId, BoundaryType boundaryType); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern BoundaryTestResult ovrp_TestBoundaryPoint(Vector3f point, BoundaryType boundaryType); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetBoundaryLookAndFeel(BoundaryLookAndFeel lookAndFeel); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_ResetBoundaryLookAndFeel(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern BoundaryGeometry ovrp_GetBoundaryGeometry(BoundaryType boundaryType); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Vector3f ovrp_GetBoundaryDimensions(BoundaryType boundaryType); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetBoundaryVisible(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetBoundaryVisible(Bool value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_Update2(int stateId, int frameIndex, double predictionSeconds); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Posef ovrp_GetNodePose2(int stateId, Node nodeId); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Posef ovrp_GetNodeVelocity2(int stateId, Node nodeId); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Posef ovrp_GetNodeAcceleration2(int stateId, Node nodeId); } private static class OVRP_1_9_0 { public static readonly System.Version version = new System.Version(1, 9, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern SystemHeadset ovrp_GetSystemHeadsetType(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Controller ovrp_GetActiveController(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Controller ovrp_GetConnectedControllers(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetBoundaryGeometry2(BoundaryType boundaryType, IntPtr points, ref int pointsCount); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern AppPerfStats ovrp_GetAppPerfStats(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_ResetAppPerfStats(); } private static class OVRP_1_10_0 { public static readonly System.Version version = new System.Version(1, 10, 0); } private static class OVRP_1_11_0 { public static readonly System.Version version = new System.Version(1, 11, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetDesiredEyeTextureFormat(EyeTextureFormat value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern EyeTextureFormat ovrp_GetDesiredEyeTextureFormat(); } private static class OVRP_1_12_0 { public static readonly System.Version version = new System.Version(1, 12, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetAppFramerate(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern PoseStatef ovrp_GetNodePoseState(Step stepId, Node nodeId); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern ControllerState2 ovrp_GetControllerState2(uint controllerMask); } private static class OVRP_1_13_0 { public static readonly System.Version version = new System.Version(1, 13, 0); } }
using System; using System.Collections.Generic; using Tao.OpenGl; using Behemoth.Util; namespace Behemoth.TaoUtil { /// <summary> /// Graphics utility functions. /// </summary> public static class Gfx { public enum VertexFlags { Pos = 1 << 0, Normal = 1 << 1, Color = 1 << 2, Texture = 1 << 3, } /// <summary> /// Draw a sprite from a sheet of sprites as a texture mapped quad. /// </summary> public static void DrawSprite( double x, double y, int frame, double spriteWidth, double spriteHeight, int sheetTexture, int sheetRows, int sheetColumns, int xFlip, int yFlip, Color color) { float x0 = (float)(frame % sheetColumns) / (float)sheetColumns + (float)xFlip / (float)sheetColumns; float y0 = (float)((sheetColumns + frame) / sheetRows) / (float)sheetRows - (float)yFlip / (float)sheetRows; float x1 = x0 + (1.0f - 2.0f * xFlip) / (float)sheetColumns; float y1 = y0 - (1.0f - 2.0f * yFlip) / (float)sheetRows; GlColor(color); Gl.glPushMatrix(); Gl.glTranslatef((float)x, (float)y, 0.0f); Gl.glBindTexture(Gl.GL_TEXTURE_2D, sheetTexture); Gl.glBegin(Gl.GL_QUADS); Gl.glTexCoord2f(x0, y0); Gl.glVertex3f(0.0f, 0.0f, 0.0f); Gl.glTexCoord2f(x1, y0); Gl.glVertex3f((float)spriteWidth, 0.0f, 0.0f); Gl.glTexCoord2f(x1, y1); Gl.glVertex3f((float)spriteWidth, (float)spriteHeight, 0.0f); Gl.glTexCoord2f(x0, y1); Gl.glVertex3f(0.0f, (float)spriteHeight, 0.0f); Gl.glEnd(); Gl.glPopMatrix(); } /// <summary> /// Draw a sprite from a sheet of sprites as a texture mapped quad. /// </summary> public static void DrawSprite( double x, double y, int frame, double spriteWidth, double spriteHeight, int sheetTexture, int sheetRows, int sheetColumns) { DrawSprite(x, y, frame, spriteWidth, spriteHeight, sheetTexture, sheetColumns, sheetColumns, 0, 0, Color.White); } /// <summary> /// Draw a sprite from a sheet of sprites as a texture mapped quad /// mirrored along the vertical axis. /// </summary> public static void DrawMirroredSprite( double x, double y, int frame, double spriteWidth, double spriteHeight, int sheetTexture, int sheetRows, int sheetColumns) { DrawSprite(x, y, frame, spriteWidth, spriteHeight, sheetTexture, sheetColumns, sheetColumns, 1, 0, Color.White); } /// <summary> /// Draw a sprite from a sheet of sprites as a texture mapped quad /// mirrored along the horizontal axis. /// </summary> public static void DrawFlippedSprite( double x, double y, int frame, double spriteWidth, double spriteHeight, int sheetTexture, int sheetRows, int sheetColumns) { DrawSprite(x, y, frame, spriteWidth, spriteHeight, sheetTexture, sheetColumns, sheetColumns, 0, 1, Color.White); } /// <summary> /// Draw a vertically scrolling starfield /// </summary> public static void DrawStarfield( IEnumerable<Vec3> points, double t, double pointSize, double screenWidth) { const double span = 1000.0; const double depthFactor = 100.0; Gl.glBindTexture(Gl.GL_TEXTURE_2D, 0); Gl.glColor3f(1.0f, 1.0f, 1.0f); Gl.glPointSize((float)pointSize); Gl.glBegin(Gl.GL_POINTS); foreach (var point in points) { Gl.glVertex3f( (float)((screenWidth / 2 + point.X) * depthFactor / (depthFactor + point.Z)), (float)((point.Y - t % span) * depthFactor / (depthFactor + point.Z)), 0.0f); Gl.glVertex3f( (float)((screenWidth / 2 + point.X) * depthFactor / (depthFactor + point.Z)), (float)((point.Y + span - t % span) * depthFactor / (depthFactor + point.Z)), 0.0f); } Gl.glEnd(); } public static void DrawChar( char ch, double x, double y, double w, double h, int sheetTexture, Color color) { int frame = (int)ch; if (frame > 0xff) { throw new ArgumentException("Can't render chars above 255.", "ch"); } DrawSprite(x, y, frame, w, h, sheetTexture, 16, 16, 0, 0, color); } public static void DrawString( String str, double x, double y, double fontW, double fontH, int sheetTexture, Color color) { for (int i = 0; i < str.Length; i++) { DrawChar(str[i], x + i * fontW, y, fontW, fontH, sheetTexture, color); } } public static void GlColor(Color color) { Gl.glColor4f((float)color.R / 256.0f, (float)color.G / 256.0f, (float)color.B / 256.0f, (float)color.A / 256.0f); } /// <summary> /// Set OpenGL color for emissive objects. /// </summary> public static void GlEmissionColor(Color color) { GlColor(color); Gl.glMaterialfv(Gl.GL_FRONT, Gl.GL_EMISSION, color.FloatArray); } public static void DrawRect(double x, double y, double w, double h, byte r, byte g, byte b) { // Clear the bound texture. Gl.glBindTexture(Gl.GL_TEXTURE_2D, 0); Gl.glColor3f((float)r / 256, (float)g / 256, (float)b / 256); Gl.glBegin(Gl.GL_QUADS); Gl.glVertex3f((float)x, (float)y, 0.0f); Gl.glVertex3f((float)(x + w), (float)y, 0.0f); Gl.glVertex3f((float)(x + w), (float)(y + h), 0.0f); Gl.glVertex3f((float)x, (float)(y + h), 0.0f); Gl.glEnd(); } public static void ClearScreen() { Gl.glClear(Gl.GL_COLOR_BUFFER_BIT | Gl.GL_DEPTH_BUFFER_BIT); } /// <summary> /// Draw an axis-aligned OpenGL cube. /// </summary> public static void DrawCube( float x, float y, float z, float w, float h, float d) { Gl.glBegin(Gl.GL_QUADS); Gl.glNormal3f(-1, 0, 0); Gl.glVertex3f(x, y, z); Gl.glVertex3f(x, y, z + d); Gl.glVertex3f(x, y + h, z + d); Gl.glVertex3f(x, y + h, z); Gl.glNormal3f(1, 0, 0); Gl.glVertex3f(x + w, y, z); Gl.glVertex3f(x + w, y + h, z); Gl.glVertex3f(x + w, y + h, z + d); Gl.glVertex3f(x + w, y, z + d); Gl.glNormal3f(0, -1, 0); Gl.glVertex3f(x, y, z); Gl.glVertex3f(x + w, y, z); Gl.glVertex3f(x + w, y, z + d); Gl.glVertex3f(x, y, z + d); Gl.glNormal3f(0, 1, 0); Gl.glVertex3f(x, y + h, z); Gl.glVertex3f(x, y + h, z + d); Gl.glVertex3f(x + w, y + h, z + d); Gl.glVertex3f(x + w, y + h, z); Gl.glNormal3f(0, 0, -1); Gl.glVertex3f(x, y, z); Gl.glVertex3f(x, y + h, z); Gl.glVertex3f(x + w, y + h, z); Gl.glVertex3f(x + w, y, z); Gl.glNormal3f(0, 0, 1); Gl.glVertex3f(x, y, z + d); Gl.glVertex3f(x + w, y, z + d); Gl.glVertex3f(x + w, y + h, z + d); Gl.glVertex3f(x, y + h, z + d); Gl.glEnd(); } /// <summary> /// Draw a triangle mesh. Vertices and normals are arrays which contain /// positions and normal coordinates of the mesh vertices. Indices is a /// list of the vertex triplets that make the faces of the mesh. /// </summary> public static void DrawTriMesh(float[,] vertices, float[,] normals, short[,] indices) { var types = VertexFlags.Pos | VertexFlags.Normal; InitArrayState(types); Gl.glVertexPointer(3, Gl.GL_FLOAT, 0, vertices); Gl.glNormalPointer(Gl.GL_FLOAT, 0, normals); Gl.glDrawElements(Gl.GL_TRIANGLES, indices.Length, Gl.GL_UNSIGNED_SHORT, indices); UninitArrayState(types); } /// <summary> /// Initialize OpenGL for drawing an element array. /// </summary> public static void InitArrayState(VertexFlags types) { if ((types & VertexFlags.Pos) != 0) Gl.glEnableClientState(Gl.GL_VERTEX_ARRAY); if ((types & VertexFlags.Normal) != 0) Gl.glEnableClientState(Gl.GL_NORMAL_ARRAY); if ((types & VertexFlags.Color) != 0) Gl.glEnableClientState(Gl.GL_COLOR_ARRAY); if ((types & VertexFlags.Texture) != 0) Gl.glEnableClientState(Gl.GL_TEXTURE_COORD_ARRAY); } /// <summary> /// Uninitialize OpenGL element array drawing. /// </summary> public static void UninitArrayState(VertexFlags types) { if ((types & VertexFlags.Pos) != 0) Gl.glDisableClientState(Gl.GL_VERTEX_ARRAY); if ((types & VertexFlags.Normal) != 0) Gl.glDisableClientState(Gl.GL_NORMAL_ARRAY); if ((types & VertexFlags.Color) != 0) Gl.glDisableClientState(Gl.GL_COLOR_ARRAY); if ((types & VertexFlags.Texture) != 0) Gl.glDisableClientState(Gl.GL_TEXTURE_COORD_ARRAY); } /// <summary> /// Draws a single particle using point sprites. Might be less efficient /// than drawing a batch of them at once. Doesn't bind texture or set /// color, do these before calling. /// </summary> public static void DrawParticle(float x, float y, float z, float size) { Gl.glPointSize(size); Gl.glTexEnvf(Gl.GL_POINT_SPRITE_ARB, Gl.GL_COORD_REPLACE_ARB, Gl.GL_TRUE); Gl.glEnable(Gl.GL_POINT_SPRITE_ARB); Gl.glBegin(Gl.GL_POINTS); // Set normal so that existing normal state doesn't affect particle shading. Gl.glNormal3f(0, 0, 1); Gl.glVertex3f(x, y, z); Gl.glEnd(); Gl.glDisable(Gl.GL_POINT_SPRITE_ARB); } /// <summary> /// Draw a glowing laser beam. /// </summary> public static void DrawBeam( Vec3 start, Vec3 end, double size, Color inner, Color outer) { // TODO: Push translation and rotation to get the result point from start to end. Vec3 dir = end - start; Vec3 axis; double angle; Geom.OrientTowards(new Vec3(1, 0, 0), dir, out axis, out angle); float length = (float)dir.Abs(); float unit = (float)size / 4; Gl.glPushMatrix(); Gl.glTranslated(start.X, start.Y, start.Z); Gl.glRotated(Geom.Rad2Deg(angle), axis.X, axis.Y, axis.Z); Gl.glPushAttrib(Gl.GL_LIGHTING_BIT | Gl.GL_ENABLE_BIT); Gl.glBlendFunc(Gl.GL_ONE, Gl.GL_ONE); Gfx.GlEmissionColor(inner); Gfx.DrawCube(unit, -unit, -unit, length - 2 * unit, 2 * unit, 2 * unit); Gfx.GlEmissionColor(outer); Gfx.DrawCube(0, -2 * unit, -2 * unit, length, 4 * unit, 4 * unit); Gl.glBlendFunc(Gl.GL_ONE, Gl.GL_ZERO); Gl.glPopAttrib(); Gl.glPopMatrix(); } } }
// // Copyright (c) 2008 Microsoft Corporation. All rights reserved. // using System; using System.Text; using System.IO; using System.Xml; using System.Net; using System.Management.Automation; using System.ComponentModel; using System.Reflection; using System.Globalization; using System.Management.Automation.Runspaces; using System.Collections; using System.Collections.Specialized; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Security; using System.Security.Principal; using System.Resources; using System.Threading; using System.Diagnostics.CodeAnalysis; using Microsoft.Powershell.Commands.GetCounter.PdhNative; using Microsoft.PowerShell.Commands.GetCounter; using Microsoft.PowerShell.Commands.Diagnostics.Common; namespace Microsoft.PowerShell.Commands { /// /// Class that implements the Get-Counter cmdlet. /// [Cmdlet("Export", "Counter", DefaultParameterSetName = "ExportCounterSet", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=138337")] public sealed class ExportCounterCommand : PSCmdlet { // // Path parameter // [Parameter( Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, HelpMessageBaseName = "GetEventResources")] [Alias("PSPath")] public string Path { get { return _path; } set { _path = value; } } private string _path; private string _resolvedPath; // // Format parameter. // Valid strings are "blg", "csv", "tsv" (case-insensitive). // [Parameter( Mandatory = false, ValueFromPipeline = false, ValueFromPipelineByPropertyName = false, HelpMessageBaseName = "GetEventResources")] [ValidateNotNull] public string FileFormat { get { return _format; } set { _format = value; } } private string _format = "BLG"; // // MaxSize parameter // Maximum output file size, in megabytes. // [Parameter( HelpMessageBaseName = "GetEventResources")] public UInt32 MaxSize { get { return _maxSize; } set { _maxSize = value; } } private UInt32 _maxSize = 0; // // InputObject parameter // [Parameter( Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, HelpMessageBaseName = "GetEventResources")] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Scope = "member", Target = "Microsoft.PowerShell.Commands.ExportCounterCommand.InputObject", Justification = "A PerformanceCounterSampleSet[] is required here because Powershell supports arrays natively.")] public PerformanceCounterSampleSet[] InputObject { get { return _counterSampleSets; } set { _counterSampleSets = value; } } private PerformanceCounterSampleSet[] _counterSampleSets = new PerformanceCounterSampleSet[0]; // // Force switch // [Parameter( HelpMessageBaseName = "GetEventResources")] public SwitchParameter Force { get { return _force; } set { _force = value; } } private SwitchParameter _force; // // Circular switch // [Parameter( HelpMessageBaseName = "GetEventResources")] public SwitchParameter Circular { get { return _circular; } set { _circular = value; } } private SwitchParameter _circular; private ResourceManager _resourceMgr = null; private PdhHelper _pdhHelper = null; private bool _stopping = false; private bool _queryInitialized = false; private PdhLogFileType _outputFormat = PdhLogFileType.PDH_LOG_TYPE_BINARY; // // BeginProcessing() is invoked once per pipeline // protected override void BeginProcessing() { _resourceMgr = Microsoft.PowerShell.Commands.Diagnostics.Common.CommonUtilities.GetResourceManager(); // // Determine the OS version: this cmdlet requires Windows 7 // because it uses new Pdh functionality. // if (System.Environment.OSVersion.Version.Major < 6 || (System.Environment.OSVersion.Version.Major == 6 && System.Environment.OSVersion.Version.Minor < 1)) { string msg = _resourceMgr.GetString("ExportCtrWin7Required"); Exception exc = new Exception(msg); ThrowTerminatingError(new ErrorRecord(exc, "ExportCtrWin7Required", ErrorCategory.NotImplemented, null)); } _pdhHelper = new PdhHelper(System.Environment.OSVersion.Version.Major < 6); // // Validate the Format and CounterSamples arguments // ValidateFormat(); if (Circular.IsPresent && _maxSize == 0) { string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterCircularNoMaxSize")); Exception exc = new Exception(msg); WriteError(new ErrorRecord(exc, "CounterCircularNoMaxSize", ErrorCategory.InvalidResult, null)); } uint res = _pdhHelper.ConnectToDataSource(); if (res != 0) { ReportPdhError(res, true); } res = _pdhHelper.OpenQuery(); if (res != 0) { ReportPdhError(res, true); } } // // EndProcessing() is invoked once per pipeline // protected override void EndProcessing() { _pdhHelper.Dispose(); } /// /// Handle Control-C /// protected override void StopProcessing() { _stopping = true; _pdhHelper.Dispose(); } // // ProcessRecord() override. // This is the main entry point for the cmdlet. // When counter data comes from the pipeline, this gets invoked for each pipelined object. // When it's passed in as an argument, ProcessRecord() is called once for the entire _counterSampleSets array. // protected override void ProcessRecord() { Debug.Assert(_counterSampleSets.Length != 0 && _counterSampleSets[0] != null); ResolvePath(); uint res = 0; if (!_queryInitialized) { if (_format.ToLower(CultureInfo.InvariantCulture).Equals("blg")) { res = _pdhHelper.AddRelogCounters(_counterSampleSets[0]); } else { res = _pdhHelper.AddRelogCountersPreservingPaths(_counterSampleSets[0]); } if (res != 0) { ReportPdhError(res, true); } res = _pdhHelper.OpenLogForWriting(_resolvedPath, _outputFormat, Force.IsPresent, _maxSize * 1024 * 1024, Circular.IsPresent, null); if (res == PdhResults.PDH_FILE_ALREADY_EXISTS) { string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterFileExists"), _resolvedPath); Exception exc = new Exception(msg); ThrowTerminatingError(new ErrorRecord(exc, "CounterFileExists", ErrorCategory.InvalidResult, null)); } else if (res == PdhResults.PDH_LOG_FILE_CREATE_ERROR) { string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("FileCreateFailed"), _resolvedPath); Exception exc = new Exception(msg); ThrowTerminatingError(new ErrorRecord(exc, "FileCreateFailed", ErrorCategory.InvalidResult, null)); } else if (res == PdhResults.PDH_LOG_FILE_OPEN_ERROR) { string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("FileOpenFailed"), _resolvedPath); Exception exc = new Exception(msg); ThrowTerminatingError(new ErrorRecord(exc, "FileOpenFailed", ErrorCategory.InvalidResult, null)); } else if (res != 0) { ReportPdhError(res, true); } _queryInitialized = true; } foreach (PerformanceCounterSampleSet set in _counterSampleSets) { _pdhHelper.ResetRelogValues(); foreach (PerformanceCounterSample sample in set.CounterSamples) { bool bUnknownKey = false; res = _pdhHelper.SetCounterValue(sample, out bUnknownKey); if (bUnknownKey) { string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterExportSampleNotInInitialSet"), sample.Path, _resolvedPath); Exception exc = new Exception(msg); WriteError(new ErrorRecord(exc, "CounterExportSampleNotInInitialSet", ErrorCategory.InvalidResult, null)); } else if (res != 0) { ReportPdhError(res, true); } } res = _pdhHelper.WriteRelogSample(set.Timestamp); if (res != 0) { ReportPdhError(res, true); } if (_stopping) { break; } } } // ValidateFormat() helper. // Validates Format argument: only "BLG", "TSV" and "CSV" are valid strings (case-insensitive) // private void ValidateFormat() { switch (_format.ToLower(CultureInfo.InvariantCulture)) { case "blg": _outputFormat = PdhLogFileType.PDH_LOG_TYPE_BINARY; break; case "csv": _outputFormat = PdhLogFileType.PDH_LOG_TYPE_CSV; break; case "tsv": _outputFormat = PdhLogFileType.PDH_LOG_TYPE_TSV; break; default: string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterInvalidFormat"), _format); Exception exc = new Exception(msg); ThrowTerminatingError(new ErrorRecord(exc, "CounterInvalidFormat", ErrorCategory.InvalidArgument, null)); break; } } private void ResolvePath() { try { Collection<PathInfo> result = null; result = SessionState.Path.GetResolvedPSPathFromPSPath(_path); if (result.Count > 1) { string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("ExportDestPathAmbiguous"), _path); Exception exc = new Exception(msg); ThrowTerminatingError(new ErrorRecord(exc, "ExportDestPathAmbiguous", ErrorCategory.InvalidArgument, null)); } foreach (PathInfo currentPath in result) { _resolvedPath = currentPath.ProviderPath; } } catch (ItemNotFoundException pathNotFound) { // // This is an expected condition - we will be creating a new file // _resolvedPath = pathNotFound.ItemName; } } private void ReportPdhError(uint res, bool bTerminate) { string msg; uint formatRes = CommonUtilities.FormatMessageFromModule(res, "pdh.dll", out msg); if (formatRes != 0) { msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterApiError"), res); } Exception exc = new Exception(msg); if (bTerminate) { ThrowTerminatingError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null)); } else { WriteError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null)); } } } }
namespace Orleans.CodeGeneration { using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Orleans.CodeGenerator; using Orleans.Runtime; using Orleans.Serialization; using Orleans.Runtime.Configuration; /// <summary> /// Generates factory, grain reference, and invoker classes for grain interfaces. /// Generates state object classes for grain implementation classes. /// </summary> public class GrainClientGenerator : MarshalByRefObject { [Serializable] internal class CodeGenOptions { public FileInfo InputAssembly; public List<string> ReferencedAssemblies = new List<string>(); public string OutputFileName; } [Serializable] internal class GrainClientGeneratorFlags { internal static bool Verbose = false; internal static bool FailOnPathNotFound = false; } private static readonly int[] suppressCompilerWarnings = { 162, // CS0162 - Unreachable code detected. 219, // CS0219 - The variable 'V' is assigned but its value is never used. 414, // CS0414 - The private field 'F' is assigned but its value is never used. 649, // CS0649 - Field 'F' is never assigned to, and will always have its default value. 693, // CS0693 - Type parameter 'type parameter' has the same name as the type parameter from outer type 'T' 1591, // CS1591 - Missing XML comment for publicly visible type or member 'Type_or_Member' 1998 // CS1998 - This async method lacks 'await' operators and will run synchronously }; /// <summary> /// Generates one GrainReference class for each Grain Type in the inputLib file /// and output code file under outputLib directory /// </summary> private static bool CreateGrainClientAssembly(CodeGenOptions options) { string generatedCode = null; AppDomain appDomain = null; try { var assembly = typeof (GrainClientGenerator).GetTypeInfo().Assembly; // Create AppDomain. var appDomainSetup = new AppDomainSetup { ApplicationBase = Path.GetDirectoryName(assembly.Location), DisallowBindingRedirects = false, ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile }; appDomain = AppDomain.CreateDomain("Orleans-CodeGen Domain", null, appDomainSetup); // Set up assembly resolver var refResolver = new ReferenceResolver(options.ReferencedAssemblies); appDomain.AssemblyResolve += refResolver.ResolveAssembly; // Create an instance var generator = (GrainClientGenerator) appDomain.CreateInstanceAndUnwrap( assembly.FullName, typeof(GrainClientGenerator).FullName); // Call a method generatedCode = generator.CreateGrainClient(options); } finally { if (appDomain != null) AppDomain.Unload(appDomain); // Unload the AppDomain } if (generatedCode != null) { using (var sourceWriter = new StreamWriter(options.OutputFileName)) { sourceWriter.WriteLine("#if !EXCLUDE_CODEGEN"); DisableWarnings(sourceWriter, suppressCompilerWarnings); sourceWriter.WriteLine(generatedCode); RestoreWarnings(sourceWriter, suppressCompilerWarnings); sourceWriter.WriteLine("#endif"); } ConsoleText.WriteStatus("Orleans-CodeGen - Generated file written {0}", options.OutputFileName); return true; } return false; } /// <summary> /// Generate one GrainReference class for each Grain Type in the inputLib file /// and output a string with the code /// </summary> private string CreateGrainClient(CodeGenOptions options) { // Load input assembly // special case Orleans.dll because there is a circular dependency. var assemblyName = AssemblyName.GetAssemblyName(options.InputAssembly.FullName); var grainAssembly = (Path.GetFileName(options.InputAssembly.FullName) != "Orleans.dll") ? Assembly.LoadFrom(options.InputAssembly.FullName) : Assembly.Load(assemblyName); // Create directory for output file if it does not exist var outputFileDirectory = Path.GetDirectoryName(options.OutputFileName); if (!String.IsNullOrEmpty(outputFileDirectory) && !Directory.Exists(outputFileDirectory)) { Directory.CreateDirectory(outputFileDirectory); } var config = new ClusterConfiguration(); var codeGenerator = new RoslynCodeGenerator(new SerializationManager(null, config.Globals, config.Defaults)); // Generate source ConsoleText.WriteStatus("Orleans-CodeGen - Generating file {0}", options.OutputFileName); return codeGenerator.GenerateSourceForAssembly(grainAssembly); } private static void DisableWarnings(TextWriter sourceWriter, IEnumerable<int> warnings) { foreach (var warningNum in warnings) sourceWriter.WriteLine("#pragma warning disable {0}", warningNum); } private static void RestoreWarnings(TextWriter sourceWriter, IEnumerable<int> warnings) { foreach (var warningNum in warnings) sourceWriter.WriteLine("#pragma warning restore {0}", warningNum); } public int RunMain(string[] args) { ConsoleText.WriteStatus("Orleans-CodeGen - command-line = {0}", Environment.CommandLine); if (args.Length < 1) { PrintUsage(); return 1; } try { var options = new CodeGenOptions(); // STEP 1 : Parse parameters if (args.Length == 1 && args[0].StartsWith("@")) { // Read command line args from file string arg = args[0]; string argsFile = arg.Trim('"').Substring(1).Trim('"'); Console.WriteLine("Orleans-CodeGen - Reading code-gen params from file={0}", argsFile); AssertWellFormed(argsFile, true); args = File.ReadAllLines(argsFile); } int i = 1; foreach (string a in args) { string arg = a.Trim('"').Trim().Trim('"'); if (GrainClientGeneratorFlags.Verbose) Console.WriteLine("Orleans-CodeGen - arg #{0}={1}", i++, arg); if (string.IsNullOrEmpty(arg) || string.IsNullOrWhiteSpace(arg)) continue; if (arg.StartsWith("/")) { if (arg.StartsWith("/reference:") || arg.StartsWith("/r:")) { // list of references passed from from project file. separator =';' string refstr = arg.Substring(arg.IndexOf(':') + 1); string[] references = refstr.Split(';'); foreach (string rp in references) { AssertWellFormed(rp, true); options.ReferencedAssemblies.Add(rp); } } else if (arg.StartsWith("/in:")) { var infile = arg.Substring(arg.IndexOf(':') + 1); AssertWellFormed(infile); options.InputAssembly = new FileInfo(infile); } else if (arg.StartsWith("/out:")) { var outfile = arg.Substring(arg.IndexOf(':') + 1); AssertWellFormed(outfile, false); options.OutputFileName = outfile; } } else { Console.WriteLine($"Invalid argument: {arg}."); PrintUsage(); return 1; } } // STEP 2 : Validate and calculate unspecified parameters if (options.InputAssembly == null) { Console.WriteLine("ERROR: Orleans-CodeGen - no input file specified."); return 2; } if (String.IsNullOrEmpty(options.OutputFileName)) { Console.WriteLine("ERROR: Orleans-Codegen - no output filename specified"); return 2; } // STEP 3 : Dump useful info for debugging Console.WriteLine($"Orleans-CodeGen - Options {Environment.NewLine}\tInputLib={options.InputAssembly.FullName}{Environment.NewLine}\tOutputFileName={options.OutputFileName}"); if (options.ReferencedAssemblies != null) { Console.WriteLine("Orleans-CodeGen - Using referenced libraries:"); foreach (string assembly in options.ReferencedAssemblies) Console.WriteLine("\t{0} => {1}", Path.GetFileName(assembly), assembly); } // STEP 5 : Finally call code generation if (!CreateGrainClientAssembly(options)) return -1; // DONE! return 0; } catch (Exception ex) { Console.WriteLine("-- Code-gen FAILED -- \n{0}", LogFormatter.PrintException(ex)); return 3; } } private static void PrintUsage() { Console.WriteLine("Usage: ClientGenerator.exe /in:<grain assembly filename> /out:<fileName for output file> /r:<reference assemblies>"); Console.WriteLine(" ClientGenerator.exe @<arguments fileName> - Arguments will be read and processed from this file."); Console.WriteLine(); Console.WriteLine("Example: ClientGenerator.exe /in:MyGrain.dll /out:C:\\OrleansSample\\MyGrain\\obj\\Debug\\MyGrain.orleans.g.cs /r:Orleans.dll;..\\MyInterfaces\\bin\\Debug\\MyInterfaces.dll"); } private static void AssertWellFormed(string path, bool mustExist = false) { CheckPathNotStartWith(path, ":"); CheckPathNotStartWith(path, "\""); CheckPathNotEndsWith(path, "\""); CheckPathNotEndsWith(path, "/"); CheckPath(path, p => !string.IsNullOrWhiteSpace(p), "Empty path string"); bool exists = FileExists(path); if (mustExist && GrainClientGeneratorFlags.FailOnPathNotFound) CheckPath(path, p => exists, "Path not exists"); } private static bool FileExists(string path) { bool exists = File.Exists(path) || Directory.Exists(path); if (!exists) Console.WriteLine("MISSING: Path not exists: {0}", path); return exists; } private static void CheckPathNotStartWith(string path, string str) { CheckPath(path, p => !p.StartsWith(str), string.Format("Cannot start with '{0}'", str)); } private static void CheckPathNotEndsWith(string path, string str) { CheckPath( path, p => !p.EndsWith(str, StringComparison.InvariantCultureIgnoreCase), string.Format("Cannot end with '{0}'", str)); } private static void CheckPath(string path, Func<string, bool> condition, string what) { if (condition(path)) return; var errMsg = string.Format("Bad path {0} Reason = {1}", path, what); Console.WriteLine("CODEGEN-ERROR: " + errMsg); throw new ArgumentException("FAILED: " + errMsg); } /// <summary> /// Simple class that loads the reference assemblies upon the AppDomain.AssemblyResolve /// </summary> [Serializable] internal class ReferenceResolver { /// <summary> /// Dictionary : Assembly file name without extension -> full path /// </summary> private Dictionary<string, string> referenceAssemblyPaths = new Dictionary<string, string>(); /// <summary> /// Needs to be public so can be serialized accross the the app domain. /// </summary> public Dictionary<string, string> ReferenceAssemblyPaths { get { return referenceAssemblyPaths; } set { referenceAssemblyPaths = value; } } /// <summary> /// Inits the resolver /// </summary> /// <param name="referencedAssemblies">Full paths of referenced assemblies</param> public ReferenceResolver(IEnumerable<string> referencedAssemblies) { if (null == referencedAssemblies) return; foreach (var assemblyPath in referencedAssemblies) referenceAssemblyPaths[Path.GetFileNameWithoutExtension(assemblyPath)] = assemblyPath; } /// <summary> /// Handles System.AppDomain.AssemblyResolve event of an System.AppDomain /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="args">The event data.</param> /// <returns>The assembly that resolves the type, assembly, or resource; /// or null if theassembly cannot be resolved. /// </returns> public Assembly ResolveAssembly(object sender, ResolveEventArgs args) { Assembly assembly = null; string path; var asmName = new AssemblyName(args.Name); if (referenceAssemblyPaths.TryGetValue(asmName.Name, out path)) assembly = Assembly.LoadFrom(path); else ConsoleText.WriteStatus("Could not resolve {0}:", asmName.Name); return assembly; } } } }
// 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.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.SkinControls { public partial class GlobalSearch : WebsitePanelControlBase { const string TYPE_WEBSITE = "WebSite"; const string TYPE_DOMAIN = "Domain"; const string TYPE_ORGANIZATION = "Organization"; const string TYPE_EXCHANGEACCOUNT = "ExchangeAccount"; const string TYPE_RDSCOLLECTION = "RDSCollection"; const string TYPE_LYNC = "LyncAccount"; const string TYPE_FOLDER = "WebDAVFolder"; const string TYPE_SHAREPOINT = "SharePointFoundationSiteCollection"; const string TYPE_SHAREPOINTENTERPRISE = "SharePointEnterpriseSiteCollection"; const string PID_SPACE_WEBSITES = "SpaceWebSites"; const string PID_SPACE_DIMAINS = "SpaceDomains"; const string PID_SPACE_EXCHANGESERVER = "SpaceExchangeServer"; class Tab { int index; string name; public Tab(int index, string name) { this.index = index; this.name = name; } public int Index { get { return this.index; } set { this.index = value; } } public string Name { get { return this.name; } set { this.name = value; } } } protected void Page_Load(object sender, EventArgs e) { ClientScriptManager cs = Page.ClientScript; cs.RegisterClientScriptInclude("jquery",ResolveUrl("~/JavaScript/jquery-1.4.4.min.js")); cs.RegisterClientScriptInclude("jqueryui",ResolveUrl("~/JavaScript/jquery-ui-1.8.9.min.js")); // cs.RegisterClientScriptBlock(this.GetType(), "jquerycss", // "<link rel='stylesheet' type='text/css' href='" + ResolveUrl("~/App_Themes/Default/Styles/jquery-ui-1.8.9.css") + "' />"); if (!IsPostBack) { BindItemTypes(); } } private void BindItemTypes() { /* // bind item types DataTable dtItemTypes = ES.Services.Packages.GetSearchableServiceItemTypes().Tables[0]; foreach (DataRow dr in dtItemTypes.Rows) { // Trying a well-known workaround to distinguish different service item types with the same name var localizedStr = PortalUtils.GetSharedLocalizedString(Utils.ModuleName, "ServiceItemType." + dr["DisplayName"].ToString() + "_" + dr["ItemTypeID"].ToString()); // Looking for localized text if (String.IsNullOrWhiteSpace(localizedStr)) { localizedStr = PortalUtils.GetSharedLocalizedString(Utils.ModuleName, "ServiceItemType." + dr["DisplayName"].ToString()); } // ddlItemType.Items.Add(new ListItem(localizedStr, dr["ItemTypeID"].ToString())); } */ } protected void btnSearchUsers_Click(object sender, EventArgs e) { /* Response.Redirect(PortalUtils.NavigatePageURL(PortalUtils.GetUsersSearchPageId(), PortalUtils.USER_ID_PARAM, PanelSecurity.SelectedUserId.ToString(), "Query=" + Server.UrlEncode(txtUsersQuery.Text), "Criteria=" + ddlUserFields.SelectedValue)); */ } protected void btnSearchSpaces_Click(object sender, EventArgs e) { /* Response.Redirect(PortalUtils.NavigatePageURL(PortalUtils.GetSpacesSearchPageId(), PortalUtils.USER_ID_PARAM, PanelSecurity.SelectedUserId.ToString(), "Query=" + Server.UrlEncode(txtSpacesQuery.Text), "ItemTypeID=" + ddlItemType.SelectedValue)); */ } public string GetItemPageUrl(string fullType, string itemType, int itemId, int spaceId, int accountId, string textSearch = "") { string res = ""; if (fullType.Equals("AccountHome")) { res = PortalUtils.GetUserHomePageUrl(itemId); } else { switch (itemType) { case TYPE_WEBSITE: res = PortalUtils.NavigatePageURL(PID_SPACE_WEBSITES, "ItemID", itemId.ToString(), PortalUtils.SPACE_ID_PARAM + "=" + spaceId, "ctl=edit_item", "moduleDefId=websites"); break; case TYPE_DOMAIN: res = PortalUtils.NavigatePageURL(PID_SPACE_DIMAINS, "DomainID", itemId.ToString(), PortalUtils.SPACE_ID_PARAM + "=" + spaceId, "ctl=edit_item", "moduleDefId=domains"); break; case TYPE_ORGANIZATION: res = PortalUtils.NavigatePageURL(PID_SPACE_EXCHANGESERVER, "ItemID", itemId.ToString(), PortalUtils.SPACE_ID_PARAM + "=" + spaceId, "ctl=edit_item", "moduleDefId=ExchangeServer"); break; case TYPE_EXCHANGEACCOUNT: if (fullType.Equals("Mailbox")) { res = PortalUtils.NavigatePageURL(PID_SPACE_EXCHANGESERVER, "ItemID", itemId.ToString(), PortalUtils.SPACE_ID_PARAM + "=" + spaceId, "ctl=mailbox_settings", "AccountID=" + accountId, "moduleDefId=ExchangeServer"); } else { res = PortalUtils.NavigatePageURL(PID_SPACE_EXCHANGESERVER, "ItemID", itemId.ToString(), PortalUtils.SPACE_ID_PARAM + "=" + spaceId, "ctl=edit_user", "AccountID=" + accountId, "moduleDefId=ExchangeServer"); } break; case TYPE_RDSCOLLECTION: res = PortalUtils.NavigatePageURL(PID_SPACE_EXCHANGESERVER, "ItemID", itemId.ToString(), PortalUtils.SPACE_ID_PARAM + "=" + spaceId, "ctl=rds_edit_collection", "CollectionId=" + accountId, "moduleDefId=ExchangeServer"); break; case TYPE_LYNC: res = PortalUtils.NavigatePageURL(PID_SPACE_EXCHANGESERVER, "ItemID", itemId.ToString(), PortalUtils.SPACE_ID_PARAM + "=" + spaceId.ToString(), "ctl=edit_lync_user", "AccountID=" + accountId, "moduleDefId=ExchangeServer"); break; case TYPE_FOLDER: res = PortalUtils.NavigatePageURL(PID_SPACE_EXCHANGESERVER, "ItemID", itemId.ToString(), PortalUtils.SPACE_ID_PARAM + "=" + spaceId.ToString(), "ctl=enterprisestorage_folder_settings", "FolderID=" + textSearch, "moduleDefId=ExchangeServer"); break; case TYPE_SHAREPOINT: case TYPE_SHAREPOINTENTERPRISE: res = PortalUtils.NavigatePageURL(PID_SPACE_EXCHANGESERVER, "ItemID", itemId.ToString(), PortalUtils.SPACE_ID_PARAM + "=" + spaceId, "ctl=" + (itemType == TYPE_SHAREPOINT ? "sharepoint_edit_sitecollection" : "sharepoint_enterprise_edit_sitecollection"), "SiteCollectionID=" + accountId, "moduleDefId=ExchangeServer"); break; default: res = PortalUtils.GetSpaceHomePageUrl(spaceId); break; } } return res; } //TODO START protected void btnSearchObject_Click(object sender, EventArgs e) { String strColumnType = tbSearchColumnType.Text; String strFullType = tbSearchFullType.Text; String strText = tbSearchText.Text; if (strText.Length > 0) { if (strFullType == "Users") { if (tbObjectId.Text.Length > 0) { Response.Redirect(PortalUtils.GetUserHomePageUrl(Int32.Parse(tbObjectId.Text))); } else { Response.Redirect(PortalUtils.NavigatePageURL(PortalUtils.GetUsersSearchPageId(), PortalUtils.USER_ID_PARAM, PanelSecurity.SelectedUserId.ToString(), "Query=" + Server.UrlEncode(strText), "Criteria=" + Server.UrlEncode(strColumnType) )); } } else if (strFullType == "Space") { if (tbObjectId.Text.Length > 0) { Response.Redirect(GetItemPageUrl(strFullType, tbSearchColumnType.Text, Int32.Parse(tbObjectId.Text), Int32.Parse(tbPackageId.Text), Int32.Parse(tbAccountId.Text), tbSearchText.Text)); } else { Response.Redirect(PortalUtils.NavigatePageURL(PortalUtils.GetSpacesSearchPageId(), PortalUtils.USER_ID_PARAM, PanelSecurity.SelectedUserId.ToString(), "Query=" + Server.UrlEncode(strText), "Criteria=" + Server.UrlEncode(strColumnType) )); } } else { if (tbObjectId.Text.Length > 0) { Response.Redirect(GetItemPageUrl(strFullType, tbSearchColumnType.Text, Int32.Parse(tbObjectId.Text), Int32.Parse(tbPackageId.Text), Int32.Parse(tbAccountId.Text), tbSearchText.Text)); } else { Response.Redirect(PortalUtils.NavigatePageURL(PortalUtils.GetObjectSearchPageId(), PortalUtils.USER_ID_PARAM, PanelSecurity.SelectedUserId.ToString(), "Query=" + Server.UrlEncode(strText))); } } } else { Response.Redirect(PortalUtils.NavigatePageURL(PortalUtils.GetObjectSearchPageId(), PortalUtils.USER_ID_PARAM, PanelSecurity.SelectedUserId.ToString(), "Query=" + Server.UrlEncode(tbSearch.Text))); } } //TODO END } }
using System; using System.Collections.Generic; using Orleans.Streams; namespace Orleans.Providers.Streams.Common { /// <summary> /// CachedMessageBlock is a block of tightly packed structures containing tracking data for cached messages. This data is /// tightly packed to reduced GC pressure. The tracking data is used by the queue cache to walk the cache serving ordered /// queue messages by stream. /// </summary> public class CachedMessageBlock : PooledResource<CachedMessageBlock> { private const int OneKb = 1024; private const int DefaultCachedMessagesPerBlock = 16 * OneKb; // 16kb private readonly CachedMessage[] cachedMessages; private readonly int blockSize; private int writeIndex; private int readIndex; /// <summary> /// Linked list node, so this message block can be kept in a linked list /// </summary> public LinkedListNode<CachedMessageBlock> Node { get; private set; } /// <summary> /// More messages can be added to the blocks /// </summary> public bool HasCapacity => writeIndex < blockSize; /// <summary> /// Block is empty /// </summary> public bool IsEmpty => readIndex >= writeIndex; /// <summary> /// Index of most recent message added to the block /// </summary> public int NewestMessageIndex => writeIndex - 1; /// <summary> /// Index of oldest message in this block /// </summary> public int OldestMessageIndex => readIndex; /// <summary> /// Oldest message in the block /// </summary> public CachedMessage OldestMessage => cachedMessages[OldestMessageIndex]; /// <summary> /// Newest message in this block /// </summary> public CachedMessage NewestMessage => cachedMessages[NewestMessageIndex]; /// <summary> /// Message count in this block /// </summary> public int ItemCount { get { int count = writeIndex - readIndex; return count >= 0 ? count : 0; } } /// <summary> /// Block of cached messages /// </summary> /// <param name="blockSize"></param> public CachedMessageBlock(int blockSize = DefaultCachedMessagesPerBlock) { this.blockSize = blockSize; cachedMessages = new CachedMessage[blockSize]; writeIndex = 0; readIndex = 0; Node = new LinkedListNode<CachedMessageBlock>(this); } /// <summary> /// Removes a message from the start of the block (oldest data). Returns true if more items are still available. /// </summary> /// <returns></returns> public bool Remove() { if (readIndex < writeIndex) { readIndex++; return true; } return false; } /// <summary> /// Add a message from the queue to the block. /// Converts the queue message to a cached message and stores it at the end of the block. /// </summary> public void Add(CachedMessage message) { if (!HasCapacity) { throw new InvalidOperationException("Block is full"); } int index = writeIndex++; cachedMessages[index] = message; } /// <summary> /// Access the cached message at the provided index. /// </summary> /// <param name="index"></param> /// <returns></returns> public CachedMessage this[int index] { get { if (index >= writeIndex || index < readIndex) { throw new ArgumentOutOfRangeException("index"); } return cachedMessages[index]; } } /// <summary> /// Gets the sequence token of the cached message a the provided index /// </summary> /// <param name="index"></param> /// <param name="dataAdapter"></param> /// <returns></returns> public StreamSequenceToken GetSequenceToken(int index, ICacheDataAdapter dataAdapter) { if (index >= writeIndex || index < readIndex) { throw new ArgumentOutOfRangeException(nameof(index)); } return dataAdapter.GetSequenceToken(ref cachedMessages[index]); } /// <summary> /// Gets the sequence token of the newest message in this block /// </summary> /// <param name="dataAdapter"></param> /// <returns></returns> public StreamSequenceToken GetNewestSequenceToken(ICacheDataAdapter dataAdapter) { return GetSequenceToken(NewestMessageIndex, dataAdapter); } /// <summary> /// Gets the sequence token of the oldest message in this block /// </summary> /// <param name="dataAdapter"></param> /// <returns></returns> public StreamSequenceToken GetOldestSequenceToken(ICacheDataAdapter dataAdapter) { return GetSequenceToken(OldestMessageIndex, dataAdapter); } /// <summary> /// Gets the index of the first message in this block that has a sequence token at or before the provided token /// </summary> /// <param name="token"></param> /// <returns></returns> public int GetIndexOfFirstMessageLessThanOrEqualTo(StreamSequenceToken token) { for (int i = writeIndex - 1; i >= readIndex; i--) { if (cachedMessages[i].Compare(token) <= 0) { return i; } } throw new ArgumentOutOfRangeException("token"); } /// <summary> /// Tries to find the first message in the block that is part of the provided stream. /// </summary> public bool TryFindFirstMessage(IStreamIdentity streamIdentity, ICacheDataAdapter dataAdapter, out int index) { return TryFindNextMessage(readIndex, streamIdentity, dataAdapter, out index); } /// <summary> /// Tries to get the next message from the provided stream, starting at the start index. /// </summary> public bool TryFindNextMessage(int start, IStreamIdentity streamIdentity, ICacheDataAdapter dataAdapter, out int index) { if (start < readIndex) { throw new ArgumentOutOfRangeException("start"); } for (int i = start; i < writeIndex; i++) { if (cachedMessages[i].CompareStreamId(streamIdentity)) { index = i; return true; } } index = writeIndex - 1; return false; } /// <summary> /// Resets this blocks state to that of an empty block. /// </summary> public override void OnResetState() { writeIndex = 0; readIndex = 0; } } }
/* ==================================================================== */ using System; using System.Xml; using System.Collections; using System.Collections.Generic; namespace Oranikle.Report.Engine { ///<summary> /// A collection of rows. ///</summary> public class Rows : System.Collections.Generic.IComparer<Row> { List<Row> _Data; // array of Row object; List<RowsSortExpression> _SortBy; // array of expressions used to sort the data GroupEntry[] _CurrentGroups; // group Report _Rpt; public Rows(Report rpt) { _Rpt = rpt; _SortBy = null; _CurrentGroups = null; } // Constructor that takes existing Rows; a start, end and bitArray with the rows wanted public Rows(Report rpt, Rows r, int start, int end, BitArray ba) { _Rpt = rpt; _SortBy = null; _CurrentGroups = null; if (end - start < 0) // null set? { _Data = new List<Row>(1); _Data.TrimExcess(); return; } _Data = new List<Row>(end - start + 1); for (int iRow = start; iRow <= end; iRow++) { if (ba == null || ba.Get(iRow)) { Row or = r.Data[iRow]; Row nr = new Row(this, or); nr.RowNumber = or.RowNumber; _Data.Add(nr); } } _Data.TrimExcess(); } // Constructor that takes existing Rows public Rows(Report rpt, Rows r) { _Rpt = rpt; _SortBy = null; _CurrentGroups = null; if (r.Data == null || r.Data.Count <= 0) // null set? { _Data = new List<Row>(1); _Data.TrimExcess(); return; } _Data = new List<Row>(r.Data.Count); for (int iRow = 0; iRow < r.Data.Count; iRow++) { Row or = r.Data[iRow]; Row nr = new Row(this, or); nr.RowNumber = or.RowNumber; _Data.Add(nr); } _Data.TrimExcess(); } // Constructor that creates exactly one row and one column static public Rows CreateOneRow(Report rpt) { Rows or = new Rows(rpt); or._Data = new List<Row>(1); Row nr = new Row(or, 1); nr.RowNumber = 0; or._Data.Add(nr); or._Data.TrimExcess(); return or; } public Rows(Report rpt, TableGroups tg, Grouping g, Sorting s) { _Rpt = rpt; _SortBy = new List<RowsSortExpression>(); // Pull all the sort expression together if (tg != null) { foreach(TableGroup t in tg.Items) { foreach(GroupExpression ge in t.Grouping.GroupExpressions.Items) { _SortBy.Add(new RowsSortExpression(ge.Expression)); } // TODO what to do with the sort expressions!!!! } } if (g != null) { if (g.ParentGroup != null) _SortBy.Add(new RowsSortExpression(g.ParentGroup)); else if (g.GroupExpressions != null) { foreach (GroupExpression ge in g.GroupExpressions.Items) { _SortBy.Add(new RowsSortExpression(ge.Expression)); } } } if (s != null) { foreach (SortBy sb in s.Items) { _SortBy.Add(new RowsSortExpression(sb.SortExpression, sb.Direction == SortDirectionEnum.Ascending)); } } if (_SortBy.Count > 0) _SortBy.TrimExcess(); else _SortBy = null; } public Report Report { get {return this._Rpt;} } public void Sort() { // sort the data array by the data. _Data.Sort(this); } public List<Row> Data { get { return _Data; } set { _Data = value; // Assign the new value foreach(Row r in _Data) // Updata all rows { r.R = this; } } } public List<RowsSortExpression> SortBy { get { return _SortBy; } set { _SortBy = value; } } public GroupEntry[] CurrentGroups { get { return _CurrentGroups; } set { _CurrentGroups = value; } } #region IComparer Members public int Compare(Row r1, Row r2) { if (r1 == r2) // why does the sort routine do this?? return 0; object o1=null,o2=null; TypeCode tc = TypeCode.Object; int rc; try { foreach (RowsSortExpression se in _SortBy) { o1 = se.expr.Evaluate(this._Rpt, r1); o2 = se.expr.Evaluate(this._Rpt, r2); tc = se.expr.GetTypeCode(); rc = Filter.ApplyCompare(tc, o1, o2); if (rc != 0) return se.bAscending? rc: -rc; } } catch (Exception e) // this really shouldn't happen { _Rpt.rl.LogError(8, string.Format("Sort rows exception\r\nArguments: {0} {1}\r\nTypecode: {2}\r\n{3}\r\n{4}", o1, o2, tc.ToString(), e.Message, e.StackTrace)); } return r1.RowNumber - r2.RowNumber; // in case of tie use original row number } #endregion } public class RowsSortExpression { public Expression expr; public bool bAscending; public RowsSortExpression(Expression e, bool asc) { expr = e; bAscending = asc; } public RowsSortExpression(Expression e) { expr = e; bAscending = true; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace openCaseApi.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.IO; using System.Runtime.InteropServices; using ESRI.ArcGIS.ADF.COMSupport; using stdole; namespace Miner.Interop.Process { /// <summary> /// Base class for Tree Tools used to execute Px Tasks in either WorkflowManager or SessionManager. /// You must provide your own COM Registration because they can be registered in multiple categories. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Px")] [ComVisible(true)] public abstract class BasePxTreeTool : IMMTreeViewTool, IMMTreeViewToolEx, IMMTreeViewTool2, IMMTreeViewToolEx2 { #region Fields private static readonly ILog Log = LogProvider.For<BasePxTreeTool>(); #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="BasePxTreeTool" /> class. /// </summary> /// <param name="taskName">Name of the task.</param> /// <param name="priority">The priority.</param> /// <param name="category">The category.</param> /// <param name="categoryName">Name of the category.</param> /// <param name="extensionName">Name of the extension. (i.e MMSessionManager or MMWorkflowManager)</param> protected BasePxTreeTool(string taskName, int priority, int category, string categoryName, string extensionName) { this.Name = taskName; this.Priority = priority; this.Category = category; this.CategoryName = categoryName; this.ExtensionName = extensionName; this.ToolTip = taskName; this.TaskName = taskName; this.SubCategory = 0; this.AllowAsDefaultTool = false; } #endregion #region Public Properties /// <summary> /// Gets a value indicating whether there are allow as default tool. /// </summary> /// <value> /// <c>true</c> if there are allow as default tool; otherwise, <c>false</c>. /// </value> public bool AllowAsDefaultTool { get; protected set; } /// <summary> /// Gets the bitmap. /// </summary> /// <value>The bitmap.</value> public IPictureDisp Bitmap { get; protected set; } /// <summary> /// Gets the category. /// </summary> /// <value>The category.</value> public int Category { get; protected set; } /// <summary> /// Gets the name of the category. /// </summary> /// <value>The name of the category.</value> public string CategoryName { get; protected set; } /// <summary> /// Gets a value indicating whether this <see cref="BasePxTreeTool" /> is checked. /// </summary> /// <value><c>true</c> if checked; otherwise, <c>false</c>.</value> public virtual bool Checked { get; protected set; } /// <summary> /// Gets the name of the extension. /// </summary> /// <value>The name of the extension.</value> public string ExtensionName { get; protected set; } /// <summary> /// Gets the name. /// </summary> /// <value>The name.</value> public string Name { get; protected set; } /// <summary> /// Gets the priority. /// </summary> /// <value>The priority.</value> public int Priority { get; protected set; } /// <summary> /// Gets the sub category. /// </summary> /// <value>The sub category.</value> public int SubCategory { get; protected set; } /// <summary> /// Gets the tool tip. /// </summary> /// <value>The tool tip.</value> public string ToolTip { get; protected set; } #endregion #region Protected Properties /// <summary> /// Gets the process application reference. /// </summary> /// <value> /// The process application reference. /// </value> protected IMMPxApplication PxApplication { get; set; } /// <summary> /// Gets the name of the task. /// </summary> /// <value> /// The name of the task. /// </value> protected string TaskName { get; set; } #endregion #region Public Methods /// <summary> /// Returns <c>true</c> if the tool should be enabled for the specified selection of items. /// </summary> /// <param name="vSelection">The selection.</param> /// <returns> /// <c>true</c> if the tool should be enabled; otherwise <c>false</c> /// </returns> public int EnabledEx(object vSelection) { return get_Enabled((IMMTreeViewSelection) vSelection); } /// <summary> /// Executes the specified tree tool using the selected items. /// </summary> /// <param name="pSelection">The selection.</param> public void Execute(IMMTreeViewSelection pSelection) { try { this.InternalExecute(pSelection); } catch (Exception e) { Log.Error("Error Executing Tree Tool " + this.Name, e); } } /// <summary> /// Executes the specified tree tool using the selected items. /// </summary> /// <param name="vSelection">The selection.</param> /// <returns><c>true</c> if the tool executed; otherwise <c>false</c>.</returns> public bool ExecuteEx(object vSelection) { this.Execute((IMMTreeViewSelection) vSelection); return true; } /// <summary> /// Returns <c>true</c> if the tool should be enabled for the specified selection of items. /// </summary> /// <param name="pSelection">The selection.</param> /// <returns> /// <c>true</c> if the tool should be enabled; otherwise <c>false</c> /// </returns> public int get_Enabled(IMMTreeViewSelection pSelection) { try { return this.InternalEnabled(pSelection); } catch (Exception e) { Log.Error("Error Enabling Tree Tool " + this.Name, e); } return 0; } /// <summary> /// Initializes the specified v init data. /// </summary> /// <param name="vInitData">The v init data.</param> public void Initialize(object vInitData) { this.PxApplication = vInitData as IMMPxApplication; } #endregion #region Protected Methods /// <summary> /// Determines of the tree tool is enabled for the specified selection of items. /// </summary> /// <param name="selection">The selection.</param> /// <returns> /// Returns bitwise flag combination of the <see cref="mmToolState" /> to specify if enabled. /// </returns> protected virtual int InternalEnabled(IMMTreeViewSelection selection) { if (selection == null) return 0; if (selection.Count != 1) return 0; selection.Reset(); IMMPxNode node = (IMMPxNode) selection.Next; IMMPxTask task = ((IMMPxNode3) node).GetTaskByName(this.Name); if (task == null) return 0; if (task.get_Enabled(node)) return 3; return 0; } /// <summary> /// Executes the tree tool within error handling. /// </summary> /// <param name="selection">The selection.</param> protected virtual void InternalExecute(IMMTreeViewSelection selection) { // Only enable if 1 item is selected. if (selection == null || selection.Count != 1) return; // Execute the Task for the specified node. selection.Reset(); IMMPxNode node = (IMMPxNode) selection.Next; IMMPxTask task = ((IMMPxNode3) node).GetTaskByName(this.Name); if (task == null) return; task.Execute(node); } /// <summary> /// Updates the bitmap image with the image from the <paramref name="stream" />. /// </summary> /// <param name="stream">Stream of bitmap to load.</param> protected void UpdateBitmap(Stream stream) { try { Bitmap bitmap = new Bitmap(stream); bitmap.MakeTransparent(bitmap.GetPixel(0, 0)); this.Bitmap = OLE.GetIPictureDispFromBitmap(bitmap) as IPictureDisp; } catch (Exception e) { if (MinerRuntimeEnvironment.IsUserInterfaceSupported) Log.Error("Error Updating Bitmap " + this.Name, e); else Log.Error(e); } } /// <summary> /// Updates the bitmap image with the image from the <paramref name="bitmap" />. /// </summary> /// <param name="bitmap">The bitmap.</param> protected void UpdateBitmap(Bitmap bitmap) { try { this.Bitmap = OLE.GetIPictureDispFromBitmap(bitmap) as IPictureDisp; } catch (Exception e) { if (MinerRuntimeEnvironment.IsUserInterfaceSupported) Log.Error("Error Updating Bitmap " + this.Name, e); else Log.Error(e); } } #endregion } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; /// <summary> /// An <see cref="IHttpProvider"/> implementation using standard .NET libraries. /// </summary> public class HttpProvider : IHttpProvider { internal bool disposeHandler; internal HttpClient httpClient; internal HttpMessageHandler httpMessageHandler; /// <summary> /// Constructs a new <see cref="HttpProvider"/>. /// </summary> /// <param name="serializer">A serializer for serializing and deserializing JSON objects.</param> public HttpProvider(ISerializer serializer = null) : this((HttpMessageHandler)null, true, serializer) { } /// <summary> /// Constructs a new <see cref="HttpProvider"/>. /// </summary> /// <param name="httpClientHandler">An HTTP client handler to pass to the <see cref="HttpClient"/> for sending requests.</param> /// <param name="disposeHandler">Whether or not to dispose the client handler on Dispose().</param> /// <param name="serializer">A serializer for serializing and deserializing JSON objects.</param> /// <remarks> /// By default, HttpProvider disables automatic redirects and handles redirects to preserve authentication headers. If providing /// an <see cref="HttpClientHandler"/> to the constructor and enabling automatic redirects this could cause issues with authentication /// over the redirect. /// </remarks> public HttpProvider(HttpClientHandler httpClientHandler, bool disposeHandler, ISerializer serializer = null) : this((HttpMessageHandler)httpClientHandler, disposeHandler, serializer) { } /// <summary> /// Constructs a new <see cref="HttpProvider"/>. /// </summary> /// <param name="httpMessageHandler">An HTTP message handler to pass to the <see cref="HttpClient"/> for sending requests.</param> /// <param name="disposeHandler">Whether or not to dispose the client handler on Dispose().</param> /// <param name="serializer">A serializer for serializing and deserializing JSON objects.</param> public HttpProvider(HttpMessageHandler httpMessageHandler, bool disposeHandler, ISerializer serializer) { this.disposeHandler = disposeHandler; this.httpMessageHandler = httpMessageHandler; this.Serializer = serializer ?? new Serializer(); // NOTE: Override our pipeline when a httpMessageHandler is provided - httpMessageHandler can implement custom pipeline. // This check won't be needed once we re-write the HttpProvider to work with GraphClientFactory. if (this.httpMessageHandler == null) { this.httpMessageHandler = GraphClientFactory.GetNativePlatformHttpHandler(); this.httpClient = GraphClientFactory.Create(authenticationProvider: null, version: "v1.0", nationalCloud: GraphClientFactory.Global_Cloud, finalHandler: this.httpMessageHandler); } else { this.httpClient = new HttpClient(this.httpMessageHandler, this.disposeHandler); } this.httpClient.SetFeatureFlag(FeatureFlag.DefaultHttpProvider); } /// <summary> /// Gets or sets the cache control header for requests; /// </summary> public CacheControlHeaderValue CacheControlHeader { get { return this.httpClient.DefaultRequestHeaders.CacheControl; } set { this.httpClient.DefaultRequestHeaders.CacheControl = value; } } /// <summary> /// Gets or sets the overall request timeout. /// </summary> public TimeSpan OverallTimeout { get { return this.httpClient.Timeout; } set { try { this.httpClient.Timeout = value; } catch (InvalidOperationException exception) { throw new ServiceException( new Error { Code = ErrorConstants.Codes.NotAllowed, Message = ErrorConstants.Messages.OverallTimeoutCannotBeSet, }, exception); } } } /// <summary> /// Gets a serializer for serializing and deserializing JSON objects. /// </summary> public ISerializer Serializer { get; private set; } /// <summary> /// Disposes the HttpClient and HttpClientHandler instances. /// </summary> public void Dispose() { if (this.httpClient != null) { this.httpClient.Dispose(); } } /// <summary> /// Sends the request. /// </summary> /// <param name="request">The <see cref="HttpRequestMessage"/> to send.</param> /// <returns>The <see cref="HttpResponseMessage"/>.</returns> public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request) { return this.SendAsync(request, HttpCompletionOption.ResponseContentRead, CancellationToken.None); } /// <summary> /// Sends the request. /// </summary> /// <param name="request">The <see cref="HttpRequestMessage"/> to send.</param> /// <param name="completionOption">The <see cref="HttpCompletionOption"/> to pass to the <see cref="IHttpProvider"/> on send.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The <see cref="HttpResponseMessage"/>.</returns> public async Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken) { var response = await this.SendRequestAsync(request, completionOption, cancellationToken).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { using (response) { if (null != response.Content) { await response.Content.LoadIntoBufferAsync().ConfigureAwait(false); } var errorResponse = await this.ConvertErrorResponseAsync(response).ConfigureAwait(false); Error error = null; if (errorResponse == null || errorResponse.Error == null) { if (response != null && response.StatusCode == HttpStatusCode.NotFound) { error = new Error { Code = ErrorConstants.Codes.ItemNotFound }; } else { error = new Error { Code = ErrorConstants.Codes.GeneralException, Message = ErrorConstants.Messages.UnexpectedExceptionResponse, }; } } else { error = errorResponse.Error; } if (string.IsNullOrEmpty(error.ThrowSite)) { IEnumerable<string> throwsiteValues; if (response.Headers.TryGetValues(CoreConstants.Headers.ThrowSiteHeaderName, out throwsiteValues)) { error.ThrowSite = throwsiteValues.FirstOrDefault(); } } if (string.IsNullOrEmpty(error.ClientRequestId)) { IEnumerable<string> clientRequestId; if (response.Headers.TryGetValues(CoreConstants.Headers.ClientRequestId, out clientRequestId)) { error.ClientRequestId = clientRequestId.FirstOrDefault(); } } if (response.Content?.Headers.ContentType.MediaType == "application/json") { string rawResponseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ServiceException(error, response.Headers, response.StatusCode, rawResponseBody); } else { // Pass through the response headers and status code to the ServiceException. // System.Net.HttpStatusCode does not support RFC 6585, Additional HTTP Status Codes. // Throttling status code 429 is in RFC 6586. The status code 429 will be passed through. throw new ServiceException(error, response.Headers, response.StatusCode); } } } return response; } internal async Task<HttpResponseMessage> SendRequestAsync( HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken) { try { return await this.httpClient.SendAsync(request, completionOption, cancellationToken).ConfigureAwait(false); } catch (TaskCanceledException exception) { throw new ServiceException( new Error { Code = ErrorConstants.Codes.Timeout, Message = ErrorConstants.Messages.RequestTimedOut, }, exception); } catch(ServiceException exception) { throw exception; } catch (Exception exception) { throw new ServiceException( new Error { Code = ErrorConstants.Codes.GeneralException, Message = ErrorConstants.Messages.UnexpectedExceptionOnSend, }, exception); } } /// <summary> /// Converts the <see cref="HttpRequestException"/> into an <see cref="ErrorResponse"/> object; /// </summary> /// <param name="response">The <see cref="HttpResponseMessage"/> to convert.</param> /// <returns>The <see cref="ErrorResponse"/> object.</returns> private async Task<ErrorResponse> ConvertErrorResponseAsync(HttpResponseMessage response) { try { using (var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) { return this.Serializer.DeserializeObject<ErrorResponse>(responseStream); } } catch (Exception) { // If there's an exception deserializing the error response return null and throw a generic // ServiceException later. return null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.ComponentModel.Composition.AttributedModel; using System.ComponentModel.Composition.Primitives; using System.ComponentModel.Composition.ReflectionModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using Microsoft.Internal; using Microsoft.Internal.Collections; namespace System.ComponentModel.Composition.Hosting { /// <summary> /// An immutable ComposablePartCatalog created from a type array or a list of managed types. This class is threadsafe. /// It is Disposable. /// </summary> [DebuggerTypeProxy(typeof(ComposablePartCatalogDebuggerProxy))] public class TypeCatalog : ComposablePartCatalog, ICompositionElement { private readonly object _thisLock = new object(); private Type[] _types = null; private volatile List<ComposablePartDefinition> _parts; private volatile bool _isDisposed = false; private readonly ICompositionElement _definitionOrigin; private readonly Lazy<IDictionary<string, List<ComposablePartDefinition>>> _contractPartIndex; /// <summary> /// Initializes a new instance of the <see cref="TypeCatalog"/> class /// with the specified types. /// </summary> /// <param name="types"> /// An <see cref="Array"/> of attributed <see cref="Type"/> objects to add to the /// <see cref="TypeCatalog"/>. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="types"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="types"/> contains an element that is <see langword="null"/>. /// <para> /// -or- /// </para> /// <paramref name="types"/> contains an element that was loaded in the Reflection-only context. /// </exception> public TypeCatalog(params Type[] types) : this((IEnumerable<Type>)types) { } /// <summary> /// Initializes a new instance of the <see cref="TypeCatalog"/> class /// with the specified types. /// </summary> /// <param name="types"> /// An <see cref="IEnumerable{T}"/> of attributed <see cref="Type"/> objects to add /// to the <see cref="TypeCatalog"/>. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="types"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="types"/> contains an element that is <see langword="null"/>. /// <para> /// -or- /// </para> /// <paramref name="types"/> contains an element that was loaded in the reflection-only context. /// </exception> public TypeCatalog(IEnumerable<Type> types) { Requires.NotNull(types, nameof(types)); InitializeTypeCatalog(types); _definitionOrigin = this; _contractPartIndex = new Lazy<IDictionary<string, List<ComposablePartDefinition>>>(CreateIndex, true); } /// <summary> /// Initializes a new instance of the <see cref="TypeCatalog"/> class /// with the specified types. /// </summary> /// <param name="types"> /// An <see cref="IEnumerable{T}"/> of attributed <see cref="Type"/> objects to add /// to the <see cref="TypeCatalog"/>. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="types"/> is <see langword="null"/>. /// </exception> /// <param name="definitionOrigin"> /// The <see cref="ICompositionElement"/> CompositionElement used by Diagnostics to identify the source for parts. /// </param> /// <exception cref="ArgumentException"> /// <paramref name="types"/> contains an element that is <see langword="null"/>. /// </exception> public TypeCatalog(IEnumerable<Type> types, ICompositionElement definitionOrigin) { Requires.NotNull(types, nameof(types)); Requires.NotNull(definitionOrigin, nameof(definitionOrigin)); InitializeTypeCatalog(types); _definitionOrigin = definitionOrigin; _contractPartIndex = new Lazy<IDictionary<string, List<ComposablePartDefinition>>>(CreateIndex, true); } /// <summary> /// Initializes a new instance of the <see cref="TypeCatalog"/> class /// with the specified types. /// </summary> /// <param name="types"> /// An <see cref="IEnumerable{T}"/> of attributed <see cref="Type"/> objects to add /// to the <see cref="TypeCatalog"/>. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="types"/> is <see langword="null"/>. /// </exception> /// <param name="reflectionContext"> /// The <see cref="ReflectionContext"/> a context used by the catalog when /// interpreting the types to inject attributes into the type definition. /// </param> /// <exception cref="ArgumentException"> /// <paramref name="types"/> contains an element that is <see langword="null"/>. /// </exception> public TypeCatalog(IEnumerable<Type> types, ReflectionContext reflectionContext) { Requires.NotNull(types, nameof(types)); Requires.NotNull(reflectionContext, nameof(reflectionContext)); InitializeTypeCatalog(types, reflectionContext); _definitionOrigin = this; _contractPartIndex = new Lazy<IDictionary<string, List<ComposablePartDefinition>>>(CreateIndex, true); } /// <summary> /// Initializes a new instance of the <see cref="TypeCatalog"/> class /// with the specified types. /// </summary> /// <param name="types"> /// An <see cref="IEnumerable{T}"/> of attributed <see cref="Type"/> objects to add /// to the <see cref="TypeCatalog"/>. /// </param> /// <param name="reflectionContext"> /// The <see cref="ReflectionContext"/> a context used by the catalog when /// interpreting the types to inject attributes into the type definition. /// </param> /// <param name="definitionOrigin"> /// The <see cref="ICompositionElement"/> CompositionElement used by Diagnostics to identify the source for parts. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="types"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="types"/> contains an element that is <see langword="null"/>. /// </exception> public TypeCatalog(IEnumerable<Type> types, ReflectionContext reflectionContext, ICompositionElement definitionOrigin) { Requires.NotNull(types, nameof(types)); Requires.NotNull(reflectionContext, nameof(reflectionContext)); Requires.NotNull(definitionOrigin, nameof(definitionOrigin)); InitializeTypeCatalog(types, reflectionContext); _definitionOrigin = definitionOrigin; _contractPartIndex = new Lazy<IDictionary<string, List<ComposablePartDefinition>>>(CreateIndex, true); } private void InitializeTypeCatalog(IEnumerable<Type> types, ReflectionContext reflectionContext) { var typesList = new List<Type>(); foreach (var type in types) { if (type == null) { throw ExceptionBuilder.CreateContainsNullElement(nameof(types)); } if (type.Assembly.ReflectionOnly) { throw new ArgumentException(SR.Format(SR.Argument_ElementReflectionOnlyType, nameof(types)), nameof(types)); } var typeInfo = type.GetTypeInfo(); var lclType = (reflectionContext != null) ? reflectionContext.MapType(typeInfo) : typeInfo; // It is valid for the reflectionContext to delete types by mapping them to null if (lclType != null) { // The final mapped type may be activated so we check to see if it is in a reflect only assembly if (lclType.Assembly.ReflectionOnly) { throw new ArgumentException(SR.Format(SR.Argument_ReflectionContextReturnsReflectionOnlyType, nameof(reflectionContext)), nameof(reflectionContext)); } typesList.Add(lclType); } } _types = typesList.ToArray(); } private void InitializeTypeCatalog(IEnumerable<Type> types) { foreach (var type in types) { if (type == null) { throw ExceptionBuilder.CreateContainsNullElement(nameof(types)); } else if (type.Assembly.ReflectionOnly) { throw new ArgumentException(SR.Format(SR.Argument_ElementReflectionOnlyType, nameof(types)), nameof(types)); } } _types = types.ToArray(); } public override IEnumerator<ComposablePartDefinition> GetEnumerator() { ThrowIfDisposed(); return PartsInternal.GetEnumerator(); } /// <summary> /// Gets the display name of the type catalog. /// </summary> /// <value> /// A <see cref="String"/> containing a human-readable display name of the <see cref="TypeCatalog"/>. /// </value> [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] string ICompositionElement.DisplayName { get { return GetDisplayName(); } } /// <summary> /// Gets the composition element from which the type catalog originated. /// </summary> /// <value> /// This property always returns <see langword="null"/>. /// </value> [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] ICompositionElement ICompositionElement.Origin { get { return null; } } private IEnumerable<ComposablePartDefinition> PartsInternal { get { if (_parts == null) { lock (_thisLock) { if (_parts == null) { if (_types == null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } var collection = new List<ComposablePartDefinition>(); foreach (Type type in _types) { var definition = AttributedModelDiscovery.CreatePartDefinitionIfDiscoverable(type, _definitionOrigin); if (definition != null) { collection.Add(definition); } } Thread.MemoryBarrier(); _types = null; _parts = collection; } } } return _parts; } } internal override IEnumerable<ComposablePartDefinition> GetCandidateParts(ImportDefinition definition) { if (definition == null) { throw new ArgumentNullException(nameof(definition)); } string contractName = definition.ContractName; if (string.IsNullOrEmpty(contractName)) { return PartsInternal; } string genericContractName = definition.Metadata.GetValue<string>(CompositionConstants.GenericContractMetadataName); List<ComposablePartDefinition> nonGenericMatches = GetCandidateParts(contractName); List<ComposablePartDefinition> genericMatches = GetCandidateParts(genericContractName); return nonGenericMatches.ConcatAllowingNull(genericMatches); } private List<ComposablePartDefinition> GetCandidateParts(string contractName) { if (contractName == null) { return null; } List<ComposablePartDefinition> contractCandidateParts = null; _contractPartIndex.Value.TryGetValue(contractName, out contractCandidateParts); return contractCandidateParts; } private IDictionary<string, List<ComposablePartDefinition>> CreateIndex() { Dictionary<string, List<ComposablePartDefinition>> index = new Dictionary<string, List<ComposablePartDefinition>>(StringComparers.ContractName); foreach (var part in PartsInternal) { foreach (string contractName in part.ExportDefinitions.Select(export => export.ContractName).Distinct()) { List<ComposablePartDefinition> contractParts = null; if (!index.TryGetValue(contractName, out contractParts)) { contractParts = new List<ComposablePartDefinition>(); index.Add(contractName, contractParts); } contractParts.Add(part); } } return index; } /// <summary> /// Returns a string representation of the type catalog. /// </summary> /// <returns> /// A <see cref="String"/> containing the string representation of the <see cref="TypeCatalog"/>. /// </returns> public override string ToString() { return GetDisplayName(); } protected override void Dispose(bool disposing) { if (disposing) { _isDisposed = true; } base.Dispose(disposing); } private string GetDisplayName() { return SR.Format( SR.TypeCatalog_DisplayNameFormat, GetType().Name, GetTypesDisplay()); } private string GetTypesDisplay() { int count = PartsInternal.Count(); if (count == 0) { return SR.TypeCatalog_Empty; } const int displayCount = 2; StringBuilder builder = new StringBuilder(); foreach (ReflectionComposablePartDefinition definition in PartsInternal.Take(displayCount)) { if (builder.Length > 0) { builder.Append(CultureInfo.CurrentCulture.TextInfo.ListSeparator); builder.Append(" "); } builder.Append(definition.GetPartType().GetDisplayName()); } if (count > displayCount) { // Add an elipse to indicate that there // are more types than actually listed builder.Append(CultureInfo.CurrentCulture.TextInfo.ListSeparator); builder.Append(" ..."); } return builder.ToString(); } [DebuggerStepThrough] private void ThrowIfDisposed() { if (_isDisposed) { throw ExceptionBuilder.CreateObjectDisposed(this); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Security.Util { using System; using System.Collections; using System.Globalization; using System.Diagnostics.Contracts; [Serializable] internal class SiteString { protected String m_site; protected ArrayList m_separatedSite; protected static char[] m_separators = { '.' }; protected internal SiteString() { // Only call this in derived classes when you know what you're doing. } public SiteString( String site ) { m_separatedSite = CreateSeparatedSite( site ); m_site = site; } private SiteString(String site, ArrayList separatedSite) { m_separatedSite = separatedSite; m_site = site; } private static ArrayList CreateSeparatedSite(String site) { if (site == null || site.Length == 0) { throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" )); } Contract.EndContractBlock(); ArrayList list = new ArrayList(); int braIndex = -1; int ketIndex = -1; braIndex = site.IndexOf('['); if (braIndex == 0) ketIndex = site.IndexOf(']', braIndex+1); if (ketIndex != -1) { // Found an IPv6 address. Special case that String ipv6Addr = site.Substring(braIndex+1, ketIndex-braIndex-1); list.Add(ipv6Addr); return list; } // Regular hostnames or IPv4 addresses // We dont need to do this for IPv4 addresses, but it's easier to do it anyway String[] separatedArray = site.Split( m_separators ); for (int index = separatedArray.Length-1; index > -1; --index) { if (separatedArray[index] == null) { throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" )); } else if (separatedArray[index].Equals( "" )) { if (index != separatedArray.Length-1) { throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" )); } } else if (separatedArray[index].Equals( "*" )) { if (index != 0) { throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" )); } list.Add( separatedArray[index] ); } else if (!AllLegalCharacters( separatedArray[index] )) { throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" )); } else { list.Add( separatedArray[index] ); } } return list; } // KB# Q188997 - http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q188997& gives the list of allowed characters in // a NETBIOS name. DNS names are a subset of that (alphanumeric or '-'). private static bool AllLegalCharacters( String str ) { for (int i = 0; i < str.Length; ++i) { char c = str[i]; if (IsLegalDNSChar(c) || IsNetbiosSplChar(c)) { continue; } else { return false; } } return true; } private static bool IsLegalDNSChar(char c) { if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c == '-')) return true; else return false; } private static bool IsNetbiosSplChar(char c) { // ! @ # $ % ^ & ( ) - _ ' { } . ~ are OK switch (c) { case '-': case '_': case '@': case '!': case '#': case '$': case '%': case '^': case '&': case '(': case ')': case '\'': case '{': case '}': case '.': case '~': return true; default: return false; } } public override String ToString() { return m_site; } public override bool Equals(Object o) { if (o == null || !(o is SiteString)) return false; else return this.Equals( (SiteString)o, true ); } public override int GetHashCode() { TextInfo info = CultureInfo.InvariantCulture.TextInfo; return info.GetCaseInsensitiveHashCode( this.m_site ); } internal bool Equals( SiteString ss, bool ignoreCase ) { if (this.m_site == null) return ss.m_site == null; if (ss.m_site == null) return false; return this.IsSubsetOf(ss, ignoreCase) && ss.IsSubsetOf(this, ignoreCase); } public virtual SiteString Copy() { return new SiteString( m_site, m_separatedSite ); } public virtual bool IsSubsetOf( SiteString operand ) { return this.IsSubsetOf( operand, true ); } public virtual bool IsSubsetOf( SiteString operand, bool ignoreCase ) { StringComparison strComp = (ignoreCase? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); if (operand == null) { return false; } else if (this.m_separatedSite.Count == operand.m_separatedSite.Count && this.m_separatedSite.Count == 0) { return true; } else if (this.m_separatedSite.Count < operand.m_separatedSite.Count - 1) { return false; } else if (this.m_separatedSite.Count > operand.m_separatedSite.Count && operand.m_separatedSite.Count > 0 && !operand.m_separatedSite[operand.m_separatedSite.Count - 1].Equals("*")) { return false; } else if (String.Compare( this.m_site, operand.m_site, strComp) == 0) { return true; } for (int index = 0; index < operand.m_separatedSite.Count - 1; ++index) { if (String.Compare((String)this.m_separatedSite[index], (String)operand.m_separatedSite[index], strComp) != 0) { return false; } } if (this.m_separatedSite.Count < operand.m_separatedSite.Count) { return operand.m_separatedSite[operand.m_separatedSite.Count - 1].Equals("*"); } else if (this.m_separatedSite.Count == operand.m_separatedSite.Count) { // last item must be the same or operand must have a * in its last item return (String.Compare((String)this.m_separatedSite[this.m_separatedSite.Count - 1], (String)operand.m_separatedSite[this.m_separatedSite.Count - 1], strComp ) == 0 || operand.m_separatedSite[operand.m_separatedSite.Count - 1].Equals("*")); } else return true; } public virtual SiteString Intersect( SiteString operand ) { if (operand == null) { return null; } else if (this.IsSubsetOf( operand )) { return this.Copy(); } else if (operand.IsSubsetOf( this )) { return operand.Copy(); } else { return null; } } public virtual SiteString Union( SiteString operand ) { if (operand == null) { return this; } else if (this.IsSubsetOf( operand )) { return operand.Copy(); } else if (operand.IsSubsetOf( this )) { return this.Copy(); } else { return null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.IO.Tests { public class PathTests_Combine { private static readonly char s_separator = Path.DirectorySeparatorChar; public static IEnumerable<object[]> Combine_Basic_TestData() { yield return new object[] { new string[0] }; yield return new object[] { new string[] { "abc" } }; yield return new object[] { new string[] { "abc", "def" } }; yield return new object[] { new string[] { "abc", "def", "ghi", "jkl", "mno" } }; yield return new object[] { new string[] { "abc" + s_separator + "def", "def", "ghi", "jkl", "mno" } }; // All paths are empty yield return new object[] { new string[] { "" } }; yield return new object[] { new string[] { "", "" } }; yield return new object[] { new string[] { "", "", "" } }; yield return new object[] { new string[] { "", "", "", "" } }; yield return new object[] { new string[] { "", "", "", "", "" } }; // Elements are all separated yield return new object[] { new string[] { "abc" + s_separator, "def" + s_separator } }; yield return new object[] { new string[] { "abc" + s_separator, "def" + s_separator, "ghi" + s_separator } }; yield return new object[] { new string[] { "abc" + s_separator, "def" + s_separator, "ghi" + s_separator, "jkl" + s_separator } }; yield return new object[] { new string[] { "abc" + s_separator, "def" + s_separator, "ghi" + s_separator, "jkl" + s_separator, "mno" + s_separator } }; } public static IEnumerable<string> Combine_CommonCases_Input_TestData() { // Any path is rooted (starts with \, \\, A:) yield return s_separator + "abc"; yield return s_separator + s_separator + "abc"; // Any path is empty (skipped) yield return ""; // Any path is single element yield return "abc"; yield return "abc" + s_separator; // Any path is multiple element yield return Path.Combine("abc", Path.Combine("def", "ghi")); // Wildcard characters yield return "*"; yield return "?"; // Obscure wildcard characters yield return "\""; yield return "<"; yield return ">"; } public static IEnumerable<object[]> Combine_CommonCases_TestData() { foreach (string testPath in Combine_CommonCases_Input_TestData()) { yield return new object[] { new string[] { testPath } }; yield return new object[] { new string[] { "abc", testPath } }; yield return new object[] { new string[] { testPath, "abc" } }; yield return new object[] { new string[] { "abc", "def", testPath } }; yield return new object[] { new string[] { "abc", testPath, "def" } }; yield return new object[] { new string[] { testPath, "abc", "def" } }; yield return new object[] { new string[] { "abc", "def", "ghi", testPath } }; yield return new object[] { new string[] { "abc", "def", testPath, "ghi" } }; yield return new object[] { new string[] { "abc", testPath, "def", "ghi" } }; yield return new object[] { new string[] { testPath, "abc", "def", "ghi" } }; yield return new object[] { new string[] { "abc", "def", "ghi", "jkl", testPath } }; yield return new object[] { new string[] { "abc", "def", "ghi", testPath, "jkl" } }; yield return new object[] { new string[] { "abc", "def", testPath, "ghi", "jkl" } }; yield return new object[] { new string[] { "abc", testPath, "def", "ghi", "jkl" } }; yield return new object[] { new string[] { testPath, "abc", "def", "ghi", "jkl" } }; } } [Theory] [MemberData(nameof(Combine_Basic_TestData))] [MemberData(nameof(Combine_CommonCases_TestData))] public static void Combine(string[] paths) { string expected = string.Empty; if (paths.Length > 0) expected = paths[0]; for (int i = 1; i < paths.Length; i++) { expected = Path.Combine(expected, paths[i]); } // Combine(string[]) Assert.Equal(expected, Path.Combine(paths)); // Verify special cases switch (paths.Length) { case 2: // Combine(string, string) Assert.Equal(expected, Path.Combine(paths[0], paths[1])); break; case 3: // Combine(string, string, string) Assert.Equal(expected, Path.Combine(paths[0], paths[1], paths[2])); break; case 4: // Combine(string, string, string, string) Assert.Equal(expected, Path.Combine(paths[0], paths[1], paths[2], paths[3])); break; } } [Fact] public static void PathIsNull() { VerifyException<ArgumentNullException>(null); } [Fact] public static void PathIsNullWihtoutRooted() { //any path is null without rooted after (ANE) CommonCasesException<ArgumentNullException>(null); } [Fact] public static void ContainsInvalidCharWithoutRooted_Core() { Assert.Equal("ab\0cd", Path.Combine("ab\0cd")); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Tests Windows-specific invalid paths public static void ContainsInvalidCharWithoutRooted_Windows_Core() { Assert.Equal("ab|cd", Path.Combine("ab|cd")); Assert.Equal("ab\bcd", Path.Combine("ab\bcd")); Assert.Equal("ab\0cd", Path.Combine("ab\0cd")); Assert.Equal("ab\tcd", Path.Combine("ab\tcd")); } [Fact] public static void ContainsInvalidCharWithRooted_Core() { Assert.Equal(s_separator + "abc", Path.Combine("ab\0cd", s_separator + "abc")); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Tests Windows-specific invalid paths public static void ContainsInvalidCharWithRooted_Windows_core() { Assert.Equal(s_separator + "abc", Path.Combine("ab|cd", s_separator + "abc")); Assert.Equal(s_separator + "abc", Path.Combine("ab\bcd", s_separator + "abc")); Assert.Equal(s_separator + "abc", Path.Combine("ab\tcd", s_separator + "abc")); } private static void VerifyException<T>(string[] paths) where T : Exception { Assert.Throws<T>(() => Path.Combine(paths)); //verify passed as elements case if (paths != null) { Assert.InRange(paths.Length, 1, 5); Assert.Throws<T>(() => { switch (paths.Length) { case 0: Path.Combine(); break; case 1: Path.Combine(paths[0]); break; case 2: Path.Combine(paths[0], paths[1]); break; case 3: Path.Combine(paths[0], paths[1], paths[2]); break; case 4: Path.Combine(paths[0], paths[1], paths[2], paths[3]); break; case 5: Path.Combine(paths[0], paths[1], paths[2], paths[3], paths[4]); break; } }); } } private static void CommonCasesException<T>(string testing) where T : Exception { VerifyException<T>(new string[] { testing }); VerifyException<T>(new string[] { "abc", testing }); VerifyException<T>(new string[] { testing, "abc" }); VerifyException<T>(new string[] { "abc", "def", testing }); VerifyException<T>(new string[] { "abc", testing, "def" }); VerifyException<T>(new string[] { testing, "abc", "def" }); VerifyException<T>(new string[] { "abc", "def", "ghi", testing }); VerifyException<T>(new string[] { "abc", "def", testing, "ghi" }); VerifyException<T>(new string[] { "abc", testing, "def", "ghi" }); VerifyException<T>(new string[] { testing, "abc", "def", "ghi" }); VerifyException<T>(new string[] { "abc", "def", "ghi", "jkl", testing }); VerifyException<T>(new string[] { "abc", "def", "ghi", testing, "jkl" }); VerifyException<T>(new string[] { "abc", "def", testing, "ghi", "jkl" }); VerifyException<T>(new string[] { "abc", testing, "def", "ghi", "jkl" }); VerifyException<T>(new string[] { testing, "abc", "def", "ghi", "jkl" }); } private static void CommonCasesException<T>(string testing, string testing2) where T : Exception { VerifyException<T>(new string[] { testing, testing2 }); VerifyException<T>(new string[] { "abc", testing, testing2 }); VerifyException<T>(new string[] { testing, "abc", testing2 }); VerifyException<T>(new string[] { testing, testing2, "def" }); VerifyException<T>(new string[] { "abc", "def", testing, testing2 }); VerifyException<T>(new string[] { "abc", testing, "def", testing2 }); VerifyException<T>(new string[] { "abc", testing, testing2, "ghi" }); VerifyException<T>(new string[] { testing, "abc", "def", testing2 }); VerifyException<T>(new string[] { testing, "abc", testing2, "ghi" }); VerifyException<T>(new string[] { testing, testing2, "def", "ghi" }); VerifyException<T>(new string[] { "abc", "def", "ghi", testing, testing2 }); VerifyException<T>(new string[] { "abc", "def", testing, "ghi", testing2 }); VerifyException<T>(new string[] { "abc", "def", testing, testing2, "jkl" }); VerifyException<T>(new string[] { "abc", testing, "def", "ghi", testing2 }); VerifyException<T>(new string[] { "abc", testing, "def", testing2, "jkl" }); VerifyException<T>(new string[] { "abc", testing, testing2, "ghi", "jkl" }); VerifyException<T>(new string[] { testing, "abc", "def", "ghi", testing2 }); VerifyException<T>(new string[] { testing, "abc", "def", testing2, "jkl" }); VerifyException<T>(new string[] { testing, "abc", testing2, "ghi", "jkl" }); VerifyException<T>(new string[] { testing, testing2, "def", "ghi", "jkl" }); } } }
using System; using ChainUtils.BouncyCastle.Crypto.Utilities; using ChainUtils.BouncyCastle.Utilities; namespace ChainUtils.BouncyCastle.Crypto.Digests { /** * implementation of SHA-1 as outlined in "Handbook of Applied Cryptography", pages 346 - 349. * * It is interesting to ponder why the, apart from the extra IV, the other difference here from MD5 * is the "endianness" of the word processing! */ public class Sha1Digest : GeneralDigest { private const int DigestLength = 20; private uint H1, H2, H3, H4, H5; private uint[] X = new uint[80]; private int xOff; public Sha1Digest() { Reset(); } /** * Copy constructor. This will copy the state of the provided * message digest. */ public Sha1Digest(Sha1Digest t) : base(t) { CopyIn(t); } private void CopyIn(Sha1Digest t) { base.CopyIn(t); H1 = t.H1; H2 = t.H2; H3 = t.H3; H4 = t.H4; H5 = t.H5; Array.Copy(t.X, 0, X, 0, t.X.Length); xOff = t.xOff; } public override string AlgorithmName { get { return "SHA-1"; } } public override int GetDigestSize() { return DigestLength; } internal override void ProcessWord( byte[] input, int inOff) { X[xOff] = Pack.BE_To_UInt32(input, inOff); if (++xOff == 16) { ProcessBlock(); } } internal override void ProcessLength(long bitLength) { if (xOff > 14) { ProcessBlock(); } X[14] = (uint)((ulong)bitLength >> 32); X[15] = (uint)((ulong)bitLength); } public override int DoFinal( byte[] output, int outOff) { Finish(); Pack.UInt32_To_BE(H1, output, outOff); Pack.UInt32_To_BE(H2, output, outOff + 4); Pack.UInt32_To_BE(H3, output, outOff + 8); Pack.UInt32_To_BE(H4, output, outOff + 12); Pack.UInt32_To_BE(H5, output, outOff + 16); Reset(); return DigestLength; } /** * reset the chaining variables */ public override void Reset() { base.Reset(); H1 = 0x67452301; H2 = 0xefcdab89; H3 = 0x98badcfe; H4 = 0x10325476; H5 = 0xc3d2e1f0; xOff = 0; Array.Clear(X, 0, X.Length); } // // Additive constants // private const uint Y1 = 0x5a827999; private const uint Y2 = 0x6ed9eba1; private const uint Y3 = 0x8f1bbcdc; private const uint Y4 = 0xca62c1d6; private static uint F(uint u, uint v, uint w) { return (u & v) | (~u & w); } private static uint H(uint u, uint v, uint w) { return u ^ v ^ w; } private static uint G(uint u, uint v, uint w) { return (u & v) | (u & w) | (v & w); } internal override void ProcessBlock() { // // expand 16 word block into 80 word block. // for (var i = 16; i < 80; i++) { var t = X[i - 3] ^ X[i - 8] ^ X[i - 14] ^ X[i - 16]; X[i] = t << 1 | t >> 31; } // // set up working variables. // var A = H1; var B = H2; var C = H3; var D = H4; var E = H5; // // round 1 // var idx = 0; for (var j = 0; j < 4; j++) { // E = rotateLeft(A, 5) + F(B, C, D) + E + X[idx++] + Y1 // B = rotateLeft(B, 30) E += (A << 5 | (A >> 27)) + F(B, C, D) + X[idx++] + Y1; B = B << 30 | (B >> 2); D += (E << 5 | (E >> 27)) + F(A, B, C) + X[idx++] + Y1; A = A << 30 | (A >> 2); C += (D << 5 | (D >> 27)) + F(E, A, B) + X[idx++] + Y1; E = E << 30 | (E >> 2); B += (C << 5 | (C >> 27)) + F(D, E, A) + X[idx++] + Y1; D = D << 30 | (D >> 2); A += (B << 5 | (B >> 27)) + F(C, D, E) + X[idx++] + Y1; C = C << 30 | (C >> 2); } // // round 2 // for (var j = 0; j < 4; j++) { // E = rotateLeft(A, 5) + H(B, C, D) + E + X[idx++] + Y2 // B = rotateLeft(B, 30) E += (A << 5 | (A >> 27)) + H(B, C, D) + X[idx++] + Y2; B = B << 30 | (B >> 2); D += (E << 5 | (E >> 27)) + H(A, B, C) + X[idx++] + Y2; A = A << 30 | (A >> 2); C += (D << 5 | (D >> 27)) + H(E, A, B) + X[idx++] + Y2; E = E << 30 | (E >> 2); B += (C << 5 | (C >> 27)) + H(D, E, A) + X[idx++] + Y2; D = D << 30 | (D >> 2); A += (B << 5 | (B >> 27)) + H(C, D, E) + X[idx++] + Y2; C = C << 30 | (C >> 2); } // // round 3 // for (var j = 0; j < 4; j++) { // E = rotateLeft(A, 5) + G(B, C, D) + E + X[idx++] + Y3 // B = rotateLeft(B, 30) E += (A << 5 | (A >> 27)) + G(B, C, D) + X[idx++] + Y3; B = B << 30 | (B >> 2); D += (E << 5 | (E >> 27)) + G(A, B, C) + X[idx++] + Y3; A = A << 30 | (A >> 2); C += (D << 5 | (D >> 27)) + G(E, A, B) + X[idx++] + Y3; E = E << 30 | (E >> 2); B += (C << 5 | (C >> 27)) + G(D, E, A) + X[idx++] + Y3; D = D << 30 | (D >> 2); A += (B << 5 | (B >> 27)) + G(C, D, E) + X[idx++] + Y3; C = C << 30 | (C >> 2); } // // round 4 // for (var j = 0; j < 4; j++) { // E = rotateLeft(A, 5) + H(B, C, D) + E + X[idx++] + Y4 // B = rotateLeft(B, 30) E += (A << 5 | (A >> 27)) + H(B, C, D) + X[idx++] + Y4; B = B << 30 | (B >> 2); D += (E << 5 | (E >> 27)) + H(A, B, C) + X[idx++] + Y4; A = A << 30 | (A >> 2); C += (D << 5 | (D >> 27)) + H(E, A, B) + X[idx++] + Y4; E = E << 30 | (E >> 2); B += (C << 5 | (C >> 27)) + H(D, E, A) + X[idx++] + Y4; D = D << 30 | (D >> 2); A += (B << 5 | (B >> 27)) + H(C, D, E) + X[idx++] + Y4; C = C << 30 | (C >> 2); } H1 += A; H2 += B; H3 += C; H4 += D; H5 += E; // // reset start of the buffer. // xOff = 0; Array.Clear(X, 0, 16); } public override IMemoable Copy() { return new Sha1Digest(this); } public override void Reset(IMemoable other) { var d = (Sha1Digest)other; CopyIn(d); } } }
namespace Org.BouncyCastle.Math.EC { public abstract class ECFieldElement { public abstract IBigInteger ToBigInteger(); public abstract string FieldName { get; } public abstract int FieldSize { get; } public abstract ECFieldElement Add(ECFieldElement b); public abstract ECFieldElement Subtract(ECFieldElement b); public abstract ECFieldElement Multiply(ECFieldElement b); public abstract ECFieldElement Divide(ECFieldElement b); public abstract ECFieldElement Negate(); public abstract ECFieldElement Square(); public abstract ECFieldElement Invert(); public abstract ECFieldElement Sqrt(); public override bool Equals( object obj) { if (obj == this) return true; var other = obj as ECFieldElement; return other != null && Equals(other); } protected bool Equals(ECFieldElement other) { return ToBigInteger().Equals(other.ToBigInteger()); } public override int GetHashCode() { return ToBigInteger().GetHashCode(); } public override string ToString() { return this.ToBigInteger().ToString(2); } } // /** // * Class representing the Elements of the finite field // * <code>F<sub>2<sup>m</sup></sub></code> in polynomial basis (PB) // * representation. Both trinomial (Tpb) and pentanomial (Ppb) polynomial // * basis representations are supported. Gaussian normal basis (GNB) // * representation is not supported. // */ // public class F2mFieldElement // : ECFieldElement // { // /** // * Indicates gaussian normal basis representation (GNB). Number chosen // * according to X9.62. GNB is not implemented at present. // */ // public const int Gnb = 1; // // /** // * Indicates trinomial basis representation (Tpb). Number chosen // * according to X9.62. // */ // public const int Tpb = 2; // // /** // * Indicates pentanomial basis representation (Ppb). Number chosen // * according to X9.62. // */ // public const int Ppb = 3; // // /** // * Tpb or Ppb. // */ // private int representation; // // /** // * The exponent <code>m</code> of <code>F<sub>2<sup>m</sup></sub></code>. // */ // private int m; // // /** // * Tpb: The integer <code>k</code> where <code>x<sup>m</sup> + // * x<sup>k</sup> + 1</code> represents the reduction polynomial // * <code>f(z)</code>.<br/> // * Ppb: The integer <code>k1</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br/> // */ // private int k1; // // /** // * Tpb: Always set to <code>0</code><br/> // * Ppb: The integer <code>k2</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br/> // */ // private int k2; // // /** // * Tpb: Always set to <code>0</code><br/> // * Ppb: The integer <code>k3</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br/> // */ // private int k3; // // /** // * Constructor for Ppb. // * @param m The exponent <code>m</code> of // * <code>F<sub>2<sup>m</sup></sub></code>. // * @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>. // * @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>. // * @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>. // * @param x The IBigInteger representing the value of the field element. // */ // public F2mFieldElement( // int m, // int k1, // int k2, // int k3, // BigInteger x) // : base(x) // { // if ((k2 == 0) && (k3 == 0)) // { // this.representation = Tpb; // } // else // { // if (k2 >= k3) // throw new ArgumentException("k2 must be smaller than k3"); // if (k2 <= 0) // throw new ArgumentException("k2 must be larger than 0"); // // this.representation = Ppb; // } // // if (x.SignValue < 0) // throw new ArgumentException("x value cannot be negative"); // // this.m = m; // this.k1 = k1; // this.k2 = k2; // this.k3 = k3; // } // // /** // * Constructor for Tpb. // * @param m The exponent <code>m</code> of // * <code>F<sub>2<sup>m</sup></sub></code>. // * @param k The integer <code>k</code> where <code>x<sup>m</sup> + // * x<sup>k</sup> + 1</code> represents the reduction // * polynomial <code>f(z)</code>. // * @param x The IBigInteger representing the value of the field element. // */ // public F2mFieldElement( // int m, // int k, // BigInteger x) // : this(m, k, 0, 0, x) // { // // Set k1 to k, and set k2 and k3 to 0 // } // // public override string FieldName // { // get { return "F2m"; } // } // // /** // * Checks, if the ECFieldElements <code>a</code> and <code>b</code> // * are elements of the same field <code>F<sub>2<sup>m</sup></sub></code> // * (having the same representation). // * @param a field element. // * @param b field element to be compared. // * @throws ArgumentException if <code>a</code> and <code>b</code> // * are not elements of the same field // * <code>F<sub>2<sup>m</sup></sub></code> (having the same // * representation). // */ // public static void CheckFieldElements( // ECFieldElement a, // ECFieldElement b) // { // if (!(a is F2mFieldElement) || !(b is F2mFieldElement)) // { // throw new ArgumentException("Field elements are not " // + "both instances of F2mFieldElement"); // } // // if ((a.x.SignValue < 0) || (b.x.SignValue < 0)) // { // throw new ArgumentException( // "x value may not be negative"); // } // // F2mFieldElement aF2m = (F2mFieldElement)a; // F2mFieldElement bF2m = (F2mFieldElement)b; // // if ((aF2m.m != bF2m.m) || (aF2m.k1 != bF2m.k1) // || (aF2m.k2 != bF2m.k2) || (aF2m.k3 != bF2m.k3)) // { // throw new ArgumentException("Field elements are not " // + "elements of the same field F2m"); // } // // if (aF2m.representation != bF2m.representation) // { // // Should never occur // throw new ArgumentException( // "One of the field " // + "elements are not elements has incorrect representation"); // } // } // // /** // * Computes <code>z * a(z) mod f(z)</code>, where <code>f(z)</code> is // * the reduction polynomial of <code>this</code>. // * @param a The polynomial <code>a(z)</code> to be multiplied by // * <code>z mod f(z)</code>. // * @return <code>z * a(z) mod f(z)</code> // */ // private IBigInteger multZModF( // IBigInteger a) // { // // Left-shift of a(z) // IBigInteger az = a.ShiftLeft(1); // if (az.TestBit(this.m)) // { // // If the coefficient of z^m in a(z) Equals 1, reduction // // modulo f(z) is performed: Add f(z) to to a(z): // // Step 1: Unset mth coeffient of a(z) // az = az.ClearBit(this.m); // // // Step 2: Add r(z) to a(z), where r(z) is defined as // // f(z) = z^m + r(z), and k1, k2, k3 are the positions of // // the non-zero coefficients in r(z) // az = az.FlipBit(0); // az = az.FlipBit(this.k1); // if (this.representation == Ppb) // { // az = az.FlipBit(this.k2); // az = az.FlipBit(this.k3); // } // } // return az; // } // // public override ECFieldElement Add( // ECFieldElement b) // { // // No check performed here for performance reasons. Instead the // // elements involved are checked in ECPoint.F2m // // checkFieldElements(this, b); // if (b.x.SignValue == 0) // return this; // // return new F2mFieldElement(this.m, this.k1, this.k2, this.k3, this.x.Xor(b.x)); // } // // public override ECFieldElement Subtract( // ECFieldElement b) // { // // Addition and subtraction are the same in F2m // return Add(b); // } // // public override ECFieldElement Multiply( // ECFieldElement b) // { // // Left-to-right shift-and-add field multiplication in F2m // // Input: Binary polynomials a(z) and b(z) of degree at most m-1 // // Output: c(z) = a(z) * b(z) mod f(z) // // // No check performed here for performance reasons. Instead the // // elements involved are checked in ECPoint.F2m // // checkFieldElements(this, b); // IBigInteger az = this.x; // IBigInteger bz = b.x; // IBigInteger cz; // // // Compute c(z) = a(z) * b(z) mod f(z) // if (az.TestBit(0)) // { // cz = bz; // } // else // { // cz = BigInteger.Zero; // } // // for (int i = 1; i < this.m; i++) // { // // b(z) := z * b(z) mod f(z) // bz = multZModF(bz); // // if (az.TestBit(i)) // { // // If the coefficient of x^i in a(z) Equals 1, b(z) is added // // to c(z) // cz = cz.Xor(bz); // } // } // return new F2mFieldElement(m, this.k1, this.k2, this.k3, cz); // } // // // public override ECFieldElement Divide( // ECFieldElement b) // { // // There may be more efficient implementations // ECFieldElement bInv = b.Invert(); // return Multiply(bInv); // } // // public override ECFieldElement Negate() // { // // -x == x holds for all x in F2m // return this; // } // // public override ECFieldElement Square() // { // // Naive implementation, can probably be speeded up using modular // // reduction // return Multiply(this); // } // // public override ECFieldElement Invert() // { // // Inversion in F2m using the extended Euclidean algorithm // // Input: A nonzero polynomial a(z) of degree at most m-1 // // Output: a(z)^(-1) mod f(z) // // // u(z) := a(z) // IBigInteger uz = this.x; // if (uz.SignValue <= 0) // { // throw new ArithmeticException("x is zero or negative, " + // "inversion is impossible"); // } // // // v(z) := f(z) // IBigInteger vz = BigInteger.One.ShiftLeft(m); // vz = vz.SetBit(0); // vz = vz.SetBit(this.k1); // if (this.representation == Ppb) // { // vz = vz.SetBit(this.k2); // vz = vz.SetBit(this.k3); // } // // // g1(z) := 1, g2(z) := 0 // IBigInteger g1z = BigInteger.One; // IBigInteger g2z = BigInteger.Zero; // // // while u != 1 // while (uz.SignValue != 0) // { // // j := deg(u(z)) - deg(v(z)) // int j = uz.BitLength - vz.BitLength; // // // If j < 0 then: u(z) <-> v(z), g1(z) <-> g2(z), j := -j // if (j < 0) // { // IBigInteger uzCopy = uz; // uz = vz; // vz = uzCopy; // // IBigInteger g1zCopy = g1z; // g1z = g2z; // g2z = g1zCopy; // // j = -j; // } // // // u(z) := u(z) + z^j * v(z) // // Note, that no reduction modulo f(z) is required, because // // deg(u(z) + z^j * v(z)) <= max(deg(u(z)), j + deg(v(z))) // // = max(deg(u(z)), deg(u(z)) - deg(v(z)) + deg(v(z)) // // = deg(u(z)) // uz = uz.Xor(vz.ShiftLeft(j)); // // // g1(z) := g1(z) + z^j * g2(z) // g1z = g1z.Xor(g2z.ShiftLeft(j)); // // if (g1z.BitLength() > this.m) { // // throw new ArithmeticException( // // "deg(g1z) >= m, g1z = " + g1z.ToString(2)); // // } // } // return new F2mFieldElement(this.m, this.k1, this.k2, this.k3, g2z); // } // // public override ECFieldElement Sqrt() // { // throw new ArithmeticException("Not implemented"); // } // // /** // * @return the representation of the field // * <code>F<sub>2<sup>m</sup></sub></code>, either of // * {@link F2mFieldElement.Tpb} (trinomial // * basis representation) or // * {@link F2mFieldElement.Ppb} (pentanomial // * basis representation). // */ // public int Representation // { // get { return this.representation; } // } // // /** // * @return the degree <code>m</code> of the reduction polynomial // * <code>f(z)</code>. // */ // public int M // { // get { return this.m; } // } // // /** // * @return Tpb: The integer <code>k</code> where <code>x<sup>m</sup> + // * x<sup>k</sup> + 1</code> represents the reduction polynomial // * <code>f(z)</code>.<br/> // * Ppb: The integer <code>k1</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br/> // */ // public int K1 // { // get { return this.k1; } // } // // /** // * @return Tpb: Always returns <code>0</code><br/> // * Ppb: The integer <code>k2</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br/> // */ // public int K2 // { // get { return this.k2; } // } // // /** // * @return Tpb: Always set to <code>0</code><br/> // * Ppb: The integer <code>k3</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br/> // */ // public int K3 // { // get { return this.k3; } // } // // public override bool Equals( // object obj) // { // if (obj == this) // return true; // // F2mFieldElement other = obj as F2mFieldElement; // // if (other == null) // return false; // // return Equals(other); // } // // protected bool Equals( // F2mFieldElement other) // { // return m == other.m // && k1 == other.k1 // && k2 == other.k2 // && k3 == other.k3 // && representation == other.representation // && base.Equals(other); // } // // public override int GetHashCode() // { // return base.GetHashCode() ^ m ^ k1 ^ k2 ^ k3; // } // } /** * Class representing the Elements of the finite field * <code>F<sub>2<sup>m</sup></sub></code> in polynomial basis (PB) * representation. Both trinomial (Tpb) and pentanomial (Ppb) polynomial * basis representations are supported. Gaussian normal basis (GNB) * representation is not supported. */ }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace System.Collections.Immutable { public sealed partial class ImmutableSortedSet<T> { /// <summary> /// A node in the AVL tree storing this set. /// </summary> [DebuggerDisplay("{_key}")] internal sealed class Node : IBinaryTree<T>, IEnumerable<T> { /// <summary> /// The default empty node. /// </summary> internal static readonly Node EmptyNode = new Node(); /// <summary> /// The key associated with this node. /// </summary> private readonly T _key; /// <summary> /// A value indicating whether this node has been frozen (made immutable). /// </summary> /// <remarks> /// Nodes must be frozen before ever being observed by a wrapping collection type /// to protect collections from further mutations. /// </remarks> private bool _frozen; /// <summary> /// The depth of the tree beneath this node. /// </summary> private byte _height; // AVL tree max height <= ~1.44 * log2(maxNodes + 2) /// <summary> /// The number of elements contained by this subtree starting at this node. /// </summary> /// <remarks> /// If this node would benefit from saving 4 bytes, we could have only a few nodes /// scattered throughout the graph actually record the count of nodes beneath them. /// Those without the count could query their descendants, which would often short-circuit /// when they hit a node that *does* include a count field. /// </remarks> private int _count; /// <summary> /// The left tree. /// </summary> private Node _left; /// <summary> /// The right tree. /// </summary> private Node _right; /// <summary> /// Initializes a new instance of the <see cref="ImmutableSortedSet{T}.Node"/> class /// that is pre-frozen. /// </summary> private Node() { Contract.Ensures(this.IsEmpty); _frozen = true; // the empty node is *always* frozen. } /// <summary> /// Initializes a new instance of the <see cref="ImmutableSortedSet{T}.Node"/> class /// that is not yet frozen. /// </summary> /// <param name="key">The value stored by this node.</param> /// <param name="left">The left branch.</param> /// <param name="right">The right branch.</param> /// <param name="frozen">Whether this node is prefrozen.</param> private Node(T key, Node left, Node right, bool frozen = false) { Requires.NotNull(left, nameof(left)); Requires.NotNull(right, nameof(right)); Debug.Assert(!frozen || (left._frozen && right._frozen)); _key = key; _left = left; _right = right; _height = checked((byte)(1 + Math.Max(left._height, right._height))); _count = 1 + left._count + right._count; _frozen = frozen; } /// <summary> /// Gets a value indicating whether this instance is empty. /// </summary> /// <value> /// <c>true</c> if this instance is empty; otherwise, <c>false</c>. /// </value> public bool IsEmpty { get { return _left == null; } } /// <summary> /// Gets the height of the tree beneath this node. /// </summary> public int Height { get { return _height; } } /// <summary> /// Gets the left branch of this node. /// </summary> public Node Left { get { return _left; } } /// <summary> /// Gets the left branch of this node. /// </summary> IBinaryTree IBinaryTree.Left { get { return _left; } } /// <summary> /// Gets the right branch of this node. /// </summary> public Node Right { get { return _right; } } /// <summary> /// Gets the right branch of this node. /// </summary> IBinaryTree IBinaryTree.Right { get { return _right; } } /// <summary> /// Gets the left branch of this node. /// </summary> IBinaryTree<T> IBinaryTree<T>.Left { get { return _left; } } /// <summary> /// Gets the right branch of this node. /// </summary> IBinaryTree<T> IBinaryTree<T>.Right { get { return _right; } } /// <summary> /// Gets the value represented by the current node. /// </summary> public T Value { get { return _key; } } /// <summary> /// Gets the number of elements contained by this subtree starting at this node. /// </summary> public int Count { get { return _count; } } /// <summary> /// Gets the key. /// </summary> internal T Key { get { return _key; } } /// <summary> /// Gets the maximum value in the collection, as defined by the comparer. /// </summary> /// <value>The maximum value in the set.</value> internal T Max { get { if (this.IsEmpty) { return default(T); } Node n = this; while (!n._right.IsEmpty) { n = n._right; } return n._key; } } /// <summary> /// Gets the minimum value in the collection, as defined by the comparer. /// </summary> /// <value>The minimum value in the set.</value> internal T Min { get { if (this.IsEmpty) { return default(T); } Node n = this; while (!n._left.IsEmpty) { n = n._left; } return n._key; } } /// <summary> /// Gets the element of the set at the given index. /// </summary> /// <param name="index">The 0-based index of the element in the set to return.</param> /// <returns>The element at the given position.</returns> internal T this[int index] { get { Requires.Range(index >= 0 && index < this.Count, nameof(index)); if (index < _left._count) { return _left[index]; } if (index > _left._count) { return _right[index - _left._count - 1]; } return _key; } } #region IEnumerable<T> Members /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> public Enumerator GetEnumerator() { return new Enumerator(this); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> [ExcludeFromCodeCoverage] // internal and never called, but here for the interface. IEnumerator<T> IEnumerable<T>.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> [ExcludeFromCodeCoverage] // internal and never called, but here for the interface. IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <param name="builder">The builder, if applicable.</param> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> internal Enumerator GetEnumerator(Builder builder) { return new Enumerator(this, builder); } /// <summary> /// See the <see cref="ICollection{T}"/> interface. /// </summary> internal void CopyTo(T[] array, int arrayIndex) { Requires.NotNull(array, nameof(array)); Requires.Range(arrayIndex >= 0, nameof(arrayIndex)); Requires.Range(array.Length >= arrayIndex + this.Count, nameof(arrayIndex)); foreach (var item in this) { array[arrayIndex++] = item; } } /// <summary> /// See the <see cref="ICollection{T}"/> interface. /// </summary> internal void CopyTo(Array array, int arrayIndex) { Requires.NotNull(array, nameof(array)); Requires.Range(arrayIndex >= 0, nameof(arrayIndex)); Requires.Range(array.Length >= arrayIndex + this.Count, nameof(arrayIndex)); foreach (var item in this) { array.SetValue(item, arrayIndex++); } } /// <summary> /// Adds the specified key to the tree. /// </summary> /// <param name="key">The key.</param> /// <param name="comparer">The comparer.</param> /// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param> /// <returns>The new tree.</returns> internal Node Add(T key, IComparer<T> comparer, out bool mutated) { Requires.NotNull(comparer, nameof(comparer)); if (this.IsEmpty) { mutated = true; return new Node(key, this, this); } else { Node result = this; int compareResult = comparer.Compare(key, _key); if (compareResult > 0) { var newRight = _right.Add(key, comparer, out mutated); if (mutated) { result = this.Mutate(right: newRight); } } else if (compareResult < 0) { var newLeft = _left.Add(key, comparer, out mutated); if (mutated) { result = this.Mutate(left: newLeft); } } else { mutated = false; return this; } return mutated ? MakeBalanced(result) : result; } } /// <summary> /// Removes the specified key from the tree. /// </summary> /// <param name="key">The key.</param> /// <param name="comparer">The comparer.</param> /// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param> /// <returns>The new tree.</returns> internal Node Remove(T key, IComparer<T> comparer, out bool mutated) { Requires.NotNull(comparer, nameof(comparer)); if (this.IsEmpty) { mutated = false; return this; } else { Node result = this; int compare = comparer.Compare(key, _key); if (compare == 0) { // We have a match. mutated = true; // If this is a leaf, just remove it // by returning Empty. If we have only one child, // replace the node with the child. if (_right.IsEmpty && _left.IsEmpty) { result = EmptyNode; } else if (_right.IsEmpty && !_left.IsEmpty) { result = _left; } else if (!_right.IsEmpty && _left.IsEmpty) { result = _right; } else { // We have two children. Remove the next-highest node and replace // this node with it. var successor = _right; while (!successor._left.IsEmpty) { successor = successor._left; } bool dummyMutated; var newRight = _right.Remove(successor._key, comparer, out dummyMutated); result = successor.Mutate(left: _left, right: newRight); } } else if (compare < 0) { var newLeft = _left.Remove(key, comparer, out mutated); if (mutated) { result = this.Mutate(left: newLeft); } } else { var newRight = _right.Remove(key, comparer, out mutated); if (mutated) { result = this.Mutate(right: newRight); } } return result.IsEmpty ? result : MakeBalanced(result); } } /// <summary> /// Determines whether the specified key is in this tree. /// </summary> /// <param name="key">The key.</param> /// <param name="comparer">The comparer.</param> /// <returns> /// <c>true</c> if the tree contains the specified key; otherwise, <c>false</c>. /// </returns> [Pure] internal bool Contains(T key, IComparer<T> comparer) { Requires.NotNull(comparer, nameof(comparer)); return !this.Search(key, comparer).IsEmpty; } /// <summary> /// Freezes this node and all descendant nodes so that any mutations require a new instance of the nodes. /// </summary> internal void Freeze() { // If this node is frozen, all its descendants must already be frozen. if (!_frozen) { _left.Freeze(); _right.Freeze(); _frozen = true; } } /// <summary> /// Searches for the specified key. /// </summary> /// <param name="key">The key to search for.</param> /// <param name="comparer">The comparer.</param> /// <returns>The matching node, or <see cref="EmptyNode"/> if no match was found.</returns> [Pure] internal Node Search(T key, IComparer<T> comparer) { Requires.NotNull(comparer, nameof(comparer)); if (this.IsEmpty) { return this; } else { int compare = comparer.Compare(key, _key); if (compare == 0) { return this; } else if (compare > 0) { return _right.Search(key, comparer); } else { return _left.Search(key, comparer); } } } /// <summary> /// Searches for the specified key. /// </summary> /// <param name="key">The key to search for.</param> /// <param name="comparer">The comparer.</param> /// <returns>The matching node, or <see cref="EmptyNode"/> if no match was found.</returns> [Pure] internal int IndexOf(T key, IComparer<T> comparer) { Requires.NotNull(comparer, nameof(comparer)); if (this.IsEmpty) { return -1; } else { int compare = comparer.Compare(key, _key); if (compare == 0) { return _left.Count; } else if (compare > 0) { int result = _right.IndexOf(key, comparer); bool missing = result < 0; if (missing) { result = ~result; } result = _left.Count + 1 + result; if (missing) { result = ~result; } return result; } else { return _left.IndexOf(key, comparer); } } } /// <summary> /// Returns an <see cref="IEnumerable{T}"/> that iterates over this /// collection in reverse order. /// </summary> /// <returns> /// An enumerator that iterates over the <see cref="ImmutableSortedSet{T}"/> /// in reverse order. /// </returns> [Pure] internal IEnumerator<T> Reverse() { return new Enumerator(this, reverse: true); } #region Tree balancing methods /// <summary> /// AVL rotate left operation. /// </summary> /// <param name="tree">The tree.</param> /// <returns>The rotated tree.</returns> private static Node RotateLeft(Node tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); Contract.Ensures(Contract.Result<Node>() != null); if (tree._right.IsEmpty) { return tree; } var right = tree._right; return right.Mutate(left: tree.Mutate(right: right._left)); } /// <summary> /// AVL rotate right operation. /// </summary> /// <param name="tree">The tree.</param> /// <returns>The rotated tree.</returns> private static Node RotateRight(Node tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); Contract.Ensures(Contract.Result<Node>() != null); if (tree._left.IsEmpty) { return tree; } var left = tree._left; return left.Mutate(right: tree.Mutate(left: left._right)); } /// <summary> /// AVL rotate double-left operation. /// </summary> /// <param name="tree">The tree.</param> /// <returns>The rotated tree.</returns> private static Node DoubleLeft(Node tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); Contract.Ensures(Contract.Result<Node>() != null); if (tree._right.IsEmpty) { return tree; } Node rotatedRightChild = tree.Mutate(right: RotateRight(tree._right)); return RotateLeft(rotatedRightChild); } /// <summary> /// AVL rotate double-right operation. /// </summary> /// <param name="tree">The tree.</param> /// <returns>The rotated tree.</returns> private static Node DoubleRight(Node tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); Contract.Ensures(Contract.Result<Node>() != null); if (tree._left.IsEmpty) { return tree; } Node rotatedLeftChild = tree.Mutate(left: RotateLeft(tree._left)); return RotateRight(rotatedLeftChild); } /// <summary> /// Returns a value indicating whether the tree is in balance. /// </summary> /// <param name="tree">The tree.</param> /// <returns>0 if the tree is in balance, a positive integer if the right side is heavy, or a negative integer if the left side is heavy.</returns> [Pure] private static int Balance(Node tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); return tree._right._height - tree._left._height; } /// <summary> /// Determines whether the specified tree is right heavy. /// </summary> /// <param name="tree">The tree.</param> /// <returns> /// <c>true</c> if [is right heavy] [the specified tree]; otherwise, <c>false</c>. /// </returns> [Pure] private static bool IsRightHeavy(Node tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); return Balance(tree) >= 2; } /// <summary> /// Determines whether the specified tree is left heavy. /// </summary> [Pure] private static bool IsLeftHeavy(Node tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); return Balance(tree) <= -2; } /// <summary> /// Balances the specified tree. /// </summary> /// <param name="tree">The tree.</param> /// <returns>A balanced tree.</returns> [Pure] private static Node MakeBalanced(Node tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); Contract.Ensures(Contract.Result<Node>() != null); if (IsRightHeavy(tree)) { return Balance(tree._right) < 0 ? DoubleLeft(tree) : RotateLeft(tree); } if (IsLeftHeavy(tree)) { return Balance(tree._left) > 0 ? DoubleRight(tree) : RotateRight(tree); } return tree; } #endregion /// <summary> /// Creates a node tree that contains the contents of a list. /// </summary> /// <param name="items">An indexable list with the contents that the new node tree should contain.</param> /// <param name="start">The starting index within <paramref name="items"/> that should be captured by the node tree.</param> /// <param name="length">The number of elements from <paramref name="items"/> that should be captured by the node tree.</param> /// <returns>The root of the created node tree.</returns> [Pure] internal static Node NodeTreeFromList(IOrderedCollection<T> items, int start, int length) { Requires.NotNull(items, nameof(items)); Debug.Assert(start >= 0); Debug.Assert(length >= 0); if (length == 0) { return EmptyNode; } int rightCount = (length - 1) / 2; int leftCount = (length - 1) - rightCount; Node left = NodeTreeFromList(items, start, leftCount); Node right = NodeTreeFromList(items, start + leftCount + 1, rightCount); return new Node(items[start + leftCount], left, right, true); } /// <summary> /// Creates a node mutation, either by mutating this node (if not yet frozen) or by creating a clone of this node /// with the described changes. /// </summary> /// <param name="left">The left branch of the mutated node.</param> /// <param name="right">The right branch of the mutated node.</param> /// <returns>The mutated (or created) node.</returns> private Node Mutate(Node left = null, Node right = null) { if (_frozen) { return new Node(_key, left ?? _left, right ?? _right); } else { if (left != null) { _left = left; } if (right != null) { _right = right; } _height = checked((byte)(1 + Math.Max(_left._height, _right._height))); _count = 1 + _left._count + _right._count; return this; } } } } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections; using System.Configuration; using System.Diagnostics; // ReSharper disable once CheckNamespace namespace log4net.Util { using log4net.helpers; /// <summary> /// Outputs log statements from within the log4net assembly. /// </summary> /// <remarks> /// <para> /// Log4net components cannot make log4net logging calls. However, it is /// sometimes useful for the user to learn about what log4net is /// doing. /// </para> /// <para> /// All log4net internal debug calls go to the standard output stream /// whereas internal error messages are sent to the standard error output /// stream. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public sealed class LogLog { /// <summary> /// The event raised when an internal message has been received. /// </summary> public static event LogReceivedEventHandler LogReceived; private readonly Type source; private readonly DateTime timeStamp; private readonly string prefix; private readonly string message; private readonly Exception exception; /// <summary> /// The Type that generated the internal message. /// </summary> public Type Source { get { return source; } } /// <summary> /// The DateTime stamp of when the internal message was received. /// </summary> public DateTime TimeStamp { get { return timeStamp; } } /// <summary> /// A string indicating the severity of the internal message. /// </summary> /// <remarks> /// "log4net: ", /// "log4net:ERROR ", /// "log4net:WARN " /// </remarks> public string Prefix { get { return prefix; } } /// <summary> /// The internal log message. /// </summary> public string Message { get { return message; } } /// <summary> /// The Exception related to the message. /// </summary> /// <remarks> /// Optional. Will be null if no Exception was passed. /// </remarks> public Exception Exception { get { return exception; } } /// <summary> /// Formats Prefix, Source, and Message in the same format as the value /// sent to Console.Out and Trace.Write. /// </summary> /// <returns></returns> public override string ToString() { return Prefix + Source.Name + ": " + Message; } #region Private Instance Constructors /// <summary> /// Initializes a new instance of the <see cref="LogLog" /> class. /// </summary> /// <param name="source"></param> /// <param name="prefix"></param> /// <param name="message"></param> /// <param name="exception"></param> public LogLog(Type source, string prefix, string message, Exception exception) { timeStamp = DateTime.Now; this.source = source; this.prefix = prefix; this.message = message; this.exception = exception; } #endregion Private Instance Constructors #region Static Constructor /// <summary> /// Static constructor that initializes logging by reading /// settings from the application configuration file. /// </summary> /// <remarks> /// <para> /// The <c>log4net.Internal.Debug</c> application setting /// controls internal debugging. This setting should be set /// to <c>true</c> to enable debugging. /// </para> /// <para> /// The <c>log4net.Internal.Quiet</c> application setting /// suppresses all internal logging including error messages. /// This setting should be set to <c>true</c> to enable message /// suppression. /// </para> /// </remarks> static LogLog() { #if !NETCF try { InternalDebugging = OptionConverter.ToBoolean(SystemInfo.GetAppSetting("log4net.Internal.Debug"), false); QuietMode = OptionConverter.ToBoolean(SystemInfo.GetAppSetting("log4net.Internal.Quiet"), false); EmitInternalMessages = OptionConverter.ToBoolean(SystemInfo.GetAppSetting("log4net.Internal.Emit"), true); } catch(Exception ex) { // If an exception is thrown here then it looks like the config file does not // parse correctly. // // We will leave debug OFF and print an Error message Error(typeof(LogLog), "Exception while reading ConfigurationSettings. Check your .config file is well formed XML.", ex); } #endif } #endregion Static Constructor #region Public Static Properties /// <summary> /// Gets or sets a value indicating whether log4net internal logging /// is enabled or disabled. /// </summary> /// <value> /// <c>true</c> if log4net internal logging is enabled, otherwise /// <c>false</c>. /// </value> /// <remarks> /// <para> /// When set to <c>true</c>, internal debug level logging will be /// displayed. /// </para> /// <para> /// This value can be set by setting the application setting /// <c>log4net.Internal.Debug</c> in the application configuration /// file. /// </para> /// <para> /// The default value is <c>false</c>, i.e. debugging is /// disabled. /// </para> /// </remarks> /// <example> /// <para> /// The following example enables internal debugging using the /// application configuration file : /// </para> /// <code lang="XML" escaped="true"> /// <configuration> /// <appSettings> /// <add key="log4net.Internal.Debug" value="true" /> /// </appSettings> /// </configuration> /// </code> /// </example> public static bool InternalDebugging { get { return s_debugEnabled; } set { s_debugEnabled = value; } } /// <summary> /// Gets or sets a value indicating whether log4net should generate no output /// from internal logging, not even for errors. /// </summary> /// <value> /// <c>true</c> if log4net should generate no output at all from internal /// logging, otherwise <c>false</c>. /// </value> /// <remarks> /// <para> /// When set to <c>true</c> will cause internal logging at all levels to be /// suppressed. This means that no warning or error reports will be logged. /// This option overrides the <see cref="InternalDebugging"/> setting and /// disables all debug also. /// </para> /// <para>This value can be set by setting the application setting /// <c>log4net.Internal.Quiet</c> in the application configuration file. /// </para> /// <para> /// The default value is <c>false</c>, i.e. internal logging is not /// disabled. /// </para> /// </remarks> /// <example> /// The following example disables internal logging using the /// application configuration file : /// <code lang="XML" escaped="true"> /// <configuration> /// <appSettings> /// <add key="log4net.Internal.Quiet" value="true" /> /// </appSettings> /// </configuration> /// </code> /// </example> public static bool QuietMode { get { return s_quietMode; } set { s_quietMode = value; } } /// <summary> /// /// </summary> public static bool EmitInternalMessages { get { return s_emitInternalMessages; } set { s_emitInternalMessages = value; } } #endregion Public Static Properties #region Public Static Methods /// <summary> /// Raises the LogReceived event when an internal messages is received. /// </summary> /// <param name="source"></param> /// <param name="prefix"></param> /// <param name="message"></param> /// <param name="exception"></param> public static void OnLogReceived(Type source, string prefix, string message, Exception exception) { if (LogReceived != null) { LogReceived(null, new LogReceivedEventArgs(new LogLog(source, prefix, message, exception))); } } /// <summary> /// Test if LogLog.Debug is enabled for output. /// </summary> /// <value> /// <c>true</c> if Debug is enabled /// </value> /// <remarks> /// <para> /// Test if LogLog.Debug is enabled for output. /// </para> /// </remarks> public static bool IsDebugEnabled { get { return s_debugEnabled && !s_quietMode; } } /// <summary> /// Writes log4net internal debug messages to the /// standard output stream. /// </summary> /// <param name="source"></param> /// <param name="message">The message to log.</param> /// <remarks> /// <para> /// All internal debug messages are prepended with /// the string "log4net: ". /// </para> /// </remarks> public static void Debug(Type source, string message) { if (IsDebugEnabled) { if (EmitInternalMessages) { EmitOutLine(PREFIX + message); } OnLogReceived(source, PREFIX, message, null); } } /// <summary> /// Writes log4net internal debug messages to the /// standard output stream. /// </summary> /// <param name="source">The Type that generated this message.</param> /// <param name="message">The message to log.</param> /// <param name="exception">An exception to log.</param> /// <remarks> /// <para> /// All internal debug messages are prepended with /// the string "log4net: ". /// </para> /// </remarks> public static void Debug(Type source, string message, Exception exception) { if (IsDebugEnabled) { if (EmitInternalMessages) { EmitOutLine(PREFIX + message); if (exception != null) { EmitOutLine(exception.ToString()); } } OnLogReceived(source, PREFIX, message, exception); } } /// <summary> /// Test if LogLog.Warn is enabled for output. /// </summary> /// <value> /// <c>true</c> if Warn is enabled /// </value> /// <remarks> /// <para> /// Test if LogLog.Warn is enabled for output. /// </para> /// </remarks> public static bool IsWarnEnabled { get { return !s_quietMode; } } /// <summary> /// Writes log4net internal warning messages to the /// standard error stream. /// </summary> /// <param name="source">The Type that generated this message.</param> /// <param name="message">The message to log.</param> /// <remarks> /// <para> /// All internal warning messages are prepended with /// the string "log4net:WARN ". /// </para> /// </remarks> public static void Warn(Type source, string message) { if (IsWarnEnabled) { if (EmitInternalMessages) { EmitErrorLine(WARN_PREFIX + message); } OnLogReceived(source, WARN_PREFIX, message, null); } } /// <summary> /// Writes log4net internal warning messages to the /// standard error stream. /// </summary> /// <param name="source">The Type that generated this message.</param> /// <param name="message">The message to log.</param> /// <param name="exception">An exception to log.</param> /// <remarks> /// <para> /// All internal warning messages are prepended with /// the string "log4net:WARN ". /// </para> /// </remarks> public static void Warn(Type source, string message, Exception exception) { if (IsWarnEnabled) { if (EmitInternalMessages) { EmitErrorLine(WARN_PREFIX + message); if (exception != null) { EmitErrorLine(exception.ToString()); } } OnLogReceived(source, WARN_PREFIX, message, exception); } } /// <summary> /// Test if LogLog.Error is enabled for output. /// </summary> /// <value> /// <c>true</c> if Error is enabled /// </value> /// <remarks> /// <para> /// Test if LogLog.Error is enabled for output. /// </para> /// </remarks> public static bool IsErrorEnabled { get { return !s_quietMode; } } /// <summary> /// Writes log4net internal error messages to the /// standard error stream. /// </summary> /// <param name="source">The Type that generated this message.</param> /// <param name="message">The message to log.</param> /// <remarks> /// <para> /// All internal error messages are prepended with /// the string "log4net:ERROR ". /// </para> /// </remarks> public static void Error(Type source, string message) { if (IsErrorEnabled) { if (EmitInternalMessages) { EmitErrorLine(ERR_PREFIX + message); } OnLogReceived(source, ERR_PREFIX, message, null); } } /// <summary> /// Writes log4net internal error messages to the /// standard error stream. /// </summary> /// <param name="source">The Type that generated this message.</param> /// <param name="message">The message to log.</param> /// <param name="exception">An exception to log.</param> /// <remarks> /// <para> /// All internal debug messages are prepended with /// the string "log4net:ERROR ". /// </para> /// </remarks> public static void Error(Type source, string message, Exception exception) { if (IsErrorEnabled) { if (EmitInternalMessages) { EmitErrorLine(ERR_PREFIX + message); if (exception != null) { EmitErrorLine(exception.ToString()); } } OnLogReceived(source, ERR_PREFIX, message, exception); } } #endregion Public Static Methods /// <summary> /// Writes output to the standard output stream. /// </summary> /// <param name="message">The message to log.</param> /// <remarks> /// <para> /// Writes to both Console.Out and System.Diagnostics.Trace. /// Note that the System.Diagnostics.Trace is not supported /// on the Compact Framework. /// </para> /// <para> /// If the AppDomain is not configured with a config file then /// the call to System.Diagnostics.Trace may fail. This is only /// an issue if you are programmatically creating your own AppDomains. /// </para> /// </remarks> private static void EmitOutLine(string message) { try { #if NETCF Console.WriteLine(message); //System.Diagnostics.Debug.WriteLine(message); #else Console.Out.WriteLine(message); Trace.WriteLine(message); #endif } catch { // Ignore exception, what else can we do? Not really a good idea to propagate back to the caller } } /// <summary> /// Writes output to the standard error stream. /// </summary> /// <param name="message">The message to log.</param> /// <remarks> /// <para> /// Writes to both Console.Error and System.Diagnostics.Trace. /// Note that the System.Diagnostics.Trace is not supported /// on the Compact Framework. /// </para> /// <para> /// If the AppDomain is not configured with a config file then /// the call to System.Diagnostics.Trace may fail. This is only /// an issue if you are programmatically creating your own AppDomains. /// </para> /// </remarks> private static void EmitErrorLine(string message) { try { #if NETCF Console.WriteLine(message); //System.Diagnostics.Debug.WriteLine(message); #else Console.Error.WriteLine(message); Trace.WriteLine(message); #endif } catch { // Ignore exception, what else can we do? Not really a good idea to propagate back to the caller } } #region Private Static Fields /// <summary> /// Default debug level /// </summary> private static bool s_debugEnabled = false; /// <summary> /// In quietMode not even errors generate any output. /// </summary> private static bool s_quietMode = false; private static bool s_emitInternalMessages = true; private const string PREFIX = "log4net: "; private const string ERR_PREFIX = "log4net:ERROR "; private const string WARN_PREFIX = "log4net:WARN "; #endregion Private Static Fields /// <summary> /// Subscribes to the LogLog.LogReceived event and stores messages /// to the supplied IList instance. /// </summary> public class LogReceivedAdapter : IDisposable { private readonly IList items; private readonly LogReceivedEventHandler handler; /// <summary> /// /// </summary> /// <param name="items"></param> public LogReceivedAdapter(IList items) { this.items = items; handler = new LogReceivedEventHandler(LogLog_LogReceived); LogReceived += handler; } void LogLog_LogReceived(object source, LogReceivedEventArgs e) { items.Add(e.LogLog); } /// <summary> /// /// </summary> public IList Items { get { return items; } } /// <summary> /// /// </summary> public void Dispose() { LogReceived -= handler; } } } }
using System; using System.Collections.Generic; namespace BufferManager { public class BufferPool : IDisposable { private List<ArraySegment<byte>> _buffers; private readonly BufferManager _bufferManager; private readonly int _chunkSize; private int _length; private bool _disposed; /// <summary> /// Structure to represent an index and an offset into the list of buffers allowing for quick access to a position /// </summary> private struct Position { public readonly int Index; public readonly int Offset; public Position(int index, int offset) { Index = index; Offset = offset; } } /// <summary> /// Gets the capacity of the <see cref="BufferPool"></see> /// </summary> /// <value>The capacity.</value> public int Capacity { get { CheckDisposed(); return _chunkSize * _buffers.Count; } } /// <summary> /// Gets the current length of the <see cref="BufferPool"></see> /// </summary> /// <value>The length.</value> public int Length { get { return _length; } } /// <summary> /// Gets the effective buffers contained in this <see cref="BufferPool"></see> /// </summary> /// <value>The effective buffers.</value> public IEnumerable<ArraySegment<byte>> EffectiveBuffers { get { CheckDisposed(); if (_length > 0) { Position l = GetPositionFor(_length); //send full buffers for (int i = 0; i < l.Index; i++) { yield return _buffers[i]; } //send partial buffer ArraySegment<byte> last = _buffers[l.Index]; yield return new ArraySegment<byte>(last.Array, last.Offset, l.Offset); } } } /// <summary> /// Gets or sets the <see cref="System.Byte"/> with the specified index. /// </summary> public byte this[int index] { get { CheckDisposed(); if (index < 0 || index > _length) throw new ArgumentOutOfRangeException("index"); Position l = GetPositionFor(index); ArraySegment<byte> buffer = _buffers[l.Index]; return buffer.Array[buffer.Offset + l.Offset]; } set { CheckDisposed(); if (index < 0) throw new ArgumentException("_Index"); Position l = GetPositionFor(index); EnsureCapacity(l); ArraySegment<byte> buffer = _buffers[l.Index]; buffer.Array[buffer.Offset + l.Offset] = value; if (_length <= index) _length = index + 1; } } /// <summary> /// Initializes a new instance of the <see cref="BufferPool"/> class. /// </summary> public BufferPool() : this(1, BufferManager.Default) { } /// <summary> /// Initializes a new instance of the <see cref="BufferPool"/> class. /// </summary> /// <param name="bufferManager">The buffer manager.</param> public BufferPool(BufferManager bufferManager) : this(1, bufferManager) { } /// <summary> /// Initializes a new instance of the <see cref="BufferPool"/> class. /// </summary> /// <param name="initialBufferCount">The number of initial buffers.</param> /// <param name="bufferManager">The buffer manager.</param> public BufferPool(int initialBufferCount, BufferManager bufferManager) { if (initialBufferCount <= 0) throw new ArgumentException("initialBufferCount"); if (bufferManager == null) throw new ArgumentNullException("bufferManager"); _length = 0; _buffers = new List<ArraySegment<byte>>(bufferManager.CheckOut(initialBufferCount)); // must have 1 buffer _chunkSize = _buffers[0].Count; _bufferManager = bufferManager; _disposed = false; } /// <summary> /// Appends the specified data. /// </summary> /// <param name="data">The data to write.</param> public void Append(byte [] data) { if (data == null) throw new ArgumentNullException("data"); Write(_length, data, 0, data.Length); } /// <summary> /// Appends the specified data. /// </summary> /// <param name="data">The data.</param> /// <param name="offset">The offset.</param> /// <param name="count">The count.</param> public void Append(byte [] data, int offset, int count) { Write(_length, data, offset, count); } /// <summary> /// Writes data to the specified position. /// </summary> /// <param name="position">The position to write at.</param> /// <param name="data">The data.</param> /// <param name="offset">The offset.</param> /// <param name="count">The count.</param> public void Write(int position, byte[] data, int offset, int count) { if (data == null) throw new ArgumentNullException("data"); if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException("offset"); if (count < 0 || count + offset > data.Length) throw new ArgumentOutOfRangeException("count"); Write(position, new ArraySegment<byte>(data, offset, count)); } /// <summary> /// Writes data to the specified position. /// </summary> /// <param name="position">The position to write at.</param> /// <param name="data">The data.</param> public void Write(int position, ArraySegment<byte> data) { CheckDisposed(); int written = 0; int tmpLength = position; do { Position loc = GetPositionFor(tmpLength); EnsureCapacity(loc); ArraySegment<byte> current = _buffers[loc.Index]; int canWrite = data.Count - written; int available = current.Count - loc.Offset; canWrite = canWrite > available ? available : canWrite; if (canWrite > 0) Buffer.BlockCopy(data.Array, written + data.Offset, current.Array, current.Offset + loc.Offset, canWrite); written += canWrite; tmpLength += canWrite; } while (written < data.Count); _length = tmpLength > _length ? tmpLength : _length; } /// <summary> /// Reads data from a given position /// </summary> /// <param name="position">The position to read from.</param> /// <param name="data">Where to read the data to.</param> /// <param name="offset">The offset to start reading into.</param> /// <param name="count">The number of bytes to read.</param> /// <returns></returns> public int ReadFrom(int position, byte[] data, int offset, int count) { if (data == null) throw new ArgumentNullException("data"); if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException("offset"); if (count < 0 || count + offset > data.Length) throw new ArgumentOutOfRangeException("count"); return ReadFrom(position, new ArraySegment<byte>(data, offset, count)); } /// <summary> /// Reads data from a given position. /// </summary> /// <param name="position">The position to read from.</param> /// <param name="data">Where to read the data to.</param> /// <returns></returns> public int ReadFrom(int position, ArraySegment<byte> data) { CheckDisposed(); if (position >= _length) return 0; int copied = 0; int left = Math.Min(data.Count, _length - position); int currentLocation = position; while (left > 0) { Position l = GetPositionFor(currentLocation); ArraySegment<byte> current = _buffers[l.Index]; int bytesToRead = Math.Min(_chunkSize - l.Offset, left); if (bytesToRead > 0) { Buffer.BlockCopy(current.Array, current.Offset + l.Offset, data.Array, data.Offset + copied, bytesToRead); copied += bytesToRead; left -= bytesToRead; currentLocation += bytesToRead; } } return copied; } /// <summary> /// Sets the length of the <see cref="BufferPool"></see> /// </summary> /// <param name="newLength">The new length.</param> public void SetLength(int newLength) { SetLength(newLength, true); } /// <summary> /// Sets the length of the <see cref="BufferPool"></see> /// </summary> /// <param name="newLength">The new length</param> /// <param name="releaseMemory">if set to <c>true</c> any memory no longer used will be released.</param> public void SetLength(int newLength, bool releaseMemory) { CheckDisposed(); if (newLength < 0) throw new ArgumentException("newLength must be greater than 0"); int oldCapacity = Capacity; _length = newLength; if (_length < oldCapacity && releaseMemory) RemoveCapacity(GetPositionFor(_length)); else if (_length > oldCapacity) EnsureCapacity(GetPositionFor(_length)); } private void RemoveCapacity(Position position) { while (_buffers.Count > position.Index + 1) { _bufferManager.CheckIn(_buffers[_buffers.Count - 1]); _buffers.RemoveAt(_buffers.Count - 1); } } private void EnsureCapacity(Position position) { if (position.Index >= _buffers.Count) { foreach (ArraySegment<byte> buffer in _bufferManager.CheckOut(position.Index + 1 - _buffers.Count)) { if (buffer.Count != _chunkSize) throw new Exception("Received a buffer of the wrong size: this shouldn't happen, ever."); _buffers.Add(buffer); } } } /// <summary> /// Converts this <see cref="BufferPool"></see> to a byte array. /// </summary> /// <returns></returns> public byte[] ToByteArray() { CheckDisposed(); Position l = GetPositionFor(_length); var result = new byte[_length]; for (int i=0; i<l.Index; i++) { ArraySegment<byte> current = _buffers[i]; //copy full buffers Buffer.BlockCopy(current.Array, current.Offset, result, i * _chunkSize, _chunkSize); } //copy last partial buffer if (l.Index < _buffers.Count) { ArraySegment<byte> last = _buffers[l.Index]; Buffer.BlockCopy(last.Array, last.Offset, result, l.Index*_chunkSize, l.Offset); } return result; } private Position GetPositionFor(int index) { //we could do this much faster if we restricted buffer sizes to powers of 2 var l = new Position(index / _chunkSize, index % _chunkSize); return l; } /// <summary> /// Returns any memory used buy this <see cref="BufferPool"></see> to the <see cref="BufferManager"></see> /// </summary> public void Dispose() { DisposeInternal(); GC.SuppressFinalize(this); } ~BufferPool() { DisposeInternal(); } protected virtual void DisposeInternal() { if (_buffers != null) _bufferManager.CheckIn(_buffers); _disposed = true; _buffers = null; } private void CheckDisposed() { if (_disposed) throw new ObjectDisposedException("Object has been disposed."); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #define ENABLE #define MINBUFFERS using System; using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; using System.Collections.Generic; using System.Collections.Concurrent; using System.Threading; using System.Runtime.CompilerServices; using System.Diagnostics; #if PINNABLEBUFFERCACHE_MSCORLIB namespace System.Threading #else namespace System #endif { internal sealed class PinnableBufferCache { /// <summary> /// Create a PinnableBufferCache that works on any object (it is intended for OverlappedData) /// This is only used in mscorlib. /// </summary> internal PinnableBufferCache(string cacheName, Func<object> factory) { m_NotGen2 = new List<object>(DefaultNumberOfBuffers); m_factory = factory; #if ENABLE // Check to see if we should disable the cache. string envVarName = "PinnableBufferCache_" + cacheName + "_Disabled"; try { string envVar = Environment.GetEnvironmentVariable(envVarName); if (envVar != null) { PinnableBufferCacheEventSource.Log.DebugMessage("Creating " + cacheName + " PinnableBufferCacheDisabled=" + envVar); int index = envVar.IndexOf(cacheName, StringComparison.OrdinalIgnoreCase); if (0 <= index) { // The cache is disabled because we haven't set the cache name. PinnableBufferCacheEventSource.Log.DebugMessage("Disabling " + cacheName); return; } } } catch { // Ignore failures when reading the environment variable. } #endif #if MINBUFFERS // Allow the environment to specify a minimum buffer count. string minEnvVarName = "PinnableBufferCache_" + cacheName + "_MinCount"; try { string minEnvVar = Environment.GetEnvironmentVariable(minEnvVarName); if (minEnvVar != null) { if (int.TryParse(minEnvVar, out m_minBufferCount)) CreateNewBuffers(); } } catch { // Ignore failures when reading the environment variable. } #endif PinnableBufferCacheEventSource.Log.Create(cacheName); m_CacheName = cacheName; } /// <summary> /// Get a object from the buffer manager. If no buffers exist, allocate a new one. /// </summary> internal object Allocate() { #if ENABLE // Check to see whether or not the cache is disabled. if (m_CacheName == null) return m_factory(); #endif // Fast path, get it from our Gen2 aged m_FreeList. object returnBuffer; if (!m_FreeList.TryPop(out returnBuffer)) Restock(out returnBuffer); // Computing free count is expensive enough that we don't want to compute it unless logging is on. if (PinnableBufferCacheEventSource.Log.IsEnabled()) { int numAllocCalls = Interlocked.Increment(ref m_numAllocCalls); if (numAllocCalls >= 1024) { lock (this) { int previousNumAllocCalls = Interlocked.Exchange(ref m_numAllocCalls, 0); if (previousNumAllocCalls >= 1024) { int nonGen2Count = 0; foreach (object o in m_FreeList) { if (GC.GetGeneration(o) < GC.MaxGeneration) { nonGen2Count++; } } PinnableBufferCacheEventSource.Log.WalkFreeListResult(m_CacheName, m_FreeList.Count, nonGen2Count); } } } PinnableBufferCacheEventSource.Log.AllocateBuffer(m_CacheName, PinnableBufferCacheEventSource.AddressOf(returnBuffer), returnBuffer.GetHashCode(), GC.GetGeneration(returnBuffer), m_FreeList.Count); } return returnBuffer; } /// <summary> /// Return a buffer back to the buffer manager. /// </summary> internal void Free(object buffer) { #if ENABLE // Check to see whether or not the cache is disabled. if (m_CacheName == null) return; #endif if (PinnableBufferCacheEventSource.Log.IsEnabled()) PinnableBufferCacheEventSource.Log.FreeBuffer(m_CacheName, PinnableBufferCacheEventSource.AddressOf(buffer), buffer.GetHashCode(), m_FreeList.Count); // After we've done 3 gen1 GCs, assume that all buffers have aged into gen2 on the free path. if ((m_gen1CountAtLastRestock + 3) > GC.CollectionCount(GC.MaxGeneration - 1)) { lock (this) { if (GC.GetGeneration(buffer) < GC.MaxGeneration) { // The buffer is not aged, so put it in the non-aged free list. m_moreThanFreeListNeeded = true; PinnableBufferCacheEventSource.Log.FreeBufferStillTooYoung(m_CacheName, m_NotGen2.Count); m_NotGen2.Add(buffer); m_gen1CountAtLastRestock = GC.CollectionCount(GC.MaxGeneration - 1); return; } } } // If we discovered that it is indeed Gen2, great, put it in the Gen2 list. m_FreeList.Push(buffer); } #region Private /// <summary> /// Called when we don't have any buffers in our free list to give out. /// </summary> /// <returns></returns> private void Restock(out object returnBuffer) { lock (this) { // Try again after getting the lock as another thread could have just filled the free list. If we don't check // then we unnecessarily grab a new set of buffers because we think we are out. if (m_FreeList.TryPop(out returnBuffer)) return; // Lazy init, Ask that TrimFreeListIfNeeded be called on every Gen 2 GC. if (m_restockSize == 0) Gen2GcCallback.Register(Gen2GcCallbackFunc, this); // Indicate to the trimming policy that the free list is insufficent. m_moreThanFreeListNeeded = true; PinnableBufferCacheEventSource.Log.AllocateBufferFreeListEmpty(m_CacheName, m_NotGen2.Count); // Get more buffers if needed. if (m_NotGen2.Count == 0) CreateNewBuffers(); // We have no buffers in the aged freelist, so get one from the newer list. Try to pick the best one. // Debug.Assert(m_NotGen2.Count != 0); int idx = m_NotGen2.Count - 1; if (GC.GetGeneration(m_NotGen2[idx]) < GC.MaxGeneration && GC.GetGeneration(m_NotGen2[0]) == GC.MaxGeneration) idx = 0; returnBuffer = m_NotGen2[idx]; m_NotGen2.RemoveAt(idx); // Remember any sub-optimial buffer so we don't put it on the free list when it gets freed. if (PinnableBufferCacheEventSource.Log.IsEnabled() && GC.GetGeneration(returnBuffer) < GC.MaxGeneration) { PinnableBufferCacheEventSource.Log.AllocateBufferFromNotGen2(m_CacheName, m_NotGen2.Count); } // If we have a Gen1 collection, then everything on m_NotGen2 should have aged. Move them to the m_Free list. if (!AgePendingBuffers()) { // Before we could age at set of buffers, we have handed out half of them. // This implies we should be proactive about allocating more (since we will trim them if we over-allocate). if (m_NotGen2.Count == m_restockSize / 2) { PinnableBufferCacheEventSource.Log.DebugMessage("Proactively adding more buffers to aging pool"); CreateNewBuffers(); } } } } /// <summary> /// See if we can promote the buffers to the free list. Returns true if sucessful. /// </summary> private bool AgePendingBuffers() { if (m_gen1CountAtLastRestock < GC.CollectionCount(GC.MaxGeneration - 1)) { // Allocate a temp list of buffers that are not actually in gen2, and swap it in once // we're done scanning all buffers. int promotedCount = 0; List<object> notInGen2 = new List<object>(); PinnableBufferCacheEventSource.Log.AllocateBufferAged(m_CacheName, m_NotGen2.Count); for (int i = 0; i < m_NotGen2.Count; i++) { // We actually check every object to ensure that we aren't putting non-aged buffers into the free list. object currentBuffer = m_NotGen2[i]; if (GC.GetGeneration(currentBuffer) >= GC.MaxGeneration) { m_FreeList.Push(currentBuffer); promotedCount++; } else { notInGen2.Add(currentBuffer); } } PinnableBufferCacheEventSource.Log.AgePendingBuffersResults(m_CacheName, promotedCount, notInGen2.Count); m_NotGen2 = notInGen2; return true; } return false; } /// <summary> /// Generates some buffers to age into Gen2. /// </summary> private void CreateNewBuffers() { // We choose a very modest number of buffers initially because for the client case. This is often enough. if (m_restockSize == 0) m_restockSize = 4; else if (m_restockSize < DefaultNumberOfBuffers) m_restockSize = DefaultNumberOfBuffers; else if (m_restockSize < 256) m_restockSize = m_restockSize * 2; // Grow quickly at small sizes else if (m_restockSize < 4096) m_restockSize = m_restockSize * 3 / 2; // Less agressively at large ones else m_restockSize = 4096; // Cap how agressive we are // Ensure we hit our minimums if (m_minBufferCount > m_buffersUnderManagement) m_restockSize = Math.Max(m_restockSize, m_minBufferCount - m_buffersUnderManagement); PinnableBufferCacheEventSource.Log.AllocateBufferCreatingNewBuffers(m_CacheName, m_buffersUnderManagement, m_restockSize); for (int i = 0; i < m_restockSize; i++) { // Make a new buffer. object newBuffer = m_factory(); // Create space between the objects. We do this because otherwise it forms a single plug (group of objects) // and the GC pins the entire plug making them NOT move to Gen1 and Gen2. by putting space between them // we ensure that object get a chance to move independently (even if some are pinned). var dummyObject = new object(); m_NotGen2.Add(newBuffer); } m_buffersUnderManagement += m_restockSize; m_gen1CountAtLastRestock = GC.CollectionCount(GC.MaxGeneration - 1); } /// <summary> /// This is the static function that is called from the gen2 GC callback. /// The input object is the cache itself. /// NOTE: The reason that we make this functionstatic and take the cache as a parameter is that /// otherwise, we root the cache to the Gen2GcCallback object, and leak the cache even when /// the application no longer needs it. /// </summary> private static bool Gen2GcCallbackFunc(object targetObj) { return ((PinnableBufferCache)(targetObj)).TrimFreeListIfNeeded(); } /// <summary> /// This is called on every gen2 GC to see if we need to trim the free list. /// NOTE: DO NOT CALL THIS DIRECTLY FROM THE GEN2GCCALLBACK. INSTEAD CALL IT VIA A STATIC FUNCTION (SEE ABOVE). /// If you register a non-static function as a callback, then this object will be leaked. /// </summary> private bool TrimFreeListIfNeeded() { int curMSec = Environment.TickCount; int deltaMSec = curMSec - m_msecNoUseBeyondFreeListSinceThisTime; PinnableBufferCacheEventSource.Log.TrimCheck(m_CacheName, m_buffersUnderManagement, m_moreThanFreeListNeeded, deltaMSec); // If we needed more than just the set of aged buffers since the last time we were called, // we obviously should not be trimming any memory, so do nothing except reset the flag if (m_moreThanFreeListNeeded) { m_moreThanFreeListNeeded = false; m_trimmingExperimentInProgress = false; m_msecNoUseBeyondFreeListSinceThisTime = curMSec; return true; } // We require a minimum amount of clock time to pass (10 seconds) before we trim. Ideally this time // is larger than the typical buffer hold time. if (0 <= deltaMSec && deltaMSec < 10000) return true; // If we got here we have spend the last few second without needing to lengthen the free list. Thus // we have 'enough' buffers, but maybe we have too many. // See if we can trim lock (this) { // Hit a race, try again later. if (m_moreThanFreeListNeeded) { m_moreThanFreeListNeeded = false; m_trimmingExperimentInProgress = false; m_msecNoUseBeyondFreeListSinceThisTime = curMSec; return true; } var freeCount = m_FreeList.Count; // This is expensive to fetch, do it once. // If there is something in m_NotGen2 it was not used for the last few seconds, it is trimable. if (m_NotGen2.Count > 0) { // If we are not performing an experiment and we have stuff that is waiting to go into the // free list but has not made it there, it could be becasue the 'slow path' of restocking // has not happened, so force this (which should flush the list) and start over. if (!m_trimmingExperimentInProgress) { PinnableBufferCacheEventSource.Log.TrimFlush(m_CacheName, m_buffersUnderManagement, freeCount, m_NotGen2.Count); AgePendingBuffers(); m_trimmingExperimentInProgress = true; return true; } PinnableBufferCacheEventSource.Log.TrimFree(m_CacheName, m_buffersUnderManagement, freeCount, m_NotGen2.Count); m_buffersUnderManagement -= m_NotGen2.Count; // Possibly revise the restocking down. We don't want to grow agressively if we are trimming. var newRestockSize = m_buffersUnderManagement / 4; if (newRestockSize < m_restockSize) m_restockSize = Math.Max(newRestockSize, DefaultNumberOfBuffers); m_NotGen2.Clear(); m_trimmingExperimentInProgress = false; return true; } // Set up an experiment where we use 25% less buffers in our free list. We put them in // m_NotGen2, and if they are needed they will be put back in the free list again. var trimSize = freeCount / 4 + 1; // We are OK with a 15% overhead, do nothing in that case. if (freeCount * 15 <= m_buffersUnderManagement || m_buffersUnderManagement - trimSize <= m_minBufferCount) { PinnableBufferCacheEventSource.Log.TrimFreeSizeOK(m_CacheName, m_buffersUnderManagement, freeCount); return true; } // Move buffers from the free list back to the non-aged list. If we don't use them by next time, then we'll consider trimming them. PinnableBufferCacheEventSource.Log.TrimExperiment(m_CacheName, m_buffersUnderManagement, freeCount, trimSize); object buffer; for (int i = 0; i < trimSize; i++) { if (m_FreeList.TryPop(out buffer)) m_NotGen2.Add(buffer); } m_msecNoUseBeyondFreeListSinceThisTime = curMSec; m_trimmingExperimentInProgress = true; } // Indicate that we want to be called back on the next Gen 2 GC. return true; } private const int DefaultNumberOfBuffers = 16; private string m_CacheName; private Func<object> m_factory; /// <summary> /// Contains 'good' buffers to reuse. They are guarenteed to be Gen 2 ENFORCED! /// </summary> private ConcurrentStack<object> m_FreeList = new ConcurrentStack<object>(); /// <summary> /// Contains buffers that are not gen 2 and thus we do not wish to give out unless we have to. /// To implement trimming we sometimes put aged buffers in here as a place to 'park' them /// before true deletion. /// </summary> private List<object> m_NotGen2; /// <summary> /// What whas the gen 1 count the last time re restocked? If it is now greater, then /// we know that all objects are in Gen 2 so we don't have to check. Should be updated /// every time something gets added to the m_NotGen2 list. /// </summary> private int m_gen1CountAtLastRestock; /// <summary> /// Used to ensure we have a minimum time between trimmings. /// </summary> private int m_msecNoUseBeyondFreeListSinceThisTime; /// <summary> /// To trim, we remove things from the free list (which is Gen 2) and see if we 'hit bottom' /// This flag indicates that we hit bottom (we really needed a bigger free list). /// </summary> private bool m_moreThanFreeListNeeded; /// <summary> /// The total number of buffers that this cache has ever allocated. /// Used in trimming heuristics. /// </summary> private int m_buffersUnderManagement; /// <summary> /// The number of buffers we added the last time we restocked. /// </summary> private int m_restockSize; /// <summary> /// Did we put some buffers into m_NotGen2 to see if we can trim? /// </summary> private bool m_trimmingExperimentInProgress; /// <summary> /// A forced minimum number of buffers. /// </summary> private int m_minBufferCount; /// <summary> /// The number of calls to Allocate. /// </summary> private int m_numAllocCalls; #endregion } /// <summary> /// Schedules a callback roughly every gen 2 GC (you may see a Gen 0 an Gen 1 but only once) /// (We can fix this by capturing the Gen 2 count at startup and testing, but I mostly don't care) /// </summary> internal sealed class Gen2GcCallback : CriticalFinalizerObject { public Gen2GcCallback() : base() { } /// <summary> /// Schedule 'callback' to be called in the next GC. If the callback returns true it is /// rescheduled for the next Gen 2 GC. Otherwise the callbacks stop. /// /// NOTE: This callback will be kept alive until either the callback function returns false, /// or the target object dies. /// </summary> public static void Register(Func<object, bool> callback, object targetObj) { // Create a unreachable object that remembers the callback function and target object. Gen2GcCallback gcCallback = new Gen2GcCallback(); gcCallback.Setup(callback, targetObj); } #region Private private Func<object, bool> m_callback; private GCHandle m_weakTargetObj; private void Setup(Func<object, bool> callback, object targetObj) { m_callback = callback; m_weakTargetObj = GCHandle.Alloc(targetObj, GCHandleType.Weak); } ~Gen2GcCallback() { // Check to see if the target object is still alive. object targetObj = m_weakTargetObj.Target; if (targetObj == null) { // The target object is dead, so this callback object is no longer needed. m_weakTargetObj.Free(); return; } // Execute the callback method. try { if (!m_callback(targetObj)) { // If the callback returns false, this callback object is no longer needed. return; } } catch { // Ensure that we still get a chance to resurrect this object, even if the callback throws an exception. } // Resurrect ourselves by re-registering for finalization. if (!Environment.HasShutdownStarted && !AppDomain.CurrentDomain.IsFinalizingForUnload()) { GC.ReRegisterForFinalize(this); } } #endregion } internal sealed class PinnableBufferCacheEventSource { public static readonly PinnableBufferCacheEventSource Log = new PinnableBufferCacheEventSource(); public bool IsEnabled() { return false; } public void DebugMessage(string message) { } public void Create(string cacheName) { } public void AllocateBuffer(string cacheName, ulong objectId, int objectHash, int objectGen, int freeCountAfter) { } public void AllocateBufferFromNotGen2(string cacheName, int notGen2CountAfter) { } public void AllocateBufferCreatingNewBuffers(string cacheName, int totalBuffsBefore, int objectCount) { } public void AllocateBufferAged(string cacheName, int agedCount) { } public void AllocateBufferFreeListEmpty(string cacheName, int notGen2CountBefore) { } public void FreeBuffer(string cacheName, ulong objectId, int objectHash, int freeCountBefore) { } public void FreeBufferStillTooYoung(string cacheName, int notGen2CountBefore) { } public void TrimCheck(string cacheName, int totalBuffs, bool neededMoreThanFreeList, int deltaMSec) { } public void TrimFree(string cacheName, int totalBuffs, int freeListCount, int toBeFreed) { } public void TrimExperiment(string cacheName, int totalBuffs, int freeListCount, int numTrimTrial) { } public void TrimFreeSizeOK(string cacheName, int totalBuffs, int freeListCount) { } public void TrimFlush(string cacheName, int totalBuffs, int freeListCount, int notGen2CountBefore) { } public void AgePendingBuffersResults(string cacheName, int promotedToFreeListCount, int heldBackCount) { } public void WalkFreeListResult(string cacheName, int freeListCount, int gen0BuffersInFreeList) { } static internal ulong AddressOf(object obj) { return 0; } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using QuantConnect.Data; using QuantConnect.Data.Custom; using QuantConnect.Data.Market; using QuantConnect.Indicators; using QuantConnect.Securities.Equity; using QuantConnect.Interfaces; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// This algorithm demonstrates the various ways you can call the History function, /// what it returns, and what you can do with the returned values. /// </summary> /// <meta name="tag" content="using data" /> /// <meta name="tag" content="history and warm up" /> /// <meta name="tag" content="history" /> /// <meta name="tag" content="warm up" /> public class HistoryAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition { private int _count; private SimpleMovingAverage _spyDailySma; /// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> public override void Initialize() { SetStartDate(2013, 10, 08); //Set Start Date SetEndDate(2013, 10, 11); //Set End Date SetCash(100000); //Set Strategy Cash // Find more symbols here: http://quantconnect.com/data var SPY = AddSecurity(SecurityType.Equity, "SPY", Resolution.Daily).Symbol; var CME_SP1 = AddData<QuandlFuture>("CHRIS/CME_SP1", Resolution.Daily).Symbol; // specifying the exchange will allow the history methods that accept a number of bars to return to work properly Securities["CHRIS/CME_SP1"].Exchange = new EquityExchange(); // we can get history in initialize to set up indicators and such _spyDailySma = new SimpleMovingAverage(14); // get the last calendar year's worth of SPY data at the configured resolution (daily) var tradeBarHistory = History<TradeBar>("SPY", TimeSpan.FromDays(365)); AssertHistoryCount("History<TradeBar>(\"SPY\", TimeSpan.FromDays(365))", tradeBarHistory, 250, SPY); // get the last calendar day's worth of SPY data at the specified resolution tradeBarHistory = History<TradeBar>("SPY", TimeSpan.FromDays(1), Resolution.Minute); AssertHistoryCount("History<TradeBar>(\"SPY\", TimeSpan.FromDays(1), Resolution.Minute)", tradeBarHistory, 390, SPY); // get the last 14 bars of SPY at the configured resolution (daily) tradeBarHistory = History<TradeBar>("SPY", 14).ToList(); AssertHistoryCount("History<TradeBar>(\"SPY\", 14)", tradeBarHistory, 14, SPY); // get the last 14 minute bars of SPY tradeBarHistory = History<TradeBar>("SPY", 14, Resolution.Minute); AssertHistoryCount("History<TradeBar>(\"SPY\", 14, Resolution.Minute)", tradeBarHistory, 14, SPY); // we can loop over the return value from these functions and we get TradeBars // we can use these TradeBars to initialize indicators or perform other math foreach (TradeBar tradeBar in tradeBarHistory) { _spyDailySma.Update(tradeBar.EndTime, tradeBar.Close); } // get the last calendar year's worth of quandl data at the configured resolution (daily) var quandlHistory = History<QuandlFuture>("CHRIS/CME_SP1", TimeSpan.FromDays(365)); AssertHistoryCount("History<Quandl>(\"CHRIS/CME_SP1\", TimeSpan.FromDays(365))", quandlHistory, 250, CME_SP1); // get the last 14 bars of SPY at the configured resolution (daily) quandlHistory = History<QuandlFuture>("CHRIS/CME_SP1", 14); AssertHistoryCount("History<Quandl>(\"CHRIS/CME_SP1\", 14)", quandlHistory, 14, CME_SP1); // get the last 14 minute bars of SPY // we can loop over the return values from these functions and we'll get Quandl data // this can be used in much the same way as the tradeBarHistory above _spyDailySma.Reset(); foreach (QuandlFuture quandl in quandlHistory) { _spyDailySma.Update(quandl.EndTime, quandl.Value); } // get the last year's worth of all configured Quandl data at the configured resolution (daily) var allQuandlData = History<QuandlFuture>(TimeSpan.FromDays(365)); AssertHistoryCount("History<QuandlFuture>(TimeSpan.FromDays(365))", allQuandlData, 250, CME_SP1); // get the last 14 bars worth of Quandl data for the specified symbols at the configured resolution (daily) allQuandlData = History<QuandlFuture>(Securities.Keys, 14); AssertHistoryCount("History<QuandlFuture>(Securities.Keys, 14)", allQuandlData, 14, CME_SP1); // NOTE: using different resolutions require that they are properly implemented in your data type, since // Quandl doesn't support minute data, this won't actually work, but if your custom data source has // different resolutions, it would need to be implemented in the GetSource and Reader methods properly //quandlHistory = History<QuandlFuture>("CHRIS/CME_SP1", TimeSpan.FromDays(7), Resolution.Minute); //quandlHistory = History<QuandlFuture>("CHRIS/CME_SP1", 14, Resolution.Minute); //allQuandlData = History<QuandlFuture>(TimeSpan.FromDays(365), Resolution.Minute); //allQuandlData = History<QuandlFuture>(Securities.Keys, 14, Resolution.Minute); //allQuandlData = History<QuandlFuture>(Securities.Keys, TimeSpan.FromDays(1), Resolution.Minute); //allQuandlData = History<QuandlFuture>(Securities.Keys, 14, Resolution.Minute); // get the last calendar year's worth of all quandl data allQuandlData = History<QuandlFuture>(Securities.Keys, TimeSpan.FromDays(365)); AssertHistoryCount("History<QuandlFuture>(Securities.Keys, TimeSpan.FromDays(365))", allQuandlData, 250, CME_SP1); // the return is a series of dictionaries containing all quandl data at each time // we can loop over it to get the individual dictionaries foreach (DataDictionary<QuandlFuture> quandlsDataDictionary in allQuandlData) { // we can access the dictionary to get the quandl data we want var quandl = quandlsDataDictionary["CHRIS/CME_SP1"]; } // we can also access the return value from the multiple symbol functions to request a single // symbol and then loop over it var singleSymbolQuandl = allQuandlData.Get("CHRIS/CME_SP1"); AssertHistoryCount("allQuandlData.Get(\"CHRIS/CME_SP1\")", singleSymbolQuandl, 250, CME_SP1); foreach (QuandlFuture quandl in singleSymbolQuandl) { // do something with 'CHRIS/CME_SP1' quandl data } // we can also access individual properties on our data, this will // get the 'CHRIS/CME_SP1' quandls like above, but then only return the Low properties var quandlSpyLows = allQuandlData.Get("CHRIS/CME_SP1", "Low"); AssertHistoryCount("allQuandlData.Get(\"CHRIS/CME_SP1\", \"Low\")", quandlSpyLows, 250); foreach (decimal low in quandlSpyLows) { // do something with each low value } // sometimes it's necessary to get the history for many configured symbols // request the last year's worth of history for all configured symbols at their configured resolutions var allHistory = History(TimeSpan.FromDays(365)); AssertHistoryCount("History(TimeSpan.FromDays(365))", allHistory, 250, SPY, CME_SP1); // request the last days's worth of history at the minute resolution allHistory = History(TimeSpan.FromDays(1), Resolution.Minute); AssertHistoryCount("History(TimeSpan.FromDays(1), Resolution.Minute)", allHistory, 391, SPY, CME_SP1); // request the last 100 bars for the specified securities at the configured resolution allHistory = History(Securities.Keys, 100); AssertHistoryCount("History(Securities.Keys, 100)", allHistory, 100, SPY, CME_SP1); // request the last 100 minute bars for the specified securities allHistory = History(Securities.Keys, 100, Resolution.Minute); AssertHistoryCount("History(Securities.Keys, 100, Resolution.Minute)", allHistory, 101, SPY, CME_SP1); // request the last calendar years worth of history for the specified securities allHistory = History(Securities.Keys, TimeSpan.FromDays(365)); AssertHistoryCount("History(Securities.Keys, TimeSpan.FromDays(365))", allHistory, 250, SPY, CME_SP1); // we can also specify the resolution allHistory = History(Securities.Keys, TimeSpan.FromDays(1), Resolution.Minute); AssertHistoryCount("History(Securities.Keys, TimeSpan.FromDays(1), Resolution.Minute)", allHistory, 391, SPY, CME_SP1); // if we loop over this allHistory, we get Slice objects foreach (Slice slice in allHistory) { // do something with each slice, these will come in time order // and will NOT have auxilliary data, just price data and your custom data // if those symbols were specified } // we can access the history for individual symbols from the all history by specifying the symbol // the type must be a trade bar! tradeBarHistory = allHistory.Get<TradeBar>("SPY"); AssertHistoryCount("allHistory.Get(\"SPY\")", tradeBarHistory, 390, SPY); // we can access all the closing prices in chronological order using this get function var closeHistory = allHistory.Get("SPY", Field.Close); AssertHistoryCount("allHistory.Get(\"SPY\", Field.Close)", closeHistory, 390); foreach (decimal close in closeHistory) { // do something with each closing value in order } // we can convert the close history into your normal double array (double[]) using the ToDoubleArray method double[] doubleArray = closeHistory.ToDoubleArray(); // for the purposes of regression testing, we're explicitly requesting history // using the universe symbols. Requests for universe symbols are filtered out // and never sent to the history provider. var universeSecurityHistory = History(UniverseManager.Keys, TimeSpan.FromDays(10)).ToList(); if (universeSecurityHistory.Count != 0) { throw new Exception("History request for universe symbols incorrectly returned data. " + "These requests are intended to be filtered out and never sent to the history provider."); } } /// <summary> /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. /// </summary> /// <param name="data">Slice object keyed by symbol containing the stock data</param> public override void OnData(Slice data) { _count++; if (_count > 5) { throw new Exception("Invalid number of bars arrived. Expected exactly 5"); } if (!Portfolio.Invested) { SetHoldings("SPY", 1); Debug("Purchased Stock"); } } private void AssertHistoryCount<T>(string methodCall, IEnumerable<T> history, int expected, params Symbol[] expectedSymbols) { history = history.ToList(); var count = history.Count(); if (count != expected) { throw new Exception(methodCall + " expected " + expected + ", but received " + count); } IEnumerable<Symbol> unexpectedSymbols = null; if (typeof(T) == typeof(Slice)) { var slices = (IEnumerable<Slice>) history; unexpectedSymbols = slices.SelectMany(slice => slice.Keys) .Distinct() .Where(sym => !expectedSymbols.Contains(sym)) .ToList(); } else if (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(DataDictionary<>)) { if (typeof(T).GetGenericArguments()[0] == typeof(QuandlFuture)) { var dictionaries = (IEnumerable<DataDictionary<QuandlFuture>>) history; unexpectedSymbols = dictionaries.SelectMany(dd => dd.Keys) .Distinct() .Where(sym => !expectedSymbols.Contains(sym)) .ToList(); } } else if (typeof(IBaseData).IsAssignableFrom(typeof(T))) { var slices = (IEnumerable<IBaseData>)history; unexpectedSymbols = slices.Select(data => data.Symbol) .Distinct() .Where(sym => !expectedSymbols.Contains(sym)) .ToList(); } else if (typeof(T) == typeof(decimal)) { // if the enumerable doesn't contain symbols then we can't assert that certain symbols exist // this case is used when testing data dictionary extensions that select a property value, // such as dataDictionaries.Get("MySymbol", "MyProperty") => IEnumerable<decimal> return; } if (unexpectedSymbols == null) { throw new Exception("Unhandled case: " + typeof(T).GetBetterTypeName()); } var unexpectedSymbolsString = string.Join(" | ", unexpectedSymbols); if (!string.IsNullOrWhiteSpace(unexpectedSymbolsString)) { throw new Exception($"{methodCall} contains unexpected symbols: {unexpectedSymbolsString}"); } } /// <summary> /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm. /// </summary> public bool CanRunLocally { get; } = true; /// <summary> /// This is used by the regression test system to indicate which languages this algorithm is written in. /// </summary> public Language[] Languages { get; } = { Language.CSharp, Language.Python }; /// <summary> /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm /// </summary> public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string> { {"Total Trades", "1"}, {"Average Win", "0%"}, {"Average Loss", "0%"}, {"Compounding Annual Return", "359.952%"}, {"Drawdown", "1.100%"}, {"Expectancy", "0"}, {"Net Profit", "1.686%"}, {"Sharpe Ratio", "4.502"}, {"Loss Rate", "0%"}, {"Win Rate", "0%"}, {"Profit-Loss Ratio", "0"}, {"Alpha", "0"}, {"Beta", "77.786"}, {"Annual Standard Deviation", "0.191"}, {"Annual Variance", "0.036"}, {"Information Ratio", "4.445"}, {"Tracking Error", "0.191"}, {"Treynor Ratio", "0.011"}, {"Total Fees", "$3.26"} }; /// <summary> /// Custom quandl data type for setting customized value column name. Value column is used for the primary trading calculations and charting. /// </summary> public class QuandlFuture : Quandl { /// <summary> /// Initializes a new instance of the <see cref="QuandlFuture"/> class. /// </summary> public QuandlFuture() : base(valueColumnName: "Settle") { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Data.Common; using System.IO; using System.Text; using Xunit; namespace System.Data.SqlClient.ManualTesting.Tests { public static class ReaderTest { [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void TestMain() { string connectionString = DataTestUtility.TcpConnStr; string tempTable = DataTestUtility.GetUniqueName("T", "[", "]"); string tempKey = DataTestUtility.GetUniqueName("K", "[", "]"); DbProviderFactory provider = SqlClientFactory.Instance; try { using (DbConnection con = provider.CreateConnection()) { con.ConnectionString = connectionString; con.Open(); using (DbCommand cmd = provider.CreateCommand()) { cmd.Connection = con; DbTransaction tx; #region <<Create temp table>> cmd.CommandText = "SELECT LastName, FirstName, Title, Address, City, Region, PostalCode, Country into " + tempTable + " from Employees where EmployeeID=0"; cmd.ExecuteNonQuery(); #endregion tx = con.BeginTransaction(); cmd.Transaction = tx; cmd.CommandText = "insert into " + tempTable + "(LastName, FirstName, Title, Address, City, Region, PostalCode, Country) values ('Doe', 'Jane' , 'Ms.', 'One Microsoft Way', 'Redmond', 'WA', '98052', 'USA')"; cmd.ExecuteNonQuery(); cmd.CommandText = "insert into " + tempTable + "(LastName, FirstName, Title, Address, City, Region, PostalCode, Country) values ('Doe', 'John' , 'Mr.', NULL, NULL, NULL, NULL, NULL)"; cmd.ExecuteNonQuery(); tx.Commit(); cmd.Transaction = null; string parameterName = "@p1"; DbParameter p1 = cmd.CreateParameter(); p1.ParameterName = parameterName; p1.Value = "Doe"; cmd.Parameters.Add(p1); cmd.CommandText = "select * from " + tempTable + " where LastName = " + parameterName; // Test GetValue + IsDBNull using (DbDataReader rdr = cmd.ExecuteReader()) { StringBuilder actualResult = new StringBuilder(); int currentValue = 0; string[] expectedValues = { "Doe,Jane,Ms.,One Microsoft Way,Redmond,WA,98052,USA", "Doe,John,Mr.,(NULL),(NULL),(NULL),(NULL),(NULL)" }; while (rdr.Read()) { Assert.True(currentValue < expectedValues.Length, "ERROR: Received more values than expected"); for (int i = 0; i < rdr.FieldCount; i++) { if (i > 0) { actualResult.Append(","); } if (rdr.IsDBNull(i)) { actualResult.Append("(NULL)"); } else { actualResult.Append(rdr.GetValue(i)); } } DataTestUtility.AssertEqualsWithDescription(expectedValues[currentValue++], actualResult.ToString(), "FAILED: Did not receive expected data"); actualResult.Clear(); } } // Test GetFieldValue<T> + IsDBNull using (DbDataReader rdr = cmd.ExecuteReader()) { StringBuilder actualResult = new StringBuilder(); int currentValue = 0; string[] expectedValues = { "Doe,Jane,Ms.,One Microsoft Way,Redmond,WA,98052,USA", "Doe,John,Mr.,(NULL),(NULL),(NULL),(NULL),(NULL)" }; while (rdr.Read()) { Assert.True(currentValue < expectedValues.Length, "ERROR: Received more values than expected"); for (int i = 0; i < rdr.FieldCount; i++) { if (i > 0) { actualResult.Append(","); } if (rdr.IsDBNull(i)) { actualResult.Append("(NULL)"); } else { if (rdr.GetFieldType(i) == typeof(bool)) { actualResult.Append(rdr.GetFieldValue<bool>(i)); } else if (rdr.GetFieldType(i) == typeof(decimal)) { actualResult.Append(rdr.GetFieldValue<decimal>(i)); } else if (rdr.GetFieldType(i) == typeof(int)) { actualResult.Append(rdr.GetFieldValue<int>(i)); } else { actualResult.Append(rdr.GetFieldValue<string>(i)); } } } DataTestUtility.AssertEqualsWithDescription(expectedValues[currentValue++], actualResult.ToString(), "FAILED: Did not receive expected data"); actualResult.Clear(); } } // Test GetFieldValueAsync<T> + IsDBNullAsync using (DbDataReader rdr = cmd.ExecuteReaderAsync().Result) { StringBuilder actualResult = new StringBuilder(); int currentValue = 0; string[] expectedValues = { "Doe,Jane,Ms.,One Microsoft Way,Redmond,WA,98052,USA", "Doe,John,Mr.,(NULL),(NULL),(NULL),(NULL),(NULL)" }; while (rdr.ReadAsync().Result) { Assert.True(currentValue < expectedValues.Length, "ERROR: Received more values than expected"); for (int i = 0; i < rdr.FieldCount; i++) { if (i > 0) { actualResult.Append(","); } if (rdr.IsDBNullAsync(i).Result) { actualResult.Append("(NULL)"); } else { if (rdr.GetFieldType(i) == typeof(bool)) { actualResult.Append(rdr.GetFieldValueAsync<bool>(i).Result); } else if (rdr.GetFieldType(i) == typeof(decimal)) { actualResult.Append(rdr.GetFieldValueAsync<decimal>(i).Result); } else if (rdr.GetFieldType(i) == typeof(int)) { actualResult.Append(rdr.GetFieldValue<int>(i)); } else { actualResult.Append(rdr.GetFieldValueAsync<string>(i).Result); } } } DataTestUtility.AssertEqualsWithDescription(expectedValues[currentValue++], actualResult.ToString(), "FAILED: Did not receive expected data"); actualResult.Clear(); } } } // GetStream byte[] correctBytes = { 0x12, 0x34, 0x56, 0x78 }; string queryString; string correctBytesAsString = "0x12345678"; queryString = string.Format("SELECT CAST({0} AS BINARY(20)), CAST({0} AS IMAGE), CAST({0} AS VARBINARY(20))", correctBytesAsString); using (var command = provider.CreateCommand()) { command.CommandText = queryString; command.Connection = con; using (var reader = command.ExecuteReader()) { reader.Read(); for (int i = 0; i < reader.FieldCount; i++) { byte[] buffer = new byte[256]; Stream stream = reader.GetStream(i); int bytesRead = stream.Read(buffer, 0, buffer.Length); for (int j = 0; j < correctBytes.Length; j++) { Assert.True(correctBytes[j] == buffer[j], "ERROR: Bytes do not match"); } } } } // GetTextReader string[] correctStrings = { "Hello World", "\uFF8A\uFF9B\uFF70\uFF9C\uFF70\uFF99\uFF84\uFF9E" }; string[] collations = { "Latin1_General_CI_AS", "Japanese_CI_AS" }; for (int j = 0; j < collations.Length; j++) { string substring = string.Format("(N'{0}' COLLATE {1})", correctStrings[j], collations[j]); queryString = string.Format("SELECT CAST({0} AS CHAR(20)), CAST({0} AS NCHAR(20)), CAST({0} AS NTEXT), CAST({0} AS NVARCHAR(20)), CAST({0} AS TEXT), CAST({0} AS VARCHAR(20))", substring); using (var command = provider.CreateCommand()) { command.CommandText = queryString; command.Connection = con; using (var reader = command.ExecuteReader()) { reader.Read(); for (int i = 0; i < reader.FieldCount; i++) { char[] buffer = new char[256]; TextReader textReader = reader.GetTextReader(i); int charsRead = textReader.Read(buffer, 0, buffer.Length); string stringRead = new string(buffer, 0, charsRead); Assert.True(stringRead == (string)reader.GetValue(i), "ERROR: Strings to not match"); } } } } } } finally { using (DbConnection con = provider.CreateConnection()) { con.ConnectionString = connectionString; con.Open(); using (DbCommand cmd = provider.CreateCommand()) { cmd.Connection = con; cmd.CommandText = "drop table " + tempTable; cmd.ExecuteNonQuery(); } } } } } }
// Copyright (c) MarinAtanasov. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the project root for license information. using AppBrix.Logging.Contracts; using AppBrix.Logging.Events; using AppBrix.Tests; using FluentAssertions; using System; using Xunit; namespace AppBrix.Logging.Tests.LogHub; public sealed class LogHubTests : TestsBase { #region Setup and cleanup public LogHubTests() : base(TestUtils.CreateTestApp<LoggingModule>()) => this.app.Start(); #endregion #region Tests [Fact, Trait(TestCategories.Category, TestCategories.Functional)] public void TestUnsubscribedTrace() { Action<ILogEntry> handler = _ => throw new InvalidOperationException("handler should have been unsubscribed"); var hub = this.app.GetLogHub(); hub.Subscribe(handler); hub.Unsubscribe(handler); hub.Trace(string.Empty); } [Fact, Trait(TestCategories.Category, TestCategories.Functional)] public void TestErrorLog() { var message = "Test message"; var error = new ArgumentException("Test exception"); var called = false; this.app.GetEventHub().Subscribe<ILogEntry>(x => { called = true; x.Message.Should().Be(message, "the error message same as the passed in error"); x.Exception.Should().Be(error, "the error message same as the passed in error"); x.Level.Should().Be(LogLevel.Error, "log level should be Error"); var stringed = x.ToString(); stringed.Should().Contain(x.Exception.Message, "ToString should include the exception"); stringed.Should().Contain(x.Message, "ToString should include the message"); stringed.Should().Contain(x.Level.ToString(), "ToString should include the level"); }); this.app.GetLogHub().Error(message, error); called.Should().BeTrue("the event should have been called"); } [Fact, Trait(TestCategories.Category, TestCategories.Functional)] public void TestDebugLog() { var message = "Test message"; var error = new ArgumentException("Test exception"); var called = false; this.app.GetEventHub().Subscribe<ILogEntry>(x => { called = true; x.Message.Should().Be(message, "the debug message is different than the passed in message"); x.Exception.Should().Be(error, "the error message same as the passed in error"); x.Level.Should().Be(LogLevel.Debug, "log level should be Debug"); x.GetHashCode().Should().Be(x.Message.GetHashCode(), "hash code should be the same as the message's hash code"); var stringed = x.ToString(); stringed.Should().Contain(x.Exception.Message, "ToString should include the exception"); stringed.Should().Contain(x.Message, "ToString should include the message"); stringed.Should().Contain(x.Level.ToString(), "ToString should include the level"); }); this.app.GetLogHub().Debug(message, error); called.Should().BeTrue("the event should have been called"); } [Fact, Trait(TestCategories.Category, TestCategories.Functional)] public void TestInfoLog() { var message = "Test message"; var called = false; this.app.GetEventHub().Subscribe<ILogEntry>(x => { called = true; x.Message.Should().Be(message, "the info message is different than the passed in message"); x.Level.Should().Be(LogLevel.Info, "log level should be Info"); x.GetHashCode().Should().Be(x.Message.GetHashCode(), "hash code should be the same as the message's hash code"); var stringed = x.ToString(); stringed.Should().Contain(x.Message, "ToString should include the message"); stringed.Should().Contain(x.Level.ToString(), "ToString should include the level"); }); this.app.GetLogHub().Info(message); called.Should().BeTrue("the event should have been called"); } [Fact, Trait(TestCategories.Category, TestCategories.Functional)] public void TestWarningLog() { var message = "Test message"; var error = new ArgumentException("Test exception"); var called = false; this.app.GetEventHub().Subscribe<ILogEntry>(x => { called = true; x.Message.Should().Be(message, "the warning message is different than the passed in message"); x.Exception.Should().Be(error, "the error message same as the passed in error"); x.Level.Should().Be(LogLevel.Warning, "log level should be Warning"); x.GetHashCode().Should().Be(x.Message.GetHashCode(), "hash code should be the same as the message's hash code"); var stringed = x.ToString(); stringed.Should().Contain(x.Exception.Message, "ToString should include the exception"); stringed.Should().Contain(x.Message, "ToString should include the message"); stringed.Should().Contain(x.Level.ToString(), "ToString should include the level"); }); this.app.GetLogHub().Warning(message, error); called.Should().BeTrue("the event should have been called"); } [Fact, Trait(TestCategories.Category, TestCategories.Functional)] public void TestTraceLog() { var message = "Test message"; var called = false; this.app.GetEventHub().Subscribe<ILogEntry>(x => { called = true; x.Message.Should().Be(message, "the trace message is different than the passed in message"); x.Level.Should().Be(LogLevel.Trace, "log level should be Trace"); x.GetHashCode().Should().Be(x.Message.GetHashCode(), "hash code should be the same as the message's hash code"); var stringed = x.ToString(); stringed.Should().Contain(x.Message, "ToString should include the message"); stringed.Should().Contain(x.Level.ToString(), "ToString should include the level"); }); this.app.GetLogHub().Trace(message); called.Should().BeTrue("the event should have been called"); } [Fact, Trait(TestCategories.Category, TestCategories.Functional)] public void TestDisabledLogging() { var message = "Test message"; var called = false; this.app.ConfigService.GetLoggingConfig().LogLevel = LogLevel.None; this.app.GetEventHub().Subscribe<ILogEntry>(_ => { called = true; }); this.app.GetLogHub().Trace(message); this.app.GetLogHub().Debug(message); this.app.GetLogHub().Info(message); this.app.GetLogHub().Warning(message); this.app.GetLogHub().Error(message); this.app.GetLogHub().Critical(message); called.Should().BeFalse("the event should not have been called"); } [Fact, Trait(TestCategories.Category, TestCategories.Functional)] public void TestCallerFile() { var message = "Test message"; this.app.GetEventHub().Subscribe<ILogEntry>(x => x.CallerFile.Should().EndWith(typeof(LogHubTests).Name + ".cs", "caller file should be set to current file")); this.app.GetLogHub().Warning(message); } [Fact, Trait(TestCategories.Category, TestCategories.Functional)] public void TestCallerMemberName() { var message = "Test message"; this.app.GetEventHub().Subscribe<ILogEntry>(x => x.CallerMember.Should().Be("TestCallerMemberName", "member name should be the current function")); this.app.GetLogHub().Error(message); } [Fact, Trait(TestCategories.Category, TestCategories.Functional)] public void TestThreadId() { var message = "Test message"; this.app.GetEventHub().Subscribe<ILogEntry>(x => x.ThreadId.Should().Be(Environment.CurrentManagedThreadId, "thread id should be current thread id")); this.app.GetLogHub().Info(message); } [Fact, Trait(TestCategories.Category, TestCategories.Functional)] public void TestTimeLogEntry() { var message = "Test message"; var before = this.app.GetTime(); DateTime executed = DateTime.MinValue; this.app.GetEventHub().Subscribe<ILogEntry>(x => executed = x.Created); this.app.GetLogHub().Debug(message); executed.Should().BeOnOrAfter(before, "created date time should be greater than the time before creation"); executed.Should().BeOnOrBefore(this.app.GetTime(), "created date time should be greater than the time after creation"); } [Fact, Trait(TestCategories.Category, TestCategories.Performance)] public void TestPerformanceLogging() { this.app.GetEventHub().Subscribe<ILogEntry>(_ => { }); TestUtils.TestPerformance(this.TestPerformanceLoggingInternal); } #endregion #region Private methods private void TestPerformanceLoggingInternal() { var message = "Test message"; var error = new ArgumentException("Test error"); var called = 0; var repeat = 8000; void handler(ILogEntry x) { called++; } this.app.GetEventHub().Subscribe((Action<ILogEntry>)handler); var logHub = this.app.GetLogHub(); for (var i = 0; i < repeat; i++) { logHub.Critical(message, error); logHub.Error(message, error); logHub.Debug(message); logHub.Info(message); logHub.Trace(message); logHub.Warning(message, error); } called.Should().Be(repeat * 6, "the event should have been called"); this.app.Reinitialize(); } #endregion }
// **************************************************************** // This is free software licensed under the NUnit license. You // may obtain a copy of the license as well as information regarding // copyright ownership at http://nunit.org/?p=license&r=2.4. // **************************************************************** using System; using System.Collections; using System.Xml; using System.Xml.Schema; using System.IO; using System.Threading; using NUnit.Core; namespace NUnit.Util { /// <summary> /// Types of changes that may occur to a config /// </summary> public enum ProjectChangeType { ActiveConfig, AddConfig, RemoveConfig, UpdateConfig, Other } /// <summary> /// Arguments for a project event /// </summary> public class ProjectEventArgs : EventArgs { public ProjectChangeType type; public string configName; public ProjectEventArgs( ProjectChangeType type, string configName ) { this.type = type; this.configName = configName; } } /// <summary> /// Delegate to be used to handle project events /// </summary> public delegate void ProjectEventHandler( object sender, ProjectEventArgs e ); /// <summary> /// Class that represents an NUnit test project /// </summary> public class NUnitProject { #region Static and instance variables /// <summary> /// Used to generate default names for projects /// </summary> private static int projectSeed = 0; /// <summary> /// The extension used for test projects /// </summary> private static readonly string nunitExtension = ".nunit"; /// <summary> /// Path to the file storing this project /// </summary> private string projectPath; /// <summary> /// Application Base for the project. Since this /// can be null, always fetch from the property /// rather than using the field directly. /// </summary> private string basePath; /// <summary> /// Whether the project is dirty /// </summary> private bool isDirty = false; /// <summary> /// Collection of configs for the project /// </summary> private ProjectConfigCollection configs; /// <summary> /// The currently active configuration /// </summary> private ProjectConfig activeConfig; /// <summary> /// Flag indicating that this project is a /// temporary wrapper for an assembly. /// </summary> private bool isAssemblyWrapper = false; #endregion #region Constructor public NUnitProject( string projectPath ) { this.projectPath = Path.GetFullPath( projectPath ); configs = new ProjectConfigCollection( this ); } #endregion #region Static Methods // True if it's one of our project types public static bool IsProjectFile( string path ) { return Path.GetExtension( path ) == nunitExtension; } // True if it's ours or one we can load public static bool CanLoadAsProject( string path ) { return IsProjectFile( path ) || VSProject.IsProjectFile( path ) || VSProject.IsSolutionFile( path ); } public static string GenerateProjectName() { return string.Format( "Project{0}", ++projectSeed ); } public static NUnitProject EmptyProject() { return new NUnitProject( GenerateProjectName() ); } public static NUnitProject NewProject() { NUnitProject project = EmptyProject(); project.Configs.Add( "Debug" ); project.Configs.Add( "Release" ); project.IsDirty = false; return project; } /// <summary> /// Return a test project by either loading it from /// the supplied path, creating one from a VS file /// or wrapping an assembly. /// </summary> public static NUnitProject LoadProject( string path ) { if ( NUnitProject.IsProjectFile( path ) ) { NUnitProject project = new NUnitProject( path ); project.Load(); return project; } else if ( VSProject.IsProjectFile( path ) ) return NUnitProject.FromVSProject( path ); else if ( VSProject.IsSolutionFile( path ) ) return NUnitProject.FromVSSolution( path ); else return NUnitProject.FromAssembly( path ); } /// <summary> /// Creates a project to wrap a list of assemblies /// </summary> public static NUnitProject FromAssemblies( string[] assemblies ) { // if only one assembly is passed in then the configuration file // should follow the name of the assembly. This will only happen // if the LoadAssembly method is called. Currently the console ui // does not differentiate between having one or multiple assemblies // passed in. if ( assemblies.Length == 1) return NUnitProject.FromAssembly(assemblies[0]); NUnitProject project = NUnitProject.EmptyProject(); ProjectConfig config = new ProjectConfig( "Default" ); foreach( string assembly in assemblies ) { string fullPath = Path.GetFullPath( assembly ); if ( !File.Exists( fullPath ) ) throw new FileNotFoundException( string.Format( "Assembly not found: {0}", fullPath ) ); config.Assemblies.Add( fullPath ); } project.Configs.Add( config ); // TODO: Deduce application base, and provide a // better value for loadpath and project path // analagous to how new projects are handled string basePath = Path.GetDirectoryName( Path.GetFullPath( assemblies[0] ) ); project.projectPath = Path.Combine( basePath, project.Name + ".nunit" ); project.IsDirty = true; return project; } /// <summary> /// Creates a project to wrap an assembly /// </summary> public static NUnitProject FromAssembly( string assemblyPath ) { if ( !File.Exists( assemblyPath ) ) throw new FileNotFoundException( string.Format( "Assembly not found: {0}", assemblyPath ) ); string fullPath = Path.GetFullPath( assemblyPath ); NUnitProject project = new NUnitProject( fullPath ); ProjectConfig config = new ProjectConfig( "Default" ); config.Assemblies.Add( fullPath ); project.Configs.Add( config ); project.isAssemblyWrapper = true; project.IsDirty = false; return project; } public static NUnitProject FromVSProject( string vsProjectPath ) { NUnitProject project = new NUnitProject( Path.GetFullPath( vsProjectPath ) ); VSProject vsProject = new VSProject( vsProjectPath ); project.Add( vsProject ); project.isDirty = false; return project; } public static NUnitProject FromVSSolution( string solutionPath ) { NUnitProject project = new NUnitProject( Path.GetFullPath( solutionPath ) ); string solutionDirectory = Path.GetDirectoryName( solutionPath ); using(StreamReader reader = new StreamReader( solutionPath )) { char[] delims = { '=', ',' }; char[] trimchars = { ' ', '"' }; string line = reader.ReadLine(); while ( line != null ) { if ( line.StartsWith( "Project" ) ) { string[] parts = line.Split( delims ); string vsProjectPath = parts[2].Trim(trimchars); if ( VSProject.IsProjectFile( vsProjectPath ) ) project.Add( new VSProject( Path.Combine( solutionDirectory, vsProjectPath ) ) ); } line = reader.ReadLine(); } } project.isDirty = false; return project; } /// <summary> /// Figure out the proper name to be used when saving a file. /// </summary> public static string ProjectPathFromFile( string path ) { string fileName = Path.GetFileNameWithoutExtension( path ) + nunitExtension; return Path.Combine( Path.GetDirectoryName( path ), fileName ); } #endregion #region Properties and Events public static int ProjectSeed { get { return projectSeed; } set { projectSeed = value; } } /// <summary> /// The path to which a project will be saved. /// </summary> public string ProjectPath { get { return projectPath; } set { projectPath = Path.GetFullPath( value ); isDirty = true; } } public string DefaultBasePath { get { return Path.GetDirectoryName( projectPath ); } } /// <summary> /// The base path for the project. Constructor sets /// it to the directory part of the project path. /// </summary> public string BasePath { get { if ( basePath == null || basePath == string.Empty ) return DefaultBasePath; return basePath; } set { basePath = value; if ( basePath != null && basePath != string.Empty && !Path.IsPathRooted( basePath ) ) { basePath = Path.Combine( DefaultBasePath, basePath ); } basePath = PathUtils.Canonicalize( basePath ); } } /// <summary> /// The name of the project. /// </summary> public string Name { get { return Path.GetFileNameWithoutExtension( projectPath ); } } public ProjectConfig ActiveConfig { get { // In case the previous active config was removed if ( activeConfig != null && !configs.Contains( activeConfig ) ) activeConfig = null; // In case no active config is set or it was removed if ( activeConfig == null && configs.Count > 0 ) activeConfig = configs[0]; return activeConfig; } } // Safe access to name of the active config public string ActiveConfigName { get { ProjectConfig config = ActiveConfig; return config == null ? null : config.Name; } } public bool IsLoadable { get { return ActiveConfig != null && ActiveConfig.Assemblies.Count > 0; } } // A project made from a single assembly is treated // as a transparent wrapper for some purposes until // a change is made to it. public bool IsAssemblyWrapper { get { return isAssemblyWrapper; } } public string ConfigurationFile { get { // TODO: Check this return isAssemblyWrapper ? Path.GetFileName( projectPath ) + ".config" : Path.GetFileNameWithoutExtension( projectPath ) + ".config"; } } public bool IsDirty { get { return isDirty; } set { isDirty = value; } } public ProjectConfigCollection Configs { get { return configs; } } public event ProjectEventHandler Changed; #endregion #region Instance Methods public void SetActiveConfig( int index ) { activeConfig = configs[index]; OnProjectChange( ProjectChangeType.ActiveConfig, activeConfig.Name ); } public void SetActiveConfig( string name ) { foreach( ProjectConfig config in configs ) { if ( config.Name == name ) { activeConfig = config; OnProjectChange( ProjectChangeType.ActiveConfig, activeConfig.Name ); break; } } } // public int IndexOf( string name ) // { // for( int index = 0; index < configs.Count; index++ ) // if( configs[index].Name == name ) // return index; // // return -1; // } public void OnProjectChange( ProjectChangeType type, string configName ) { isDirty = true; if ( isAssemblyWrapper ) { projectPath = Path.ChangeExtension( projectPath, ".nunit" ); isAssemblyWrapper = false; } if ( Changed != null ) Changed( this, new ProjectEventArgs( type, configName ) ); if ( type == ProjectChangeType.RemoveConfig ) { if ( activeConfig == null || activeConfig.Name == configName ) { if ( configs.Count > 0 ) SetActiveConfig( 0 ); } } } public void Add( VSProject vsProject ) { foreach( VSProjectConfig vsConfig in vsProject.Configs ) { string name = vsConfig.Name; if ( !configs.Contains( name ) ) configs.Add( name ); ProjectConfig config = this.Configs[name]; foreach ( string assembly in vsConfig.Assemblies ) config.Assemblies.Add( assembly ); } } public void Load() { XmlTextReader reader = new XmlTextReader( projectPath ); string activeConfigName = null; ProjectConfig currentConfig = null; try { reader.MoveToContent(); if ( reader.NodeType != XmlNodeType.Element || reader.Name != "NUnitProject" ) throw new ProjectFormatException( "Invalid project format: <NUnitProject> expected.", reader.LineNumber, reader.LinePosition ); while( reader.Read() ) if ( reader.NodeType == XmlNodeType.Element ) switch( reader.Name ) { case "Settings": if ( reader.NodeType == XmlNodeType.Element ) { activeConfigName = reader.GetAttribute( "activeconfig" ); if (activeConfigName == "NUnitAutoConfig") { #if DEBUG if (Environment.Version.Major == 2) activeConfigName = "Debug2005"; else activeConfigName = "Debug"; #else if (Environment.Version.Major == 2) activeConfigName = "Release2005"; else activeConfigName = "Release"; #endif } string appbase = reader.GetAttribute( "appbase" ); if ( appbase != null ) this.BasePath = appbase; } break; case "Config": if ( reader.NodeType == XmlNodeType.Element ) { string configName = reader.GetAttribute( "name" ); currentConfig = new ProjectConfig( configName ); currentConfig.BasePath = reader.GetAttribute( "appbase" ); currentConfig.ConfigurationFile = reader.GetAttribute( "configfile" ); string binpath = reader.GetAttribute( "binpath" ); currentConfig.PrivateBinPath = binpath; string type = reader.GetAttribute( "binpathtype" ); if ( type == null ) if ( binpath == null ) currentConfig.BinPathType = BinPathType.Auto; else currentConfig.BinPathType = BinPathType.Manual; else currentConfig.BinPathType = (BinPathType)Enum.Parse( typeof( BinPathType ), type, true ); Configs.Add( currentConfig ); if ( configName == activeConfigName ) activeConfig = currentConfig; } else if ( reader.NodeType == XmlNodeType.EndElement ) currentConfig = null; break; case "assembly": if ( reader.NodeType == XmlNodeType.Element && currentConfig != null ) { string path = reader.GetAttribute( "path" ); currentConfig.Assemblies.Add( Path.Combine( currentConfig.BasePath, path ) ); } break; default: break; } this.IsDirty = false; } catch( FileNotFoundException ) { throw; } catch( XmlException e ) { throw new ProjectFormatException( string.Format( "Invalid project format: {0}", e.Message ), e.LineNumber, e.LinePosition ); } catch( Exception e ) { throw new ProjectFormatException( string.Format( "Invalid project format: {0} Line {1}, Position {2}", e.Message, reader.LineNumber, reader.LinePosition ), reader.LineNumber, reader.LinePosition ); } finally { reader.Close(); } } public void Save() { projectPath = ProjectPathFromFile( projectPath ); XmlTextWriter writer = new XmlTextWriter( projectPath, System.Text.Encoding.UTF8 ); writer.Formatting = Formatting.Indented; writer.WriteStartElement( "NUnitProject" ); if ( configs.Count > 0 || this.BasePath != this.DefaultBasePath ) { writer.WriteStartElement( "Settings" ); if ( configs.Count > 0 ) writer.WriteAttributeString( "activeconfig", ActiveConfigName ); if ( this.BasePath != this.DefaultBasePath ) writer.WriteAttributeString( "appbase", this.BasePath ); writer.WriteEndElement(); } foreach( ProjectConfig config in Configs ) { writer.WriteStartElement( "Config" ); writer.WriteAttributeString( "name", config.Name ); string appbase = config.BasePath; if ( !PathUtils.SamePathOrUnder( this.BasePath, appbase ) ) writer.WriteAttributeString( "appbase", appbase ); else if ( config.RelativeBasePath != null ) writer.WriteAttributeString( "appbase", config.RelativeBasePath ); string configFile = config.ConfigurationFile; if ( configFile != null && configFile != this.ConfigurationFile ) writer.WriteAttributeString( "configfile", config.ConfigurationFile ); if ( config.BinPathType == BinPathType.Manual ) writer.WriteAttributeString( "binpath", config.PrivateBinPath ); else writer.WriteAttributeString( "binpathtype", config.BinPathType.ToString() ); foreach( string assembly in config.Assemblies ) { writer.WriteStartElement( "assembly" ); writer.WriteAttributeString( "path", PathUtils.RelativePath( config.BasePath, assembly ) ); writer.WriteEndElement(); } writer.WriteEndElement(); } writer.WriteEndElement(); writer.Close(); this.IsDirty = false; // Once we save a project, it's no longer // loaded as an assembly wrapper on reload. this.isAssemblyWrapper = false; } public void Save( string projectPath ) { this.ProjectPath = projectPath; Save(); } public TestPackage MakeTestPackage() { TestPackage package = new TestPackage( this.ProjectPath ); if ( !this.IsAssemblyWrapper ) foreach ( string assembly in this.ActiveConfig.Assemblies ) package.Assemblies.Add( assembly ); package.BasePath = this.ActiveConfig.BasePath; package.ConfigurationFile = this.ActiveConfig.ConfigurationFile; package.PrivateBinPath = this.ActiveConfig.PrivateBinPath; package.AutoBinPath = this.ActiveConfig.BinPathType == BinPathType.Auto; return package; } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections.ObjectModel; using Dbg = System.Management.Automation; namespace System.Management.Automation { /// <summary> /// The context of the core command that is being run. This /// includes data like the user name and password, as well /// as callbacks for streaming output, prompting, and progress. /// /// This allows the providers to be called in a variety of situations. /// The most common will be from the core cmdlets themselves but they /// can also be called programmatically either by having the results /// accumulated or by providing delegates for the various streams. /// /// NOTE: USER Feedback mechanism are only enabled for the CoreCmdlet /// case. This is because we have not seen a use-case for them in the /// other scenarios. /// </summary> internal sealed class CmdletProviderContext { #region Trace object /// <summary> /// An instance of the PSTraceSource class used for trace output /// using "CmdletProviderContext" as the category. /// </summary> [Dbg.TraceSourceAttribute( "CmdletProviderContext", "The context under which a core command is being run.")] private static Dbg.PSTraceSource s_tracer = Dbg.PSTraceSource.GetTracer("CmdletProviderContext", "The context under which a core command is being run."); #endregion Trace object #region Constructor /// <summary> /// Constructs the context under which the core command providers /// operate. /// </summary> /// <param name="executionContext"> /// The context of the engine. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="executionContext"/> is null. /// </exception> internal CmdletProviderContext(ExecutionContext executionContext) { if (executionContext == null) { throw PSTraceSource.NewArgumentNullException("executionContext"); } ExecutionContext = executionContext; Origin = CommandOrigin.Internal; Drive = executionContext.EngineSessionState.CurrentDrive; if ((executionContext.CurrentCommandProcessor != null) && (executionContext.CurrentCommandProcessor.Command is Cmdlet)) { _command = (Cmdlet)executionContext.CurrentCommandProcessor.Command; } } /// <summary> /// Constructs the context under which the core command providers /// operate. /// </summary> /// <param name="executionContext"> /// The context of the engine. /// </param> /// <param name="origin"> /// The origin of the caller of this API /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="executionContext"/> is null. /// </exception> internal CmdletProviderContext(ExecutionContext executionContext, CommandOrigin origin) { if (executionContext == null) { throw PSTraceSource.NewArgumentNullException("executionContext"); } ExecutionContext = executionContext; Origin = origin; } /// <summary> /// Constructs the context under which the core command providers /// operate. /// </summary> /// <param name="command"> /// The command object that is running. /// </param> /// <param name="credentials"> /// The credentials the core command provider should use. /// </param> /// <param name="drive"> /// The drive under which this context should operate. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="command"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// If <paramref name="command"/> contains a null Host or Context reference. /// </exception> internal CmdletProviderContext( PSCmdlet command, PSCredential credentials, PSDriveInfo drive) { // verify the command parameter if (command == null) { throw PSTraceSource.NewArgumentNullException("command"); } _command = command; Origin = command.CommandOrigin; if (credentials != null) { _credentials = credentials; } Drive = drive; if (command.Host == null) { throw PSTraceSource.NewArgumentException("command.Host"); } if (command.Context == null) { throw PSTraceSource.NewArgumentException("command.Context"); } ExecutionContext = command.Context; // Stream will default to true because command methods will be used. PassThru = true; _streamErrors = true; } /// <summary> /// Constructs the context under which the core command providers /// operate. /// </summary> /// <param name="command"> /// The command object that is running. /// </param> /// <param name="credentials"> /// The credentials the core command provider should use. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="command"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// If <paramref name="command"/> contains a null Host or Context reference. /// </exception> internal CmdletProviderContext( PSCmdlet command, PSCredential credentials) { // verify the command parameter if (command == null) { throw PSTraceSource.NewArgumentNullException("command"); } _command = command; Origin = command.CommandOrigin; if (credentials != null) { _credentials = credentials; } if (command.Host == null) { throw PSTraceSource.NewArgumentException("command.Host"); } if (command.Context == null) { throw PSTraceSource.NewArgumentException("command.Context"); } ExecutionContext = command.Context; // Stream will default to true because command methods will be used. PassThru = true; _streamErrors = true; } /// <summary> /// Constructs the context under which the core command providers /// operate. /// </summary> /// <param name="command"> /// The command object that is running. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="command"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// If <paramref name="command"/> contains a null Host or Context reference. /// </exception> internal CmdletProviderContext( Cmdlet command) { // verify the command parameter if (command == null) { throw PSTraceSource.NewArgumentNullException("command"); } _command = command; Origin = command.CommandOrigin; if (command.Context == null) { throw PSTraceSource.NewArgumentException("command.Context"); } ExecutionContext = command.Context; // Stream will default to true because command methods will be used. PassThru = true; _streamErrors = true; } /// <summary> /// Constructs the context under which the core command providers /// operate using an existing context. /// </summary> /// <param name="contextToCopyFrom"> /// A CmdletProviderContext instance to copy the filters, ExecutionContext, /// Credentials, Drive, and Force options from. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="contextToCopyFrom"/> is null. /// </exception> internal CmdletProviderContext( CmdletProviderContext contextToCopyFrom) { if (contextToCopyFrom == null) { throw PSTraceSource.NewArgumentNullException("contextToCopyFrom"); } ExecutionContext = contextToCopyFrom.ExecutionContext; _command = contextToCopyFrom._command; if (contextToCopyFrom.Credential != null) { _credentials = contextToCopyFrom.Credential; } Drive = contextToCopyFrom.Drive; _force = contextToCopyFrom.Force; this.CopyFilters(contextToCopyFrom); SuppressWildcardExpansion = contextToCopyFrom.SuppressWildcardExpansion; DynamicParameters = contextToCopyFrom.DynamicParameters; Origin = contextToCopyFrom.Origin; // Copy the stopping state incase the source context // has already been signaled for stopping Stopping = contextToCopyFrom.Stopping; // add this context to the stop referral on the copied // context contextToCopyFrom.StopReferrals.Add(this); _copiedContext = contextToCopyFrom; } #endregion Constructor #region private properties /// <summary> /// If the constructor that takes a context to copy is /// called, this will be set to the context being copied. /// </summary> private CmdletProviderContext _copiedContext; /// <summary> /// The credentials under which the operation should run. /// </summary> private PSCredential _credentials = PSCredential.Empty; /// <summary> /// The force parameter gives guidance to providers on how vigorously they /// should try to perform an operation. /// </summary> private bool _force; /// <summary> /// The command which defines the context. This should not be /// made visible to anyone and should only be set through the /// constructor. /// </summary> private Cmdlet _command; /// <summary> /// This makes the origin of the provider request visible to the internals. /// </summary> internal CommandOrigin Origin { get; } = CommandOrigin.Internal; /// <summary> /// This defines the default behavior for the WriteError method. /// If it is true, a call to this method will result in an immediate call /// to the command WriteError method, or to the writeErrorDelegate if /// one has been supplied. /// If it is false, the objects will be accumulated until the /// GetErrorObjects method is called. /// </summary> private bool _streamErrors; /// <summary> /// A collection in which objects that are written using the WriteObject(s) /// methods are accumulated if <see cref="PassThru" /> is false. /// </summary> private Collection<PSObject> _accumulatedObjects = new Collection<PSObject>(); /// <summary> /// A collection in which objects that are written using the WriteError /// method are accumulated if <see cref="PassThru" /> is false. /// </summary> private Collection<ErrorRecord> _accumulatedErrorObjects = new Collection<ErrorRecord>(); /// <summary> /// The instance of the provider that is currently executing in this context. /// </summary> private System.Management.Automation.Provider.CmdletProvider _providerInstance; #endregion private properties #region Internal properties /// <summary> /// Gets the execution context of the engine. /// </summary> internal ExecutionContext ExecutionContext { get; } /// <summary> /// Gets or sets the provider instance for the current /// execution context. /// </summary> internal System.Management.Automation.Provider.CmdletProvider ProviderInstance { get { return _providerInstance; } set { _providerInstance = value; } } /// <summary> /// Copies the include, exclude, and provider filters from /// the specified context to this context. /// </summary> /// <param name="context"> /// The context to copy the filters from. /// </param> private void CopyFilters(CmdletProviderContext context) { Dbg.Diagnostics.Assert( context != null, "The caller should have verified the context"); Include = context.Include; Exclude = context.Exclude; Filter = context.Filter; } internal void RemoveStopReferral() { if (_copiedContext != null) { _copiedContext.StopReferrals.Remove(this); } } #endregion Internal properties #region Public properties /// <summary> /// Gets or sets the dynamic parameters for the context. /// </summary> internal object DynamicParameters { get; set; } /// <summary> /// Returns MyInvocation from the underlying cmdlet. /// </summary> internal InvocationInfo MyInvocation { get { if (_command != null) { return _command.MyInvocation; } else { return null; } } } /// <summary> /// Determines if the Write* calls should be passed through to the command /// instance if there is one. The default value is true. /// </summary> internal bool PassThru { get; set; } /// <summary> /// The drive associated with this context. /// </summary> /// <exception cref="ArgumentNullException"> /// If <paramref name="value"/> is null on set. /// </exception> internal PSDriveInfo Drive { get; set; } /// <summary> /// Gets the user name under which the operation should run. /// </summary> internal PSCredential Credential { get { PSCredential result = _credentials; // If the username wasn't specified, use the drive credentials if (_credentials == null && Drive != null) { result = Drive.Credential; } return result; } } #region Transaction Support /// <summary> /// Gets the flag that determines if the command requested a transaction. /// </summary> internal bool UseTransaction { get { if ((_command != null) && (_command.CommandRuntime != null)) { MshCommandRuntime mshRuntime = _command.CommandRuntime as MshCommandRuntime; if (mshRuntime != null) { return mshRuntime.UseTransaction; } } return false; } } /// <summary> /// Returns true if a transaction is available and active. /// </summary> public bool TransactionAvailable() { if (_command != null) { return _command.TransactionAvailable(); } return false; } /// <summary> /// Gets an object that surfaces the current PowerShell transaction. /// When this object is disposed, PowerShell resets the active transaction. /// </summary> public PSTransactionContext CurrentPSTransaction { get { if (_command != null) { return _command.CurrentPSTransaction; } return null; } } #endregion Transaction Support /// <summary> /// Gets or sets the Force property that is passed to providers. /// </summary> internal SwitchParameter Force { get { return _force; } set { _force = value; } } /// <summary> /// The provider specific filter that should be used when determining /// which items an action should take place on. /// </summary> internal string Filter { get; set; } /// <summary> /// A glob string that signifies which items should be included when determining /// which items the action should occur on. /// </summary> internal Collection<string> Include { get; private set; } /// <summary> /// A glob string that signifies which items should be excluded when determining /// which items the action should occur on. /// </summary> internal Collection<string> Exclude { get; private set; } /// <summary> /// Gets or sets the property that tells providers (that /// declare their own wildcard support) to suppress wildcard /// expansion. This is set when the user specifies the /// -LiteralPath parameter to one of the core commands. /// </summary> public bool SuppressWildcardExpansion { get; internal set; } #region User feedback mechanisms /// <summary> /// Confirm the operation with the user. /// </summary> /// <param name="target"> /// Name of the target resource being acted upon /// </param> /// <remarks>true iff the action should be performed</remarks> /// <exception cref="PipelineStoppedException"> /// The ActionPreference.Stop or ActionPreference.Inquire policy /// triggered a terminating error. The pipeline failure will be /// ActionPreferenceStopException. /// Also, this occurs if the pipeline was already stopped. /// </exception> internal bool ShouldProcess( string target) { bool result = true; if (_command != null) { result = _command.ShouldProcess(target); } return result; } /// <summary> /// Confirm the operation with the user. /// </summary> /// <param name="target"> /// Name of the target resource being acted upon /// </param> /// <param name="action">What action was being performed.</param> /// <remarks>true iff the action should be performed</remarks> /// <exception cref="PipelineStoppedException"> /// The ActionPreference.Stop or ActionPreference.Inquire policy /// triggered a terminating error. The pipeline failure will be /// ActionPreferenceStopException. /// Also, this occurs if the pipeline was already stopped. /// </exception> internal bool ShouldProcess( string target, string action) { bool result = true; if (_command != null) { result = _command.ShouldProcess(target, action); } return result; } /// <summary> /// Confirm the operation with the user. /// </summary> /// <param name="verboseDescription"> /// This should contain a textual description of the action to be /// performed. This is what will be displayed to the user for /// ActionPreference.Continue. /// </param> /// <param name="verboseWarning"> /// This should contain a textual query of whether the action /// should be performed, usually in the form of a question. /// This is what will be displayed to the user for /// ActionPreference.Inquire. /// </param> /// <param name="caption"> /// This is the caption of the window which may be displayed /// if the user is prompted whether or not to perform the action. /// It may be displayed by some hosts, but not all. /// </param> /// <remarks>true iff the action should be performed</remarks> /// <exception cref="PipelineStoppedException"> /// The ActionPreference.Stop or ActionPreference.Inquire policy /// triggered a terminating error. The pipeline failure will be /// ActionPreferenceStopException. /// Also, this occurs if the pipeline was already stopped. /// </exception> internal bool ShouldProcess( string verboseDescription, string verboseWarning, string caption) { bool result = true; if (_command != null) { result = _command.ShouldProcess( verboseDescription, verboseWarning, caption); } return result; } /// <summary> /// Confirm the operation with the user. /// </summary> /// <param name="verboseDescription"> /// This should contain a textual description of the action to be /// performed. This is what will be displayed to the user for /// ActionPreference.Continue. /// </param> /// <param name="verboseWarning"> /// This should contain a textual query of whether the action /// should be performed, usually in the form of a question. /// This is what will be displayed to the user for /// ActionPreference.Inquire. /// </param> /// <param name="caption"> /// This is the caption of the window which may be displayed /// if the user is prompted whether or not to perform the action. /// It may be displayed by some hosts, but not all. /// </param> /// <param name="shouldProcessReason"> /// Indicates the reason(s) why ShouldProcess returned what it returned. /// Only the reasons enumerated in /// <see cref="System.Management.Automation.ShouldProcessReason"/> /// are returned. /// </param> /// <remarks>true iff the action should be performed</remarks> /// <exception cref="PipelineStoppedException"> /// The ActionPreference.Stop or ActionPreference.Inquire policy /// triggered a terminating error. The pipeline failure will be /// ActionPreferenceStopException. /// Also, this occurs if the pipeline was already stopped. /// </exception> internal bool ShouldProcess( string verboseDescription, string verboseWarning, string caption, out ShouldProcessReason shouldProcessReason) { bool result = true; if (_command != null) { result = _command.ShouldProcess( verboseDescription, verboseWarning, caption, out shouldProcessReason); } else { shouldProcessReason = ShouldProcessReason.None; } return result; } /// <summary> /// Ask the user whether to continue/stop or break to a subshell. /// </summary> /// <param name="query"> /// Message to display to the user. This routine will append /// the text "Continue" to ensure that people know what question /// they are answering. /// </param> /// <param name="caption"> /// Dialog caption if the host uses a dialog. /// </param> /// <returns> /// True if the user wants to continue, false if not. /// </returns> internal bool ShouldContinue( string query, string caption) { bool result = true; if (_command != null) { result = _command.ShouldContinue(query, caption); } return result; } /// <summary> /// Ask the user whether to continue/stop or break to a subshell. /// </summary> /// <param name="query"> /// Message to display to the user. This routine will append /// the text "Continue" to ensure that people know what question /// they are answering. /// </param> /// <param name="caption"> /// Dialog caption if the host uses a dialog. /// </param> /// <param name="yesToAll"> /// Indicates whether the user selected YesToAll /// </param> /// <param name="noToAll"> /// Indicates whether the user selected NoToAll /// </param> /// <returns> /// True if the user wants to continue, false if not. /// </returns> internal bool ShouldContinue( string query, string caption, ref bool yesToAll, ref bool noToAll) { bool result = true; if (_command != null) { result = _command.ShouldContinue( query, caption, ref yesToAll, ref noToAll); } else { yesToAll = false; noToAll = false; } return result; } /// <summary> /// Writes the object to the Verbose pipe. /// </summary> /// <param name="text"> /// The string that needs to be written. /// </param> internal void WriteVerbose(string text) { if (_command != null) { _command.WriteVerbose(text); } } /// <summary> /// Writes the object to the Warning pipe. /// </summary> /// <param name="text"> /// The string that needs to be written. /// </param> internal void WriteWarning(string text) { if (_command != null) { _command.WriteWarning(text); } } internal void WriteProgress(ProgressRecord record) { if (_command != null) { _command.WriteProgress(record); } } /// <summary> /// Writes a debug string. /// </summary> /// <param name="text"> /// The String that needs to be written. /// </param> internal void WriteDebug(string text) { if (_command != null) { _command.WriteDebug(text); } } internal void WriteInformation(InformationRecord record) { if (_command != null) { _command.WriteInformation(record); } } internal void WriteInformation(Object messageData, string[] tags) { if (_command != null) { _command.WriteInformation(messageData, tags); } } #endregion User feedback mechanisms #endregion Public properties #region Public methods /// <summary> /// Sets the filters that are used within this context. /// </summary> /// <param name="include"> /// The include filters which determines which items are included in /// operations within this context. /// </param> /// <param name="exclude"> /// The exclude filters which determines which items are excluded from /// operations within this context. /// </param> /// <param name="filter"> /// The provider specific filter for the operation. /// </param> internal void SetFilters(Collection<string> include, Collection<string> exclude, string filter) { Include = include; Exclude = exclude; Filter = filter; } /// <summary> /// Gets an array of the objects that have been accumulated /// and the clears the collection. /// </summary> /// <returns> /// An object array of the objects that have been accumulated /// through the WriteObject method. /// </returns> internal Collection<PSObject> GetAccumulatedObjects() { // Get the contents as an array Collection<PSObject> results = _accumulatedObjects; _accumulatedObjects = new Collection<PSObject>(); // Return the array return results; } /// <summary> /// Gets an array of the error objects that have been accumulated /// and the clears the collection. /// </summary> /// <returns> /// An object array of the objects that have been accumulated /// through the WriteError method. /// </returns> internal Collection<ErrorRecord> GetAccumulatedErrorObjects() { // Get the contents as an array Collection<ErrorRecord> results = _accumulatedErrorObjects; _accumulatedErrorObjects = new Collection<ErrorRecord>(); // Return the array return results; } /// <summary> /// If there are any errors accumulated, the first error is thrown. /// </summary> /// <exception cref="ProviderInvocationException"> /// If a CmdletProvider wrote any exceptions to the error pipeline, it is /// wrapped and then thrown. /// </exception> internal void ThrowFirstErrorOrDoNothing() { ThrowFirstErrorOrDoNothing(true); } /// <summary> /// If there are any errors accumulated, the first error is thrown. /// </summary> /// <param name="wrapExceptionInProviderException"> /// If true, the error will be wrapped in a ProviderInvocationException before /// being thrown. If false, the error will be thrown as is. /// </param> /// <exception cref="ProviderInvocationException"> /// If <paramref name="wrapExceptionInProviderException"/> is true, the /// first exception that was written to the error pipeline by a CmdletProvider /// is wrapped and thrown. /// </exception> /// <exception> /// If <paramref name="wrapExceptionInProviderException"/> is false, /// the first exception that was written to the error pipeline by a CmdletProvider /// is thrown. /// </exception> internal void ThrowFirstErrorOrDoNothing(bool wrapExceptionInProviderException) { if (HasErrors()) { Collection<ErrorRecord> errors = GetAccumulatedErrorObjects(); if (errors != null && errors.Count > 0) { // Throw the first exception if (wrapExceptionInProviderException) { ProviderInfo providerInfo = null; if (this.ProviderInstance != null) { providerInfo = this.ProviderInstance.ProviderInfo; } ProviderInvocationException e = new ProviderInvocationException( providerInfo, errors[0]); // Log a provider health event MshLog.LogProviderHealthEvent( this.ExecutionContext, providerInfo != null ? providerInfo.Name : "unknown provider", e, Severity.Warning); throw e; } else { throw errors[0].Exception; } } } } /// <summary> /// Writes all the accumulated errors to the specified context using WriteError. /// </summary> /// <param name="errorContext"> /// The context to write the errors to. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="errorContext"/> is null. /// </exception> internal void WriteErrorsToContext(CmdletProviderContext errorContext) { if (errorContext == null) { throw PSTraceSource.NewArgumentNullException("errorContext"); } if (HasErrors()) { foreach (ErrorRecord errorRecord in GetAccumulatedErrorObjects()) { errorContext.WriteError(errorRecord); } } } /// <summary> /// Writes an object to the output. /// </summary> /// <param name="obj"> /// The object to be written. /// </param> /// <remarks> /// If streaming is on and the writeObjectHandler was specified then the object /// gets written to the writeObjectHandler. If streaming is on and the writeObjectHandler /// was not specified and the command object was specified, the object gets written to /// the WriteObject method of the command object. /// If streaming is off the object gets written to an accumulator collection. The collection /// of written object can be retrieved using the AccumulatedObjects method. /// </remarks> /// <exception cref="InvalidOperationException"> /// The CmdletProvider could not stream the results because no /// cmdlet was specified to stream the output through. /// </exception> /// <exception cref="PipelineStoppedException"> /// If the pipeline has been signaled for stopping but /// the provider calls this method. /// </exception> internal void WriteObject(object obj) { // Making sure to obey the StopProcessing by // throwing an exception anytime a provider tries // to WriteObject if (Stopping) { PipelineStoppedException stopPipeline = new PipelineStoppedException(); throw stopPipeline; } if (PassThru) { if (_command != null) { s_tracer.WriteLine("Writing to command pipeline"); // Since there was no writeObject handler use // the command WriteObject method. _command.WriteObject(obj); } else { // The flag was set for streaming but we have no where // to stream to. InvalidOperationException e = PSTraceSource.NewInvalidOperationException( SessionStateStrings.OutputStreamingNotEnabled); throw e; } } else { s_tracer.WriteLine("Writing to accumulated objects"); // Convert the object to a PSObject if it's not already // one. PSObject newObj = PSObject.AsPSObject(obj); // Since we are not streaming, just add the object to the accumulatedObjects _accumulatedObjects.Add(newObj); } } /// <summary> /// Writes the error to the pipeline or accumulates the error in an internal /// buffer. /// </summary> /// <param name="errorRecord"> /// The error record to write to the pipeline or the internal buffer. /// </param> /// <exception cref="InvalidOperationException"> /// The CmdletProvider could not stream the error because no /// cmdlet was specified to stream the output through. /// </exception> /// <exception cref="PipelineStoppedException"> /// If the pipeline has been signaled for stopping but /// the provider calls this method. /// </exception> internal void WriteError(ErrorRecord errorRecord) { // Making sure to obey the StopProcessing by // throwing an exception anytime a provider tries // to WriteError if (Stopping) { PipelineStoppedException stopPipeline = new PipelineStoppedException(); throw stopPipeline; } if (_streamErrors) { if (_command != null) { s_tracer.WriteLine("Writing error package to command error pipe"); _command.WriteError(errorRecord); } else { InvalidOperationException e = PSTraceSource.NewInvalidOperationException( SessionStateStrings.ErrorStreamingNotEnabled); throw e; } } else { // Since we are not streaming, just add the object to the accumulatedErrorObjects _accumulatedErrorObjects.Add(errorRecord); if (errorRecord.ErrorDetails != null && errorRecord.ErrorDetails.TextLookupError != null) { Exception textLookupError = errorRecord.ErrorDetails.TextLookupError; errorRecord.ErrorDetails.TextLookupError = null; MshLog.LogProviderHealthEvent( this.ExecutionContext, this.ProviderInstance.ProviderInfo.Name, textLookupError, Severity.Warning); } } } /// <summary> /// If the error pipeline hasn't been supplied a delegate or a command then this method /// will determine if any errors have accumulated. /// </summary> /// <returns> /// True if the errors are being accumulated and some errors have been accumulated. False otherwise. /// </returns> internal bool HasErrors() { return _accumulatedErrorObjects != null && _accumulatedErrorObjects.Count > 0; } /// <summary> /// Call this on a separate thread when a provider is using /// this context to do work. This method will call the StopProcessing /// method of the provider. /// </summary> internal void StopProcessing() { Stopping = true; if (_providerInstance != null) { // We don't need to catch any of the exceptions here because // we are terminating the pipeline and any exception will // be caught by the engine. _providerInstance.StopProcessing(); } // Call the stop referrals if any foreach (CmdletProviderContext referralContext in StopReferrals) { referralContext.StopProcessing(); } } internal bool Stopping { get; private set; } /// <summary> /// The list of contexts to which the StopProcessing calls /// should be referred. /// </summary> internal Collection<CmdletProviderContext> StopReferrals { get; } = new Collection<CmdletProviderContext>(); internal bool HasIncludeOrExclude { get { return ((Include != null && Include.Count > 0) || (Exclude != null && Exclude.Count > 0)); } } #endregion Public methods } }
// ******************************************************************************************************** // Product Name: DotSpatial.Controls.dll // Description: The Windows Forms user interface controls like the map, legend, toolbox, ribbon and others. // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 11/17/2008 10:20:46 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // Kyle Ellison 01/07/2010 Changed Draw*Feature from private to public to expose label functionality // // ******************************************************************************************************** using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Text; using System.Linq; using System.Windows.Forms; using DotSpatial.Data; using DotSpatial.Serialization; using DotSpatial.Symbology; using GeoAPI.Geometries; using NetTopologySuite.Geometries; namespace DotSpatial.Controls { /// <summary> /// GeoLabelLayer /// </summary> public class MapLabelLayer : LabelLayer, IMapLabelLayer { #region Fields private static readonly Caches _caches = new Caches(); /// <summary> /// The existing labels, accessed for all map label layers, not just this instance /// </summary> private static readonly List<RectangleF> ExistingLabels = new List<RectangleF>(); // for collision prevention, tracks existing labels. private Image _backBuffer; // draw to the back buffer, and swap to the stencil when done. private Envelope _bufferExtent; // the geographic extent of the current buffer. private Rectangle _bufferRectangle; private int _chunkSize; private bool _isInitialized; private Image _stencil; // draw features to the stencil #endregion #region Constructors /// <summary> /// Creates a new instance of GeoLabelLayer /// </summary> public MapLabelLayer() { Configure(); } /// <summary> /// Creates a new label layer based on the specified featureset /// </summary> /// <param name="inFeatureSet"></param> public MapLabelLayer(IFeatureSet inFeatureSet) : base(inFeatureSet) { Configure(); } /// <summary> /// Creates a new label layer based on the specified feature layer /// </summary> /// <param name="inFeatureLayer">The feature layer to build layers from</param> public MapLabelLayer(IFeatureLayer inFeatureLayer) : base(inFeatureLayer) { Configure(); } #endregion #region Events /// <summary> /// Fires an event that indicates to the parent map-frame that it should first /// redraw the specified clip /// </summary> public event EventHandler<ClipArgs> BufferChanged; #endregion #region Properties /// <summary> /// Gets or sets the back buffer that will be drawn to as part of the initialization process. /// </summary> [ShallowCopy, Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Image BackBuffer { get { return _backBuffer; } set { _backBuffer = value; } } /// <summary> /// Gets the current buffer. /// </summary> [ShallowCopy, Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Image Buffer { get { return _stencil; } set { _stencil = value; } } /// <summary> /// Gets or sets the geographic region represented by the buffer /// Calling Initialize will set this automatically. /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Envelope BufferEnvelope { get { return _bufferExtent; } set { _bufferExtent = value; } } /// <summary> /// Gets or sets the rectangle in pixels to use as the back buffer. /// Calling Initialize will set this automatically. /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Rectangle BufferRectangle { get { return _bufferRectangle; } set { _bufferRectangle = value; } } /// <summary> /// Gets or sets the maximum number of labels that will be rendered before /// refreshing the screen. /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int ChunkSize { get { return _chunkSize; } set { _chunkSize = value; } } /// <summary> /// Gets or sets the MapFeatureLayer that this label layer is attached to. /// </summary> [ShallowCopy, Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new IMapFeatureLayer FeatureLayer { get { return base.FeatureLayer as IMapFeatureLayer; } set { base.FeatureLayer = value; } } /// <summary> /// Gets or sets whether or not this layer has been initialized. /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new bool IsInitialized { get { return _isInitialized; } set { _isInitialized = value; } } #endregion #region Methods /// <summary> /// Call StartDrawing before using this. /// </summary> /// <param name="rectangles">The rectangular region in pixels to clear.</param> /// <param name= "color">The color to use when clearing. Specifying transparent /// will replace content with transparent pixels.</param> public void Clear(List<Rectangle> rectangles, Color color) { if (_backBuffer == null) return; Graphics g = Graphics.FromImage(_backBuffer); foreach (Rectangle r in rectangles) { if (r.IsEmpty == false) { g.Clip = new Region(r); g.Clear(color); } } g.Dispose(); } /// <summary> /// Cleaer all existing labels for all layers /// </summary> public static void ClearAllExistingLabels() { ExistingLabels.Clear(); } /// <summary> /// Checks whether the given rectangle collides with the drawnRectangles. /// </summary> /// <param name="rectangle">Rectangle that we want to draw next.</param> /// <param name="drawnRectangles">Rectangle that were already drawn.</param> /// <returns>True, if the rectangle collides with a rectancle that was already drawn.</returns> private static bool Collides(RectangleF rectangle, IEnumerable<RectangleF> drawnRectangles) { return drawnRectangles.Any(rectangle.IntersectsWith); } /// <summary> /// Draws the given text if it is on screen. If PreventCollision is set only labels that don't collide with existingLables are drawn. /// </summary> /// <param name="txt">Text that should be drawn.</param> /// <param name="g">Graphics object that does the drawing.</param> /// <param name="symb">Symbolizer to figure out the look of the label.</param> /// <param name="f">Feature, the label belongs to.</param> /// <param name="e"></param> /// <param name="labelBounds"></param> /// <param name="existingLabels">List with labels that were already drawn.</param> /// <param name="angle">Angle in degree the label gets rotated by.</param> private static void CollisionDraw(string txt, Graphics g, ILabelSymbolizer symb, IFeature f, MapArgs e, RectangleF labelBounds, List<RectangleF> existingLabels, float angle) { if (labelBounds.IsEmpty || !e.ImageRectangle.IntersectsWith(labelBounds)) return; if (symb.PreventCollisions) { if (!Collides(labelBounds, existingLabels)) { DrawLabel(g, txt, labelBounds, symb, f, angle); existingLabels.Add(labelBounds); } } else { DrawLabel(g, txt, labelBounds, symb, f, angle); } } private void Configure() { _chunkSize = 10000; } /// <summary> /// Draws the labels for the given features. /// </summary> /// <param name="args">The GeoArgs that control how these features should be drawn.</param> /// <param name="features">The features that should be drawn.</param> /// <param name="clipRectangles">If an entire chunk is drawn and an update is specified, this clarifies the changed rectangles.</param> /// <param name="useChunks">Boolean, if true, this will refresh the buffer in chunks.</param> public virtual void DrawFeatures(MapArgs args, List<IFeature> features, List<Rectangle> clipRectangles, bool useChunks) { if (useChunks == false) { DrawFeatures(args, features); return; } int count = features.Count; int numChunks = (int)Math.Ceiling(count / (double)ChunkSize); for (int chunk = 0; chunk < numChunks; chunk++) { int numFeatures = ChunkSize; if (chunk == numChunks - 1) numFeatures = features.Count - (chunk * ChunkSize); DrawFeatures(args, features.GetRange(chunk * ChunkSize, numFeatures)); if (numChunks > 0 && chunk < numChunks - 1) { OnBufferChanged(clipRectangles); Application.DoEvents(); } } } /// <summary> /// Draws the labels for the given features. /// </summary> /// <param name="args">The GeoArgs that control how these features should be drawn.</param> /// <param name="features">The features that should be drawn.</param> /// <param name="clipRectangles">If an entire chunk is drawn and an update is specified, this clarifies the changed rectangles.</param> /// <param name="useChunks">Boolean, if true, this will refresh the buffer in chunks.</param> public virtual void DrawFeatures(MapArgs args, List<int> features, List<Rectangle> clipRectangles, bool useChunks) { if (useChunks == false) { DrawFeatures(args, features); return; } int count = features.Count; int numChunks = (int)Math.Ceiling(count / (double)ChunkSize); for (int chunk = 0; chunk < numChunks; chunk++) { int numFeatures = ChunkSize; if (chunk == numChunks - 1) numFeatures = features.Count - (chunk * ChunkSize); DrawFeatures(args, features.GetRange(chunk * ChunkSize, numFeatures)); if (numChunks > 0 && chunk < numChunks - 1) { OnBufferChanged(clipRectangles); Application.DoEvents(); } } } /// <summary> /// Draws the labels for the given features. /// </summary> /// <param name="e">MapArgs to get Graphics object from.</param> /// <param name="features">Indizes of the features whose labels get drawn.</param> private void DrawFeatures(MapArgs e, IEnumerable<int> features) { // Check that exists at least one category with Expression if (Symbology.Categories.All(_ => string.IsNullOrEmpty(_.Expression))) return; Graphics g = e.Device ?? Graphics.FromImage(_backBuffer); Matrix origTransform = g.Transform; // Only draw features that are currently visible. if (FastDrawnStates == null) { CreateIndexedLabels(); } FastLabelDrawnState[] drawStates = FastDrawnStates; if (drawStates == null) return; //Sets the graphics objects smoothing modes g.TextRenderingHint = TextRenderingHint.AntiAlias; g.SmoothingMode = SmoothingMode.AntiAlias; Action<int, IFeature> drawFeature; switch (FeatureSet.FeatureType) { case FeatureType.Polygon: drawFeature = (fid, feature) => DrawPolygonFeature(e, g, feature, drawStates[fid].Category, drawStates[fid].Selected, ExistingLabels); break; case FeatureType.Line: drawFeature = (fid, feature) => DrawLineFeature(e, g, feature, drawStates[fid].Category, drawStates[fid].Selected, ExistingLabels); break; case FeatureType.Point: case FeatureType.MultiPoint: drawFeature = (fid, feature) => DrawPointFeature(e, g, feature, drawStates[fid].Category, drawStates[fid].Selected, ExistingLabels); break; default: return; // Can't draw something else } foreach (var category in Symbology.Categories) { category.UpdateExpressionColumns(FeatureSet.DataTable.Columns); var catFeatures = new List<int>(); foreach (int fid in features) { if (drawStates[fid] == null || drawStates[fid].Category == null) continue; if (drawStates[fid].Category == category) { catFeatures.Add(fid); } } // Now that we are restricted to a certain category, we can look at priority if (category.Symbolizer.PriorityField != "FID") { Feature.ComparisonField = category.Symbolizer.PriorityField; catFeatures.Sort(); // When preventing collisions, we want to do high priority first. // Otherwise, do high priority last. if (category.Symbolizer.PreventCollisions) { if (!category.Symbolizer.PrioritizeLowValues) { catFeatures.Reverse(); } } else { if (category.Symbolizer.PrioritizeLowValues) { catFeatures.Reverse(); } } } foreach (var fid in catFeatures) { if (!FeatureLayer.DrawnStates[fid].Visible) continue; var feature = FeatureSet.GetFeature(fid); drawFeature(fid, feature); } } if (e.Device == null) g.Dispose(); else g.Transform = origTransform; } /// <summary> /// Draws the labels for the given features. /// </summary> /// <param name="e">MapArgs to get Graphics object from.</param> /// <param name="features">Features, whose labels get drawn.</param> private void DrawFeatures(MapArgs e, IEnumerable<IFeature> features) { // Check that exists at least one category with Expression if (Symbology.Categories.All(_ => string.IsNullOrEmpty(_.Expression))) return; Graphics g = e.Device ?? Graphics.FromImage(_backBuffer); Matrix origTransform = g.Transform; // Only draw features that are currently visible. if (DrawnStates == null || !DrawnStates.ContainsKey(features.First())) { CreateLabels(); } Dictionary<IFeature, LabelDrawState> drawStates = DrawnStates; if (drawStates == null) return; //Sets the graphics objects smoothing modes g.TextRenderingHint = TextRenderingHint.AntiAlias; g.SmoothingMode = SmoothingMode.AntiAlias; Action<IFeature> drawFeature; switch (features.First().FeatureType) { case FeatureType.Polygon: drawFeature = f => DrawPolygonFeature(e, g, f, drawStates[f].Category, drawStates[f].Selected, ExistingLabels); break; case FeatureType.Line: drawFeature = f => DrawLineFeature(e, g, f, drawStates[f].Category, drawStates[f].Selected, ExistingLabels); break; case FeatureType.Point: case FeatureType.MultiPoint: drawFeature = f => DrawPointFeature(e, g, f, drawStates[f].Category, drawStates[f].Selected, ExistingLabels); break; default: return; // Can't draw something else } foreach (ILabelCategory category in Symbology.Categories) { category.UpdateExpressionColumns(FeatureSet.DataTable.Columns); var cat = category; // prevent access to unmodified closure problems List<IFeature> catFeatures = new List<IFeature>(); foreach (IFeature f in features) { if (drawStates.ContainsKey(f) && drawStates[f].Category == cat) { catFeatures.Add(f); } } // Now that we are restricted to a certain category, we can look at // priority if (category.Symbolizer.PriorityField != "FID") { Feature.ComparisonField = cat.Symbolizer.PriorityField; catFeatures.Sort(); // When preventing collisions, we want to do high priority first. // otherwise, do high priority last. if (cat.Symbolizer.PreventCollisions) { if (!cat.Symbolizer.PrioritizeLowValues) { catFeatures.Reverse(); } } else { if (cat.Symbolizer.PrioritizeLowValues) { catFeatures.Reverse(); } } } for (int i = 0; i < catFeatures.Count; i++) { if (!FeatureLayer.DrawnStates[i].Visible) continue; drawFeature(catFeatures[i]); } } if (e.Device == null) g.Dispose(); else g.Transform = origTransform; } /// <summary> /// Draws labels in a specified rectangle /// </summary> /// <param name="g">The graphics object to draw to</param> /// <param name="labelText">The label text to draw</param> /// <param name="labelBounds">The rectangle of the label</param> /// <param name="symb">the Label Symbolizer to use when drawing the label</param> /// <param name="feature">Feature to draw</param> /// <param name="angle">Angle in degree the label gets rotated by.</param> private static void DrawLabel(Graphics g, string labelText, RectangleF labelBounds, ILabelSymbolizer symb, IFeature feature, float angle) { //Sets up the brushes and such for the labeling Font textFont = _caches.GetFont(symb); var format = new StringFormat { Alignment = symb.Alignment }; //Text graphics path var gp = new GraphicsPath(); gp.AddString(labelText, textFont.FontFamily, (int)textFont.Style, textFont.SizeInPoints * 96F / 72F, labelBounds, format); // Rotate text RotateAt(g, labelBounds.X, labelBounds.Y, angle); // Draws the text outline if (symb.BackColorEnabled && symb.BackColor != Color.Transparent) { var backBrush = _caches.GetSolidBrush(symb.BackColor); if (symb.FontColor == Color.Transparent) { using (var backgroundGP = new GraphicsPath()) { backgroundGP.AddRectangle(labelBounds); backgroundGP.FillMode = FillMode.Alternate; backgroundGP.AddPath(gp, true); g.FillPath(backBrush, backgroundGP); } } else { g.FillRectangle(backBrush, labelBounds); } } // Draws the border if its enabled if (symb.BorderVisible && symb.BorderColor != Color.Transparent) { var borderPen = _caches.GetPen(symb.BorderColor); g.DrawRectangle(borderPen, labelBounds.X, labelBounds.Y, labelBounds.Width, labelBounds.Height); } // Draws the drop shadow if (symb.DropShadowEnabled && symb.DropShadowColor != Color.Transparent) { var shadowBrush = _caches.GetSolidBrush(symb.DropShadowColor); var gpTrans = new Matrix(); gpTrans.Translate(symb.DropShadowPixelOffset.X, symb.DropShadowPixelOffset.Y); gp.Transform(gpTrans); g.FillPath(shadowBrush, gp); gpTrans = new Matrix(); gpTrans.Translate(-symb.DropShadowPixelOffset.X, -symb.DropShadowPixelOffset.Y); gp.Transform(gpTrans); gpTrans.Dispose(); } // Draws the text halo if (symb.HaloEnabled && symb.HaloColor != Color.Transparent) { using (var haloPen = new Pen(symb.HaloColor) { Width = 2, Alignment = PenAlignment.Outset }) g.DrawPath(haloPen, gp); } // Draws the text if its not transparent if (symb.FontColor != Color.Transparent) { var foreBrush = _caches.GetSolidBrush(symb.FontColor); g.FillPath(foreBrush, gp); } gp.Dispose(); } /// <summary> /// Draws a label on a line with various different methods. /// </summary> public static void DrawLineFeature(MapArgs e, Graphics g, IFeature f, ILabelCategory category, bool selected, List<RectangleF> existingLabels) { var symb = selected ? category.SelectionSymbolizer : category.Symbolizer; //Gets the features text and calculate the label size string txt = category.CalculateExpression(f.DataRow, selected, f.Fid); if (txt == null) return; Func<SizeF> labelSize = () => g.MeasureString(txt, _caches.GetFont(symb)); IGeometry geo = f.Geometry; if (geo.NumGeometries == 1) { var angle = GetAngleToRotate(symb, f, f.Geometry); RectangleF labelBounds = PlaceLineLabel(f.Geometry, labelSize, e, symb, angle); CollisionDraw(txt, g, symb, f, e, labelBounds, existingLabels, angle); } else { //Depending on the labeling strategy we do diff things if (symb.PartsLabelingMethod == PartLabelingMethod.LabelAllParts) { for (int n = 0; n < geo.NumGeometries; n++) { var angle = GetAngleToRotate(symb, f, geo.GetGeometryN(n)); RectangleF labelBounds = PlaceLineLabel(geo.GetGeometryN(n), labelSize, e, symb, angle); CollisionDraw(txt, g, symb, f, e, labelBounds, existingLabels, angle); } } else { double longestLine = 0; int longestIndex = 0; for (int n = 0; n < geo.NumGeometries; n++) { ILineString ls = geo.GetGeometryN(n) as ILineString; double tempLength = 0; if (ls != null) tempLength = ls.Length; if (longestLine < tempLength) { longestLine = tempLength; longestIndex = n; } } var angle = GetAngleToRotate(symb, f, geo.GetGeometryN(longestIndex)); RectangleF labelBounds = PlaceLineLabel(geo.GetGeometryN(longestIndex), labelSize, e, symb, angle); CollisionDraw(txt, g, symb, f, e, labelBounds, existingLabels, angle); } } } /// <summary> /// Draws a label on a point with various different methods. /// </summary> /// <param name="e"></param> /// <param name="g"></param> /// <param name="f"></param> /// <param name="category"></param> /// <param name="selected"></param> /// <param name="existingLabels"></param> public static void DrawPointFeature(MapArgs e, Graphics g, IFeature f, ILabelCategory category, bool selected, List<RectangleF> existingLabels) { var symb = selected ? category.SelectionSymbolizer : category.Symbolizer; //Gets the features text and calculate the label size string txt = category.CalculateExpression(f.DataRow, selected, f.Fid); if (txt == null) return; var angle = GetAngleToRotate(symb, f); Func<SizeF> labelSize = () => g.MeasureString(txt, _caches.GetFont(symb)); //Depending on the labeling strategy we do different things if (symb.PartsLabelingMethod == PartLabelingMethod.LabelAllParts) { for (int n = 0; n < f.Geometry.NumGeometries; n++) { RectangleF labelBounds = PlacePointLabel(f.Geometry.GetGeometryN(n), e, labelSize, symb, angle); CollisionDraw(txt, g, symb, f, e, labelBounds, existingLabels, angle); } } else { RectangleF labelBounds = PlacePointLabel(f.Geometry, e, labelSize, symb, angle); CollisionDraw(txt, g, symb, f, e, labelBounds, existingLabels, angle); } } /// <summary> /// Draws a label on a polygon with various different methods /// </summary> public static void DrawPolygonFeature(MapArgs e, Graphics g, IFeature f, ILabelCategory category, bool selected, List<RectangleF> existingLabels) { var symb = selected ? category.SelectionSymbolizer : category.Symbolizer; //Gets the features text and calculate the label size string txt = category.CalculateExpression(f.DataRow, selected, f.Fid); if (txt == null) return; var angle = GetAngleToRotate(symb, f); Func<SizeF> labelSize = () => g.MeasureString(txt, _caches.GetFont(symb)); IGeometry geo = f.Geometry; if (geo.NumGeometries == 1) { RectangleF labelBounds = PlacePolygonLabel(f.Geometry, e, labelSize, symb, angle); CollisionDraw(txt, g, symb, f, e, labelBounds, existingLabels, angle); } else { if (symb.PartsLabelingMethod == PartLabelingMethod.LabelAllParts) { for (int n = 0; n < geo.NumGeometries; n++) { RectangleF labelBounds = PlacePolygonLabel(geo.GetGeometryN(n), e, labelSize, symb, angle); CollisionDraw(txt, g, symb, f, e, labelBounds, existingLabels, angle); } } else { double largestArea = 0; IPolygon largest = null; for (int n = 0; n < geo.NumGeometries; n++) { IPolygon pg = geo.GetGeometryN(n) as IPolygon; if (pg == null) continue; double tempArea = pg.Area; if (largestArea < tempArea) { largestArea = tempArea; largest = pg; } } RectangleF labelBounds = PlacePolygonLabel(largest, e, labelSize, symb, angle); CollisionDraw(txt, g, symb, f, e, labelBounds, existingLabels, angle); } } } /// <summary> /// This will draw any features that intersect this region. To specify the features /// directly, use OnDrawFeatures. This will not clear existing buffer content. /// For that call Initialize instead. /// </summary> /// <param name="args">A GeoArgs clarifying the transformation from geographic to image space</param> /// <param name="regions">The geographic regions to draw</param> public void DrawRegions(MapArgs args, List<Extent> regions) { if (FeatureSet == null) return; #if DEBUG var sw = new Stopwatch(); sw.Start(); #endif if (FeatureSet.IndexMode) { // First determine the number of features we are talking about based on region. List<int> drawIndices = new List<int>(); foreach (Extent region in regions) { if (region != null) { // We need to consider labels that go off the screen. Figure a region that is larger. Extent sur = region.Copy(); sur.ExpandBy(region.Width, region.Height); // Use union to prevent duplicates. No sense in drawing more than we have to. drawIndices = drawIndices.Union(FeatureSet.SelectIndices(sur)).ToList(); } } List<Rectangle> clips = args.ProjToPixel(regions); DrawFeatures(args, drawIndices, clips, true); } else { // First determine the number of features we are talking about based on region. List<IFeature> drawList = new List<IFeature>(); foreach (Extent region in regions) { if (region != null) { // We need to consider labels that go off the screen. Figure a region that is larger. Extent r = region.Copy(); r.ExpandBy(region.Width, region.Height); // Use union to prevent duplicates. No sense in drawing more than we have to. drawList = drawList.Union(FeatureSet.Select(r)).ToList(); } } List<Rectangle> clipRects = args.ProjToPixel(regions); DrawFeatures(args, drawList, clipRects, true); } #if DEBUG sw.Stop(); Debug.WriteLine("MapLabelLayer {0} DrawRegions: {1} ms", FeatureSet.Name, sw.ElapsedMilliseconds); #endif } /// <summary> /// Indicates that the drawing process has been finalized and swaps the back buffer /// to the front buffer. /// </summary> public void FinishDrawing() { OnFinishDrawing(); if (_stencil != null && _stencil != _backBuffer) _stencil.Dispose(); _stencil = _backBuffer; FeatureLayer.Invalidate(); } /// <summary> /// Rotates the label for the given feature by the angle of the LabelSymbolizer. /// </summary> /// <param name="symb">LabelSymbolizer that indicates the angle to use.</param> /// <param name="feature">Feature whose label gets rotated.</param> /// <param name="lineString"></param> /// <returns>Resulting angle in degree.</returns> private static float GetAngleToRotate(ILabelSymbolizer symb, IFeature feature, IGeometry lineString = null) { if (symb.UseAngle) { return ToSingle(symb.Angle); } else if (symb.UseLabelAngleField) { var angleField = symb.LabelAngleField; if (String.IsNullOrEmpty(angleField)) return 0; return ToSingle(feature.DataRow[angleField]); } else if (symb.UseLineOrientation) { LineString ls = lineString as LineString; if (ls != null) { ls = GetSegment(ls, symb); if (ls == null) return 0; if (symb.LineOrientation == LineOrientation.Parallel) return ToSingle(-ls.Angle); return ToSingle(-ls.Angle - 90); } } return 0; } /// <summary> /// Gets the segment of the LineString that is used to position and rotate the label. /// </summary> /// <param name="lineString">LineString to get the segment from.</param> /// <param name="symb">Symbolizer to get the LineLabelPlacement from.</param> /// <returns>Null on unnown LineLabelPlacementMethod else the calculated segment. </returns> private static LineString GetSegment(LineString lineString, ILabelSymbolizer symb) { if (lineString.Coordinates.Length <= 2) return lineString; var coords = lineString.Coordinates; switch (symb.LineLabelPlacementMethod) { case LineLabelPlacementMethod.FirstSegment: return new LineString(new[] { coords[0], coords[1] }); case LineLabelPlacementMethod.LastSegment: return new LineString(new[] { coords[coords.Length - 2], coords[coords.Length - 1] }); case LineLabelPlacementMethod.MiddleSegment: int start = (int)Math.Ceiling(coords.Length / 2D) - 1; return new LineString(new[] { coords[start], coords[start + 1] }); case LineLabelPlacementMethod.LongestSegment: double length = 0; LineString temp = null; for (int i = 0; i < coords.Length - 1; i++) { LineString l = new LineString(new[] { coords[i], coords[i + 1] }); if (l.Length > length) { length = l.Length; temp = l; } } return temp; } return null; } /// <summary> /// Fires the OnBufferChanged event /// </summary> /// <param name="clipRectangles">The Rectangle in pixels</param> protected virtual void OnBufferChanged(List<Rectangle> clipRectangles) { var h = BufferChanged; if (h != null) { h(this, new ClipArgs(clipRectangles)); } } /// <summary> /// Indiciates that whatever drawing is going to occur has finished and the contents /// are about to be flipped forward to the front buffer. /// </summary> protected virtual void OnFinishDrawing() { } /// <summary> /// Occurs when a new drawing is started, but after the BackBuffer has been established. /// </summary> protected virtual void OnStartDrawing() { } /// <summary> /// Creates the RectangleF for the label. /// </summary> /// <param name="c">Coordinate, where the label should be placed.</param> /// <param name="e">MapArgs for calculating the position of the label on the output medium.</param> /// <param name="labelSize">Function that calculates the labelSize.</param> /// <param name="symb">ILabelSymbolizer to calculate the orientation based adjustment.</param> /// <param name="angle">Angle in degree used to rotate the label.</param> /// <returns>Empty Rectangle if Coordinate is outside of the drawn extent, otherwise Rectangle needed to draw the label.</returns> private static RectangleF PlaceLabel(Coordinate c, MapArgs e, Func<SizeF> labelSize, ILabelSymbolizer symb, double angle) { if (!e.GeographicExtents.Intersects(c)) return RectangleF.Empty; var lz = labelSize(); PointF adjustment = Position(symb, lz); RotatePoint(ref adjustment, angle); //rotates the adjustment according to the given angle float x = Convert.ToSingle((c.X - e.MinX) * e.Dx) + e.ImageRectangle.X + adjustment.X; float y = Convert.ToSingle((e.MaxY - c.Y) * e.Dy) + e.ImageRectangle.Y + adjustment.Y; return new RectangleF(x, y, lz.Width, lz.Height); } /// <summary> /// Places the label according to the selected LabelPlacementMethode. /// </summary> /// <param name="lineString">LineString, whose label gets drawn.</param> /// <param name="labelSize">Function that calculates the size of the label.</param> /// <param name="e"></param> /// <param name="symb">Symbolizer to figure out the look of the label.</param> /// <param name="angle">Angle in degree the label gets rotated by.</param> /// <returns>The RectangleF that is needed to draw the label.</returns> private static RectangleF PlaceLineLabel(IGeometry lineString, Func<SizeF> labelSize, MapArgs e, ILabelSymbolizer symb, float angle) { LineString ls = lineString as LineString; if (ls == null) return Rectangle.Empty; ls = GetSegment(ls, symb); if (ls == null) return Rectangle.Empty; return PlaceLabel(ls.Centroid.Coordinate, e, labelSize, symb, angle); } private static RectangleF PlacePointLabel(IGeometry f, MapArgs e, Func<SizeF> labelSize, ILabelSymbolizer symb, float angle) { Coordinate c = f.GetGeometryN(1).Coordinates[0]; return PlaceLabel(c, e, labelSize, symb, angle); } /// <summary> /// Calculates the position of the polygon label. /// </summary> /// <param name="geom"></param> /// <param name="e"></param> /// <param name="labelSize"></param> /// <param name="symb"></param> /// <returns></returns> private static RectangleF PlacePolygonLabel(IGeometry geom, MapArgs e, Func<SizeF> labelSize, ILabelSymbolizer symb, float angle) { IPolygon pg = geom as IPolygon; if (pg == null) return RectangleF.Empty; Coordinate c; switch (symb.LabelPlacementMethod) { case LabelPlacementMethod.Centroid: c = pg.Centroid.Coordinates[0]; break; case LabelPlacementMethod.InteriorPoint: c = pg.InteriorPoint.Coordinate; break; default: c = geom.EnvelopeInternal.Centre; break; } return PlaceLabel(c, e, labelSize, symb, angle); } /// <summary> /// Calculates the adjustment of the the label's position based on the symbolizers orientation. /// </summary> /// <param name="symb">ILabelSymbolizer whose orientation should be considered.</param> /// <param name="size">Size of the label.</param> /// <returns>New label-position based on label-size and symbolizer-orientation.</returns> private static PointF Position(ILabelSymbolizer symb, SizeF size) { ContentAlignment orientation = symb.Orientation; float x = symb.OffsetX; float y = -symb.OffsetY; switch (orientation) { case ContentAlignment.TopLeft: return new PointF(-size.Width + x, -size.Height + y); case ContentAlignment.TopCenter: return new PointF(-size.Width / 2 + x, -size.Height + y); case ContentAlignment.TopRight: return new PointF(0 + x, -size.Height + y); case ContentAlignment.MiddleLeft: return new PointF(-size.Width + x, -size.Height / 2 + y); case ContentAlignment.MiddleCenter: return new PointF(-size.Width / 2 + x, -size.Height / 2 + y); case ContentAlignment.MiddleRight: return new PointF(0 + x, -size.Height / 2 + y); case ContentAlignment.BottomLeft: return new PointF(-size.Width + x, 0 + y); case ContentAlignment.BottomCenter: return new PointF(-size.Width / 2 + x, 0 + y); case ContentAlignment.BottomRight: return new PointF(0 + x, 0 + y); } return new PointF(0, 0); } private static void RotateAt(Graphics gr, float cx, float cy, float angle) { gr.ResetTransform(); gr.TranslateTransform(-cx, -cy, MatrixOrder.Append); gr.RotateTransform(angle, MatrixOrder.Append); gr.TranslateTransform(cx, cy, MatrixOrder.Append); } /// <summary> /// Rotates the given point by angle around (0,0). /// </summary> /// <param name="point">Point that gets rotated.</param> /// <param name="angle">Angle in degree.</param> private static void RotatePoint(ref PointF point, double angle) { double rad = angle * Math.PI / 180; double x = (Math.Cos(rad) * (point.X) - Math.Sin(rad) * (point.Y)); double y = (Math.Sin(rad) * (point.X) + Math.Cos(rad) * (point.Y)); point.X = (float)x; point.Y = (float)y; } /// <summary> /// Copies any current content to the back buffer so that drawing should occur on the /// back buffer (instead of the fore-buffer). Calling draw methods without /// calling this may cause exceptions. /// </summary> /// <param name="preserve">Boolean, true if the front buffer content should be copied to the back buffer /// where drawing will be taking place.</param> public void StartDrawing(bool preserve) { Bitmap backBuffer = new Bitmap(BufferRectangle.Width, BufferRectangle.Height); if (Buffer != null && preserve && Buffer.Width == backBuffer.Width && Buffer.Height == backBuffer.Height) { Graphics g = Graphics.FromImage(backBuffer); g.DrawImageUnscaled(Buffer, 0, 0); } if (BackBuffer != null && BackBuffer != Buffer) BackBuffer.Dispose(); BackBuffer = backBuffer; OnStartDrawing(); } /// <summary> /// Converts the given value to single. /// </summary> /// <param name="value">Value that gets converted to single.</param> /// <returns>0 on error else the resulting value.</returns> private static float ToSingle(object value) { try { return Convert.ToSingle(value); } catch (Exception) { return 0; } } #endregion #region Classes private class Caches { #region Fields private readonly Dictionary<Color, Pen> _pens = new Dictionary<Color, Pen>(); private readonly Dictionary<Color, Brush> _solidBrushes = new Dictionary<Color, Brush>(); private readonly Dictionary<string, Font> _symbFonts = new Dictionary<string, Font>(); #endregion #region Methods public Font GetFont(ILabelSymbolizer symb) { var fontDesc = string.Format("{0};{1};{2}", symb.FontFamily, symb.FontSize, symb.FontStyle); return _symbFonts.GetOrAdd(fontDesc, _ => symb.GetFont()); } public Pen GetPen(Color color) { return _pens.GetOrAdd(color, _ => new Pen(color)); } public Brush GetSolidBrush(Color color) { return _solidBrushes.GetOrAdd(color, _ => new SolidBrush(color)); } #endregion } #endregion } internal static class DictionaryExtensions { #region Methods public static TValue GetOrAdd<TKey, TValue>(this Dictionary<TKey, TValue> dic, TKey key, Func<TKey, TValue> valueFactory) { TValue value; if (!dic.TryGetValue(key, out value)) { value = valueFactory(key); dic.Add(key, value); } return value; } #endregion } }
using System; using System.Threading; using System.Collections.Generic; using MeidoCommon; using WebIrc; using IvionSoft; class ChannelThreadManager { public readonly Blacklist Blacklist; public readonly Whitelist Whitelist; readonly IIrcComm irc; readonly ILog log; Config conf; readonly Dictionary<string, ChannelThread> channelThreads = new Dictionary<string, ChannelThread>(StringComparer.OrdinalIgnoreCase); public ChannelThreadManager(IIrcComm irc, ILog log) { this.irc = irc; this.log = log; Blacklist = new Blacklist(); Whitelist = new Whitelist(); } public void Configure(Config conf) { this.conf = conf; lock (channelThreads) { foreach (ChannelThread thread in channelThreads.Values) { thread.WebToIrc = conf.ConstructWebToIrc(thread.Channel); } } } public void EnqueueMessage(string channel, string nick, string message) { var item = new MessageItem(nick, message); ChannelThread thread = GetThread(channel); lock (thread.ChannelLock) { thread.MessageQueue.Enqueue(item); Monitor.Pulse(thread.ChannelLock); } } public void StopAll() { lock (channelThreads) { foreach (ChannelThread thread in channelThreads.Values) { lock (thread.ChannelLock) { thread.MessageQueue.Enqueue(null); Monitor.Pulse(thread.ChannelLock); } } } } public bool DisableNick(string channel, string nick) { ChannelThread thread = GetThread(channel); // Hijack the channelLock to serialize modifications (Add/Remove) to DisabledNicks. lock (thread.ChannelLock) { return thread.DisabledNicks.Add(nick); } } public bool EnableNick(string channel, string nick) { ChannelThread thread = GetThread(channel); lock (thread.ChannelLock) { return thread.DisabledNicks.Remove(nick); } } ChannelThread GetThread(string channel) { ChannelThread thread; lock (channelThreads) { if (!channelThreads.TryGetValue(channel, out thread)) { var wIrc = conf.ConstructWebToIrc(channel); thread = new ChannelThread(irc, log, Blacklist, Whitelist, wIrc, channel); channelThreads[channel] = thread; } return thread; } } } class ChannelThread { public readonly string Channel; public volatile WebToIrc WebToIrc; public readonly object ChannelLock; public readonly Queue<MessageItem> MessageQueue; public readonly HashSet<string> DisabledNicks; readonly IIrcComm irc; readonly ILog log; readonly Blacklist blacklist; readonly Whitelist whitelist; readonly ShortHistory<string> urlHistory = new ShortHistory<string>(3); public ChannelThread(IIrcComm irc, ILog log, Blacklist black, Whitelist white, WebToIrc wIrc, string channel) { this.irc = irc; this.log = log; blacklist = black; whitelist = white; WebToIrc = wIrc; Channel = channel; MessageQueue = new Queue<MessageItem>(); DisabledNicks = new HashSet<string>(); ChannelLock = new object(); new Thread(Consume).Start(); } void Consume() { Thread.CurrentThread.Name = "URLs " + Channel; MessageItem item; while (true) { lock (ChannelLock) { while (MessageQueue.Count == 0) Monitor.Wait(ChannelLock); item = MessageQueue.Dequeue(); } if (item != null) ProcessMessage(item); // A queued null is the signal to stop, so return and stop consuming. else return; } } void ProcessMessage(MessageItem item) { string[] urls = UrlTools.Extract(item.Message); if (urls.Length > 0) { log.Verbose("{0}/{1} {2}", Channel, item.Nick, item.Message); if (!DisabledNicks.Contains(item.Nick)) { foreach (string url in urls) ProcessUrl(item.Nick, url); } else log.Message("Titling disabled for {0}.", item.Nick); } } void ProcessUrl(string nick, string url) { // If we haven't seen the URL recently. if (urlHistory.Add(url)) { bool? inWhite = whitelist.IsInList(url, Channel, nick); // Check blacklist if whitelist isn't applicable. if (inWhite == null) { if ( blacklist.IsInList(url, Channel, nick) ) log.Message("Blacklisted: {0}", url); else OutputUrl(url); } // If in whitelist, go directly to output and skip blacklist. else if (inWhite == true) OutputUrl(url); // If the whitelist was applicable, but the URL wasn't found in it. else log.Message("Not whitelisted: {0}", url); } // If we have seen the URL recently, don't output it. else log.Message("Spam suppression: {0}", url); } void OutputUrl(string url) { var result = WebToIrc.WebInfo(url); if (result.Success) { if (result.PrintTitle) irc.SendMessage(Channel, UrlTools.Filter(result.Title)); log.Message(result.Messages); log.Message("{0} -- {1}", result.Requested, result.Title); } else { log.Message( ReportError(result) ); } } string ReportError(TitlingResult result) { const string errorMsg = "Error getting {0} ({1})"; if (result.Retrieved == null) return string.Format(errorMsg, result.Requested, result.Exception.Message); else return string.Format(errorMsg, result.Retrieved, result.Exception.Message); } } class MessageItem { public string Nick { get; private set; } public string Message { get; private set; } public MessageItem(string nick, string message) { Nick = nick; Message = message; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Net.Http.Headers; using System.Runtime.InteropServices; using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle; namespace System.Net.Http { internal static class WinHttpResponseParser { private const string EncodingNameDeflate = "DEFLATE"; private const string EncodingNameGzip = "GZIP"; public static HttpResponseMessage CreateResponseMessage( WinHttpRequestState state, bool doManualDecompressionCheck) { HttpRequestMessage request = state.RequestMessage; SafeWinHttpHandle requestHandle = state.RequestHandle; CookieUsePolicy cookieUsePolicy = state.Handler.CookieUsePolicy; CookieContainer cookieContainer = state.Handler.CookieContainer; var response = new HttpResponseMessage(); bool stripEncodingHeaders = false; // Create a single buffer to use for all subsequent WinHttpQueryHeaders string interop calls. // This buffer is the length needed for WINHTTP_QUERY_RAW_HEADERS_CRLF, which includes the status line // and all headers separated by CRLF, so it should be large enough for any individual status line or header queries. int bufferLength = GetResponseHeaderCharBufferLength(requestHandle, Interop.WinHttp.WINHTTP_QUERY_RAW_HEADERS_CRLF); char[] buffer = new char[bufferLength]; // Get HTTP version, status code, reason phrase from the response headers. int versionLength = GetResponseHeader(requestHandle, Interop.WinHttp.WINHTTP_QUERY_VERSION, buffer); response.Version = CharArrayHelpers.EqualsOrdinalAsciiIgnoreCase("HTTP/1.1", buffer, 0, versionLength) ? HttpVersion.Version11 : CharArrayHelpers.EqualsOrdinalAsciiIgnoreCase("HTTP/1.0", buffer, 0, versionLength) ? HttpVersion.Version10 : HttpVersion.Unknown; response.StatusCode = (HttpStatusCode)GetResponseHeaderNumberInfo( requestHandle, Interop.WinHttp.WINHTTP_QUERY_STATUS_CODE); int reasonPhraseLength = GetResponseHeader(requestHandle, Interop.WinHttp.WINHTTP_QUERY_STATUS_TEXT, buffer); response.ReasonPhrase = reasonPhraseLength > 0 ? GetReasonPhrase(response.StatusCode, buffer, reasonPhraseLength) : string.Empty; // Create response stream and wrap it in a StreamContent object. var responseStream = new WinHttpResponseStream(requestHandle, state); state.RequestHandle = null; // ownership successfully transfered to WinHttpResponseStram. Stream decompressedStream = responseStream; if (doManualDecompressionCheck) { int contentEncodingStartIndex = 0; int contentEncodingLength = GetResponseHeader( requestHandle, Interop.WinHttp.WINHTTP_QUERY_CONTENT_ENCODING, buffer); CharArrayHelpers.Trim(buffer, ref contentEncodingStartIndex, ref contentEncodingLength); if (contentEncodingLength > 0) { if (CharArrayHelpers.EqualsOrdinalAsciiIgnoreCase( EncodingNameGzip, buffer, contentEncodingStartIndex, contentEncodingLength)) { decompressedStream = new GZipStream(responseStream, CompressionMode.Decompress); stripEncodingHeaders = true; } else if (CharArrayHelpers.EqualsOrdinalAsciiIgnoreCase( EncodingNameDeflate, buffer, contentEncodingStartIndex, contentEncodingLength)) { decompressedStream = new DeflateStream(responseStream, CompressionMode.Decompress); stripEncodingHeaders = true; } } } #if HTTP_DLL var content = new StreamContent(decompressedStream, state.CancellationToken); #else // TODO: Issue https://github.com/dotnet/corefx/issues/9071 // We'd like to be able to pass state.CancellationToken into the StreamContent so that its // SerializeToStreamAsync method can use it, but that ctor isn't public, nor is there a // SerializeToStreamAsync override that takes a CancellationToken. var content = new StreamContent(decompressedStream); #endif response.Content = content; response.RequestMessage = request; // Parse raw response headers and place them into response message. ParseResponseHeaders(requestHandle, response, buffer, stripEncodingHeaders); if (response.RequestMessage.Method != HttpMethod.Head) { state.ExpectedBytesToRead = response.Content.Headers.ContentLength; } return response; } /// <summary> /// Returns the first header or throws if the header isn't found. /// </summary> public static uint GetResponseHeaderNumberInfo(SafeWinHttpHandle requestHandle, uint infoLevel) { uint result = 0; uint resultSize = sizeof(uint); if (!Interop.WinHttp.WinHttpQueryHeaders( requestHandle, infoLevel | Interop.WinHttp.WINHTTP_QUERY_FLAG_NUMBER, Interop.WinHttp.WINHTTP_HEADER_NAME_BY_INDEX, ref result, ref resultSize, IntPtr.Zero)) { WinHttpException.ThrowExceptionUsingLastError(); } return result; } public unsafe static bool GetResponseHeader( SafeWinHttpHandle requestHandle, uint infoLevel, ref char[] buffer, ref uint index, out string headerValue) { const int StackLimit = 128; Debug.Assert(buffer == null || (buffer != null && buffer.Length > StackLimit)); int bufferLength; uint originalIndex = index; if (buffer == null) { bufferLength = StackLimit; char* pBuffer = stackalloc char[bufferLength]; if (QueryHeaders(requestHandle, infoLevel, pBuffer, ref bufferLength, ref index)) { headerValue = new string(pBuffer, 0, bufferLength); return true; } } else { bufferLength = buffer.Length; fixed (char* pBuffer = buffer) { if (QueryHeaders(requestHandle, infoLevel, pBuffer, ref bufferLength, ref index)) { headerValue = new string(pBuffer, 0, bufferLength); return true; } } } int lastError = Marshal.GetLastWin32Error(); if (lastError == Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND) { headerValue = null; return false; } if (lastError == Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER) { // WinHttpQueryHeaders may advance the index even when it fails due to insufficient buffer, // so we set the index back to its original value so we can retry retrieving the same // index again with a larger buffer. index = originalIndex; buffer = new char[bufferLength]; return GetResponseHeader(requestHandle, infoLevel, ref buffer, ref index, out headerValue); } throw WinHttpException.CreateExceptionUsingError(lastError); } /// <summary> /// Fills the buffer with the header value and returns the length, or returns 0 if the header isn't found. /// </summary> private unsafe static int GetResponseHeader(SafeWinHttpHandle requestHandle, uint infoLevel, char[] buffer) { Debug.Assert(buffer != null, "buffer must not be null."); Debug.Assert(buffer.Length > 0, "buffer must not be empty."); int bufferLength = buffer.Length; uint index = 0; fixed (char* pBuffer = buffer) { if (!QueryHeaders(requestHandle, infoLevel, pBuffer, ref bufferLength, ref index)) { int lastError = Marshal.GetLastWin32Error(); if (lastError == Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND) { return 0; } Debug.Assert(lastError != Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER, "buffer must be of sufficient size."); throw WinHttpException.CreateExceptionUsingError(lastError); } } return bufferLength; } /// <summary> /// Returns the size of the char array buffer. /// </summary> private unsafe static int GetResponseHeaderCharBufferLength(SafeWinHttpHandle requestHandle, uint infoLevel) { char* buffer = null; int bufferLength = 0; uint index = 0; if (!QueryHeaders(requestHandle, infoLevel, buffer, ref bufferLength, ref index)) { int lastError = Marshal.GetLastWin32Error(); Debug.Assert(lastError != Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND); if (lastError != Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER) { throw WinHttpException.CreateExceptionUsingError(lastError); } } return bufferLength; } private unsafe static bool QueryHeaders( SafeWinHttpHandle requestHandle, uint infoLevel, char* buffer, ref int bufferLength, ref uint index) { Debug.Assert(bufferLength >= 0, "bufferLength must not be negative."); // Convert the char buffer length to the length in bytes. uint bufferLengthInBytes = (uint)bufferLength * sizeof(char); // The WinHttpQueryHeaders buffer length is in bytes, // but the API actually returns Unicode characters. bool result = Interop.WinHttp.WinHttpQueryHeaders( requestHandle, infoLevel, Interop.WinHttp.WINHTTP_HEADER_NAME_BY_INDEX, new IntPtr(buffer), ref bufferLengthInBytes, ref index); // Convert the byte buffer length back to the length in chars. bufferLength = (int)bufferLengthInBytes / sizeof(char); return result; } private static string GetReasonPhrase(HttpStatusCode statusCode, char[] buffer, int bufferLength) { CharArrayHelpers.DebugAssertArrayInputs(buffer, 0, bufferLength); Debug.Assert(bufferLength > 0); // If it's a known reason phrase, use the known reason phrase instead of allocating a new string. string knownReasonPhrase = HttpStatusDescription.Get(statusCode); return (knownReasonPhrase != null && CharArrayHelpers.EqualsOrdinal(knownReasonPhrase, buffer, 0, bufferLength)) ? knownReasonPhrase : new string(buffer, 0, bufferLength); } private static void ParseResponseHeaders( SafeWinHttpHandle requestHandle, HttpResponseMessage response, char[] buffer, bool stripEncodingHeaders) { HttpResponseHeaders responseHeaders = response.Headers; HttpContentHeaders contentHeaders = response.Content.Headers; int bufferLength = GetResponseHeader( requestHandle, Interop.WinHttp.WINHTTP_QUERY_RAW_HEADERS_CRLF, buffer); var reader = new WinHttpResponseHeaderReader(buffer, 0, bufferLength); // Skip the first line which contains status code, etc. information that we already parsed. reader.ReadLine(); // Parse the array of headers and split them between Content headers and Response headers. string headerName; string headerValue; while (reader.ReadHeader(out headerName, out headerValue)) { if (!responseHeaders.TryAddWithoutValidation(headerName, headerValue)) { if (stripEncodingHeaders) { // Remove Content-Length and Content-Encoding headers if we are // decompressing the response stream in the handler (due to // WINHTTP not supporting it in a particular downlevel platform). // This matches the behavior of WINHTTP when it does decompression itself. if (string.Equals(HttpKnownHeaderNames.ContentLength, headerName, StringComparison.OrdinalIgnoreCase) || string.Equals(HttpKnownHeaderNames.ContentEncoding, headerName, StringComparison.OrdinalIgnoreCase)) { continue; } } // TODO: Issue #2165. Should we log if there is an error here? contentHeaders.TryAddWithoutValidation(headerName, headerValue); } } } } }
/*=================================\ * PlotterControl\Form_Dialog_MacroPackEdit.cs * * The Coestaris licenses this file to you under the MIT license. * See the LICENSE file in the project root for more information. * * Created: 27.11.2017 14:04 * Last Edited: 27.11.2017 14:12:27 *=================================*/ using CWA.Connection; using CWA.Printing.Macro; using CWA.Vectors.Document; using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.IO; using System.Linq; using System.Windows.Forms; using System.Windows.Input; using TsudaKageyu; namespace CnC_WFA { public partial class Form_Dialog_MacroPackEdit : Form { public Form_Dialog_MacroPackEdit() { InitializeComponent(); } private MacroPack main; private void UpDateListbox() { listBox_macroses.Items.Clear(); listBox_macroses.Items.AddRange(main.Elems.Select(p => p.GetMacro() == null ? new ImageListBox.ImageListBoxItem(0, Color.Red, string.Format(TB.L.Phrase["Form_MacroPack.UnableToLoadMacro"], new FileInfo(p.Path).Directory.Name + "\\" + new FileInfo(p.Path).Name)) : p.Options.Hidden ? new ImageListBox.ImageListBoxItem(0, Color.Gray, string.Format(TB.L.Phrase["Form_MacroPack.Hidden"], p.GetMacro().Name)) : new ImageListBox.ImageListBoxItem(0, Color.Black, p.GetMacro().Name)).ToArray()); } private void UpDateMacrosettings(int i) { var a = main.Elems[i]; if (a.GetMacro() == null) { int height = pictureBox1.Height; int width = pictureBox1.Width; Bitmap bmp = new Bitmap(width, height); using (Graphics gr = Graphics.FromImage(bmp)) { gr.FillRectangle(new SolidBrush(Color.FromArgb(224, 224, 224)), new RectangleF(0, 0, width, height)); var font = new Font("Cambria", 15f, FontStyle.Regular); var size = gr.MeasureString(TB.L.Phrase["Form_MacroPack.NothingToPreview"], font); gr.DrawString(TB.L.Phrase["Form_MacroPack.NothingToPreview"], font, Brushes.Red, new Point((int)(width / 2 - size.Width / 2), (int)(height / 2 - size.Height / 2))); } Image img = pictureBox1.Image; pictureBox1.Image = bmp; img?.Dispose(); return; } label_macro_name.Text = TB.L.Phrase["Form_MacroPack.Name"] + ExOperators.CutString(a.GetMacro().Name, 15); label_macro_path.Text = TB.L.Phrase["Form_MacroPack.Path"] + new FileInfo(a.Path).Directory.Name + "\\" + new FileInfo(a.Path).Name; label_macro_discr.Text = TB.L.Phrase["Form_MacroPack.Discr"] + ExOperators.CutString(a.GetMacro().Discr, 15); textBox_macro_caption.Text = a.Options.Caption; comboBox_macro_keybind.SelectedItem = a.Options.KeyBind.ToString(); comboBox_macro_charbind.Text = a.Options.CharBind.ToString(); label_macro_elemcount.Text = TB.L.Phrase["Form_MacroPack.Elements"] + a.GetMacro().Elems.Count; checkBox_isHidden.Checked = a.Options.Hidden; RenderGR(i); Render(); } private void UpDateGeneralSettings() { Text = string.Format(TB.L.Phrase["Form_MacroPack.MacroPack"], main.Name); textBox_caption.Text = main.Caption; textBox_name.Text = main.Name; richTextBox_discr.Text = main.Discr; comboBox_portname.SelectedItem = main.PortName.ToString(); comboBox_bdrate.SelectedItem = main.PortBD.ToString(); label_samples.Text = string.Format(TB.L.Phrase["Form_MacroPack.Samples"], main.Samples.Count); listBox_samples.Items.AddRange(main.Samples.ToArray()); } private void Dialog_MacroPackEdit_Load(object sender, EventArgs e) { IconExtractor ie = new IconExtractor("Lib\\IconSet.dll"); ImageList il = new ImageList(); il.Images.Add(ie.GetIcon((int)FileAssociation.IconIndex.Icon_Macros).ToBitmap()); listBox_macroses.ImageList = il; comboBox_bdrate.Items.AddRange(BdRate.GetNamesStrings()); comboBox_portname.Items.AddRange(ComPortName.GetNamesStrings()); comboBox_macro_keybind.Items.AddRange(Enum.GetNames(typeof(Key))); for (int i = 30; i <= 256; i++) comboBox_macro_charbind.Items.Add((char)i); main = new MacroPack( TB.L.Phrase["Form_MacroPack.NoName"], TB.L.Phrase["Form_MacroPack.NoDiscr"], TB.L.Phrase["Form_MacroPack.NoName"]); UpDateGeneralSettings(); } private void button_addnew_Click(object sender, EventArgs e) { if (openFileDialog_macro.ShowDialog() == DialogResult.OK) { foreach (string s in openFileDialog_macro.FileNames) { var b = new Macro(s); main.Elems.Add(new MacroPackElem(s, b.Name)); main.Elems.Last().SetMacro(b); } } UpDateListbox(); } private GraphicsPath[] GrUpped, GrNormal; private void RenderGR(int index) { var item = main.Elems[index].GetMacro(); List<GraphicsPath> grUpped = new List<GraphicsPath>(); List<GraphicsPath> grNormal = new List<GraphicsPath>(); if (main.Elems.Count == 0) { GrUpped = new GraphicsPath[0]; GrNormal = new GraphicsPath[0]; return; } float CurXPos = 0, CurYPos = 0; MacroElem b; try { b = item.Elems.FindAll(a => a.Type == MacroElemType.MoveToPoint || a.Type == MacroElemType.MoveToPointAndDelay)[0]; } catch (ArgumentOutOfRangeException) { return; } if (b == null) return; CurXPos = b.MoveToPoint.X; CurYPos = b.MoveToPoint.Y; bool isUpped = true; grUpped.Add(new GraphicsPath()); foreach (var a in item.Elems) { if (a.Type == MacroElemType.Tool || a.Type == MacroElemType.ToolAndDelay) { if (a.ToolMove > 50) { isUpped = true; grUpped.Add(new GraphicsPath()); } if (a.ToolMove < -50) { grNormal.Add(new GraphicsPath()); isUpped = false; } } if (a.Type == MacroElemType.MoveRelative || a.Type == MacroElemType.MoveRelativeAndDelay) { if (isUpped) grUpped.Last().AddLine(CurXPos, CurYPos, CurXPos + a.MoveRelative.X, CurYPos + a.MoveRelative.Y); else grNormal.Last().AddLine(CurXPos, CurYPos, CurXPos + a.MoveRelative.X, CurYPos + a.MoveRelative.Y); CurXPos += a.MoveRelative.X; CurYPos += a.MoveRelative.Y; } if (a.Type == MacroElemType.MoveToPoint || a.Type == MacroElemType.MoveToPointAndDelay) { if (isUpped) grUpped.Last().AddLine(CurXPos, CurYPos, a.MoveToPoint.X, a.MoveToPoint.Y); else grNormal.Last().AddLine(CurXPos, CurYPos, a.MoveToPoint.X, a.MoveToPoint.Y); CurXPos = a.MoveToPoint.X; CurYPos = a.MoveToPoint.Y; } } GrUpped = grUpped.ToArray(); GrNormal = grNormal.ToArray(); } private float Zoom = 221f / 1180; //TODO!!!!!!! private int LastListBoxIndex; private void Render() { int height = pictureBox1.Height; int width = pictureBox1.Width; Bitmap bmp = new Bitmap(width, height); List<GraphicsPath> grUp = new List<GraphicsPath>(); GrUpped.ToList().ForEach(p => grUp.Add((GraphicsPath)p.Clone())); List<GraphicsPath> grNo = new List<GraphicsPath>(); GrNormal.ToList().ForEach(p => grNo.Add((GraphicsPath)p.Clone())); var Matrix = new Matrix(); Matrix.Scale(Zoom, Zoom); foreach (var item in grUp) item.Transform(Matrix); foreach (var item in grNo) item.Transform(Matrix); using (Graphics gr = Graphics.FromImage(bmp)) { gr.FillRectangle(Brushes.White, new RectangleF(0, 0, width, height)); gr.DrawRectangle(new Pen(Color.Black, 1) { DashStyle = DashStyle.Dot }, 2, 2, width - 4, height - 4); foreach (var item in grUp) gr.DrawPath(new Pen(Color.Gray, 1) { DashStyle = DashStyle.Dash }, item); foreach (var item in grNo) gr.DrawPath(new Pen(Color.Black, 1), item); } Image img = pictureBox1.Image; pictureBox1.Image = bmp; if (img != null) img.Dispose(); } private void listBox_macroses_SelectedIndexChanged(object sender, EventArgs e) { bool isExists = main.Elems[listBox_macroses.SelectedIndex].GetMacro() != null; bool isNNS = listBox_macroses.SelectedIndex != -1; textBox_macro_caption.Enabled = isNNS && isExists; comboBox_macro_charbind.Enabled = isNNS && isExists; comboBox_macro_keybind.Enabled = isNNS && isExists; checkBox_isHidden.Enabled = isNNS && isExists; button_openineditor.Enabled = isNNS && isExists; button_remove.Enabled = isNNS; button_repickpath.Enabled = isNNS; if (isNNS) { LastListBoxIndex = listBox_macroses.SelectedIndex; UpDateMacrosettings(listBox_macroses.SelectedIndex); } } private void comboBox_portname_SelectedIndexChanged(object sender, EventArgs e) { main.PortName = new ComPortName(comboBox_portname.Text); } private void comboBox_bdrate_SelectedIndexChanged(object sender, EventArgs e) { main.PortBD = new BdRate(comboBox_bdrate.Text); } private void richTextBox_discr_TextChanged(object sender, EventArgs e) { main.Discr = richTextBox_discr.Text; } private void textBox_name_TextChanged(object sender, EventArgs e) { main.Name = textBox_name.Text; Text = string.Format(TB.L.Phrase["Form_MacroPack.MacroPack"], main.Name); } private void textBox_caption_TextChanged(object sender, EventArgs e) { main.Caption = textBox_caption.Text; } private void button_remove_Click(object sender, EventArgs e) { if (listBox_macroses.SelectedIndex != -1) { main.Elems.RemoveAt(listBox_macroses.SelectedIndex); listBox_macroses.Items.RemoveAt(listBox_macroses.SelectedIndex); } else MessageBox.Show( TB.L.Phrase["Form_MacroPack.SelectMacro"], TB.L.Phrase["Form_MacroPack.Error"], MessageBoxButtons.OK, MessageBoxIcon.Information); } private void button_openineditor_Click(object sender, EventArgs e) { if (listBox_macroses.SelectedIndex != -1) { FormTranslator.Translate(new Form_Macro(main.Elems[listBox_macroses.SelectedIndex].Path)).Show(); } else MessageBox.Show( TB.L.Phrase["Form_MacroPack.SelectMacro"], TB.L.Phrase["Form_MacroPack.Error"], MessageBoxButtons.OK, MessageBoxIcon.Information); } private void textBox_sample_value_TextChanged(object sender, EventArgs e) { } private void button_samples_add_Click(object sender, EventArgs e) { listBox_samples.Items.Add(textBox_sample_value.Text); main.Samples.Add(textBox_sample_value.Text); textBox_sample_value.Text = ""; label_samples.Text = string.Format(TB.L.Phrase["Form_MacroPack.Samples"], main.Samples.Count); } private void button_samples_remove_Click(object sender, EventArgs e) { if (listBox_samples.SelectedIndex != -1) { main.Samples.RemoveAt(listBox_samples.SelectedIndex); listBox_samples.Items.RemoveAt(listBox_samples.SelectedIndex); } } private void textBox_macro_caption_TextChanged(object sender, EventArgs e) { if (listBox_macroses.SelectedIndex != -1) { var a = main.Elems[listBox_macroses.SelectedIndex]; main.Elems[listBox_macroses.SelectedIndex] = new MacroPackElem() { Options = new MacroPackElemOption { Caption = textBox_caption.Text, CharBind = a.Options.CharBind, KeyBind = a.Options.KeyBind }, Path = a.Path }; main.Elems[listBox_macroses.SelectedIndex].SetMacro(a.GetMacro()); } } private void comboBox_macro_keybind_SelectedIndexChanged(object sender, EventArgs e) { if (listBox_macroses.SelectedIndex != -1) { var a = main.Elems[listBox_macroses.SelectedIndex]; main.Elems[listBox_macroses.SelectedIndex] = new MacroPackElem() { Options = new MacroPackElemOption { Caption = a.Options.Caption, CharBind = a.Options.CharBind, KeyBind = ExOperators.GetEnum<Key>(comboBox_macro_keybind.Text) }, Path = a.Path }; main.Elems[listBox_macroses.SelectedIndex].SetMacro(a.GetMacro()); } } private void comboBox_macro_charbind_SelectedIndexChanged(object sender, EventArgs e) { if (listBox_macroses.SelectedIndex != -1) { main.Elems[listBox_macroses.SelectedIndex].Options.CharBind = comboBox_macro_charbind.Text.First(); } } private void button_save_Click(object sender, EventArgs e) { saveFileDialog_mpack.InitialDirectory = new FileInfo(Application.ExecutablePath).Directory + "\\Data\\Macros"; saveFileDialog_mpack.FileName = "test.pcmpack"; if (saveFileDialog_mpack.ShowDialog() == DialogResult.OK) { main.Save(saveFileDialog_mpack.FileName); } } private void button_load_Click(object sender, EventArgs e) { openFileDialog_mpack.InitialDirectory = new FileInfo(Application.ExecutablePath).Directory + "\\Data\\Macros"; openFileDialog_mpack.FileName = "test.pcmpack"; if (openFileDialog_mpack.ShowDialog() == DialogResult.OK) { try { main = MacroPack.Load(openFileDialog_mpack.FileName); } catch { MessageBox.Show( TB.L.Phrase["Form_MacroPack.ErrorWhileLoading"], TB.L.Phrase["Form_MacroPack.Error"], MessageBoxButtons.OK, MessageBoxIcon.Error); main = new MacroPack( TB.L.Phrase["Form_MacroPack.NoName"], TB.L.Phrase["Form_MacroPack.NoDiscr"], TB.L.Phrase["Form_MacroPack.NoName"]); } UpDateGeneralSettings(); UpDateListbox(); } } private void button_repickpath_Click(object sender, EventArgs e) { if (openFileDialog_macro2.ShowDialog() == DialogResult.OK) { main.Elems[listBox_macroses.SelectedIndex] = new MacroPackElem() { Options = main.Elems[listBox_macroses.SelectedIndex].Options, Path = openFileDialog_macro2.FileName }; main.Elems[listBox_macroses.SelectedIndex].SetMacro(new Macro(openFileDialog_macro2.FileName)); UpDateMacrosettings(listBox_macroses.SelectedIndex); UpDateListbox(); } } private void button1_Click(object sender, EventArgs e) { Close(); } private void button_main_Click(object sender, EventArgs e) { tabControl1.SelectedIndex = 0; button_main.BackColor = Color.FromArgb(5, 92, 199); button_conn.BackColor = Color.FromArgb(4, 60, 130); button_macro.BackColor = Color.FromArgb(4, 60, 130); button_preset.BackColor = Color.FromArgb(4, 60, 130); } private void button_conn_Click(object sender, EventArgs e) { tabControl1.SelectedIndex = 1; button_main.BackColor = Color.FromArgb(4, 60, 130); button_conn.BackColor = Color.FromArgb(5, 92, 199); button_macro.BackColor = Color.FromArgb(4, 60, 130); button_preset.BackColor = Color.FromArgb(4, 60, 130); } private void button_macro_Click(object sender, EventArgs e) { tabControl1.SelectedIndex = 2; button_main.BackColor = Color.FromArgb(4, 60, 130); button_conn.BackColor = Color.FromArgb(4, 60, 130); button_macro.BackColor = Color.FromArgb(5, 92, 199); button_preset.BackColor = Color.FromArgb(4, 60, 130); } private void button_preset_Click(object sender, EventArgs e) { tabControl1.SelectedIndex = 3; button_main.BackColor = Color.FromArgb(4, 60, 130); button_conn.BackColor = Color.FromArgb(4, 60, 130); button_macro.BackColor = Color.FromArgb(4, 60, 130); button_preset.BackColor = Color.FromArgb(5, 92, 199); } private void checkBox_isHidden_CheckedChanged(object sender, EventArgs e) { if (listBox_macroses.SelectedIndex != -1) { main.Elems[listBox_macroses.SelectedIndex].Options.Hidden = checkBox_isHidden.Checked; UpDateListbox(); listBox_macroses.SelectedIndex = LastListBoxIndex; } } private void listBox_samples_SelectedIndexChanged(object sender, EventArgs e) { textBox_sample_value.Text = (string)listBox_samples.SelectedItem; } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; // ERROR: Not supported in C#: OptionDeclaration namespace _4PosBackOffice.NET { internal partial class frmKeyboard : System.Windows.Forms.Form { int gParentID; bool grClick; private void loadLanguage() { //frmKeyboard = No Code [Keyboard Layout Editor] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then frmKeyboard(0).Caption = rsLang("LanguageLayoutLnk_Description"): frmKeyboard.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1085; //Print|Checked if (modRecordSet.rsLang.RecordCount){cmdPrint.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdPrint.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004; //Exit|Checked if (modRecordSet.rsLang.RecordCount){cmdClose.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdClose.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} //Label1 = No Code [Keyboard Name] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then Label1.Caption = rsLang("LanguageLayoutLnk_Description"): Label1.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'"; //UPGRADE_ISSUE: Form property frmKeyboard.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"' if (modRecordSet.rsHelp.RecordCount) this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value; } private void loadKeys() { string sql = null; ADODB.Recordset rs = default(ADODB.Recordset); int x = 0; string kS = null; gridEdit.RowCount = 1; rs = modRecordSet.getRS(ref "SELECT KeyboardLayout.KeyboardLayoutID, KeyboardLayout.KeyboardLayout_Name From KeyboardLayout WHERE (((KeyboardLayout.KeyboardLayoutID)=" + gParentID + "));"); if (rs.RecordCount) { modRecordSet.cnnDB.Execute("INSERT INTO KeyboardKeyboardLayoutLnk ( KeyboardKeyboardLayoutLnk_KeyboardID, KeyboardKeyboardLayoutLnk_KeyboardLayoutID, KeyboardKeyboardLayoutLnk_Shift, KeyboardKeyboardLayoutLnk_Key, KeyboardKeyboardLayoutLnk_Description ) SELECT theJoin.KeyboardID, theJoin.KeyboardLayoutID, 0 AS Expr1, 0 AS Expr2, 'None' AS Expr3 FROM (SELECT keyboard.KeyboardID, KeyboardLayout.KeyboardLayoutID From keyboard, KeyboardLayout WHERE (((KeyboardLayout.KeyboardLayoutID)=" + gParentID + "))) AS theJoin LEFT JOIN KeyboardKeyboardLayoutLnk ON (theJoin.KeyboardID = KeyboardKeyboardLayoutLnk.KeyboardKeyboardLayoutLnk_KeyboardID) AND (theJoin.KeyboardLayoutID = KeyboardKeyboardLayoutLnk.KeyboardKeyboardLayoutLnk_KeyboardLayoutID) WHERE (((KeyboardKeyboardLayoutLnk.KeyboardKeyboardLayoutLnk_KeyboardID) Is Null));"); sql = "UPDATE KeyboardKeyboardLayoutLnk AS KeyboardKeyboardLayoutLnk_1 INNER JOIN KeyboardKeyboardLayoutLnk ON KeyboardKeyboardLayoutLnk_1.KeyboardKeyboardLayoutLnk_KeyboardID = KeyboardKeyboardLayoutLnk.KeyboardKeyboardLayoutLnk_KeyboardID SET KeyboardKeyboardLayoutLnk.KeyboardKeyboardLayoutLnk_Shift = [KeyboardKeyboardLayoutLnk_1]![KeyboardKeyboardLayoutLnk_Shift], KeyboardKeyboardLayoutLnk.KeyboardKeyboardLayoutLnk_Key = [KeyboardKeyboardLayoutLnk_1]![KeyboardKeyboardLayoutLnk_Key], KeyboardKeyboardLayoutLnk.KeyboardKeyboardLayoutLnk_Description = [KeyboardKeyboardLayoutLnk_1]![KeyboardKeyboardLayoutLnk_Description] "; sql = sql + "WHERE (((KeyboardKeyboardLayoutLnk.KeyboardKeyboardLayoutLnk_Shift)=0) AND ((KeyboardKeyboardLayoutLnk.KeyboardKeyboardLayoutLnk_Key)=0) AND ((KeyboardKeyboardLayoutLnk.KeyboardKeyboardLayoutLnk_KeyboardLayoutID)=" + gParentID + ") AND ((KeyboardKeyboardLayoutLnk_1.KeyboardKeyboardLayoutLnk_KeyboardLayoutID)=1));"; if (gParentID != 1) modRecordSet.cnnDB.Execute(sql); this.txtName.Text = rs.Fields("KeyboardLayout_Name").Value; rs = modRecordSet.getRS(ref "SELECT keyboard.*, KeyboardKeyboardLayoutLnk.* FROM KeyboardKeyboardLayoutLnk INNER JOIN keyboard ON KeyboardKeyboardLayoutLnk.KeyboardKeyboardLayoutLnk_KeyboardID = keyboard.KeyboardID Where (((KeyboardKeyboardLayoutLnk.KeyboardKeyboardLayoutLnk_KeyboardLayoutID) = " + gParentID + ")) ORDER BY keyboard.keyboard_Order, keyboard.keyboard_Name;"); gridEdit.RowCount = rs.RecordCount + 1; x = 0; while (!(rs.EOF)) { x = x + 1; gridEdit.row = x; gridEdit.Col = 0; gridEdit.Text = rs.Fields("keyboard_Name").Value; gridEdit.CellAlignment = 1; gridEdit.Col = 1; gridEdit.Text = getKeyDescription(ref rs.Fields("KeyboardKeyboardLayoutLnk_Key").Value, ref rs.Fields("KeyboardKeyboardLayoutLnk_Shift").Value); gridEdit.Col = 2; gridEdit.Text = rs.Fields("KeyboardKeyboardLayoutLnk_Shift").Value; gridEdit.Col = 3; gridEdit.Text = rs.Fields("KeyboardKeyboardLayoutLnk_Key").Value; gridEdit.set_RowData(ref gridEdit.row, ref rs.Fields("KeyboardKeyboardLayoutLnk_KeyboardID").Value); gridEdit.Col = 4; gridEdit.Text = rs.Fields("Keyboard_Order").Value; gridEdit.set_RowData(ref gridEdit.row, ref rs.Fields("KeyboardKeyboardLayoutLnk_KeyboardID").Value); gridEdit.Col = 5; if (rs.Fields("keyboard_Show").Value == true) { kS = "Yes"; } else { kS = "No"; } gridEdit.Text = Strings.UCase(kS); gridEdit.Col = 6; gridEdit.Text = rs.Fields("KeyboardID").Value; gridEdit.set_RowData(ref gridEdit.row, ref rs.Fields("KeyboardKeyboardLayoutLnk_KeyboardID").Value); rs.moveNext(); } } } private void cmdClose_Click(System.Object eventSender, System.EventArgs eventArgs) { modRecordSet.cnnDB.Execute("UPDATE KeyboardLayout SET KeyboardLayout.KeyboardLayout_Name = '" + Strings.Replace(txtName.Text, "'", "''") + "' WHERE (((KeyboardLayout.KeyboardLayoutID)=" + gParentID + "));"); this.Close(); } public void loadItem(ref int lParentID) { gParentID = lParentID; loadKeys(); loadLanguage(); ShowDialog(); } private void cmdPrint_Click(System.Object eventSender, System.EventArgs eventArgs) { ADODB.Recordset rs = default(ADODB.Recordset); string sql = null; //Dim Report As New cryKeyboardName CrystalDecisions.CrystalReports.Engine.ReportDocument Report = new CrystalDecisions.CrystalReports.Engine.ReportDocument(); Report.Load("cryKeyboardName.rpt"); System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor; rs = modRecordSet.getRS(ref "SELECT * FROM Company"); Report.SetParameterValue("txtCompanyName", rs.Fields("Company_Name")); rs.Close(); rs = modRecordSet.getRS(ref "SELECT KeyboardLayout.KeyboardLayout_Name, keyboard.keyboard_Name, KeyboardKeyboardLayoutLnk.KeyboardKeyboardLayoutLnk_Description, keyboard.keyboard_Order, keyboard.keyboard_Show FROM (KeyboardKeyboardLayoutLnk INNER JOIN keyboard ON KeyboardKeyboardLayoutLnk.KeyboardKeyboardLayoutLnk_KeyboardID = keyboard.KeyboardID) INNER JOIN KeyboardLayout ON KeyboardKeyboardLayoutLnk.KeyboardKeyboardLayoutLnk_KeyboardLayoutID = KeyboardLayout.KeyboardLayoutID Where (((KeyboardLayout.KeyboardLayoutID) = " + gParentID + ")) ORDER BY keyboard.keyboard_Order, keyboard.keyboard_Name;"); //ReportNone.Load("cryNoRecords.rpt") CrystalDecisions.CrystalReports.Engine.ReportDocument ReportNone = new CrystalDecisions.CrystalReports.Engine.ReportDocument(); ReportNone.Load("cryNoRecords.rpt"); if (rs.BOF | rs.EOF) { ReportNone.SetParameterValue("txtCompanyName", Report.ParameterFields("txtCompanyName").ToString); ReportNone.SetParameterValue("txtTitle", Report.ParameterFields("txtTitle").ToString); My.MyProject.Forms.frmReportShow.Text = ReportNone.ParameterFields("txtTitle").ToString; My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = ReportNone; My.MyProject.Forms.frmReportShow.mReport = ReportNone; My.MyProject.Forms.frmReportShow.sMode = "0"; My.MyProject.Forms.frmReportShow.CRViewer1.Refresh(); System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default; My.MyProject.Forms.frmReportShow.ShowDialog(); return; } Report.Database.Tables(0).SetDataSource(rs); Report.Database.Tables(1).SetDataSource(rs); //Report.VerifyOnEveryPrint = True My.MyProject.Forms.frmReportShow.Text = Report.ParameterFields("txtTitle").ToString; My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = Report; My.MyProject.Forms.frmReportShow.mReport = Report; My.MyProject.Forms.frmReportShow.sMode = "0"; My.MyProject.Forms.frmReportShow.CRViewer1.Refresh(); System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default; My.MyProject.Forms.frmReportShow.ShowDialog(); } private void frmKeyboard_Load(System.Object eventSender, System.EventArgs eventArgs) { grClick = true; var _with1 = gridEdit; _with1.Col = 7; _with1.RowCount = 0; System.Windows.Forms.Application.DoEvents(); _with1.RowCount = 2; _with1.FixedRows = 1; _with1.FixedCols = 0; _with1.row = 0; _with1.Col = 0; _with1.CellFontBold = true; _with1.Text = "Action"; _with1.set_ColWidth(0, 3000); _with1.CellAlignment = 3; _with1.Col = 1; _with1.CellFontBold = true; _with1.Text = "Key"; _with1.set_ColWidth(1, 800); _with1.CellAlignment = 4; _with1.Col = 2; _with1.CellFontBold = true; _with1.Text = "Special"; _with1.set_ColWidth(2, 0); _with1.CellAlignment = 1; _with1.Col = 3; _with1.CellFontBold = true; _with1.Text = "Keycode"; _with1.set_ColWidth(3, 0); _with1.CellAlignment = 1; _with1.Col = 4; _with1.CellFontBold = true; _with1.Text = "Display"; _with1.set_ColWidth(4, 800); _with1.CellAlignment = 1; _with1.Col = 5; _with1.CellFontBold = true; _with1.Text = "Show"; _with1.set_ColWidth(5, 800); _with1.CellAlignment = 1; _with1.Col = 6; _with1.CellFontBold = true; _with1.Text = "KEY"; _with1.set_ColWidth(6, 0); _with1.CellAlignment = 1; } public object getKeyDescription(ref short KeyCode, ref short Shift) { string lShift = null; string lKey = null; switch (KeyCode) { case 16: case 17: case 18: break; case 112: case 113: case 114: case 115: case 116: case 117: case 118: case 119: case 120: case 121: case 122: case 123: lKey = "F" + KeyCode - 111; break; case 37: lKey = "Left"; break; case 38: lKey = "Up"; break; case 39: lKey = "Right"; break; case 40: lKey = "Down"; break; case 27: lKey = "Esc"; break; case 13: lKey = "Enter"; break; case 35: lKey = "End"; break; case 34: lKey = "PgDn"; break; case 33: lKey = "PgUp"; break; case 36: lKey = "Home"; break; case 46: lKey = "Del"; break; case 45: lKey = "Ins"; break; case 19: lKey = "Pause"; break; case 9: lKey = "Tab"; break; case 8: lKey = "Back Space"; break; default: lKey = Strings.Chr(KeyCode); break; } switch (Shift) { case 1: lShift = "Shift+"; break; case 2: lShift = "Ctrl+"; break; case 4: lShift = "Alt+"; break; default: lShift = ""; break; } return lShift + lKey; } private void gridEdit_ClickEvent(System.Object eventSender, KeyEventArgs eventArgs) { MsgBoxResult inres = default(MsgBoxResult); int k_ID = 0; string lName = null; string kView = null; short inRe = 0; short lKey = 0; short lShift = 0; ADODB.Recordset rs = default(ADODB.Recordset); if (grClick == true) { grClick = false; return; } kView = Strings.UCase(Strings.Trim(gridEdit.get_TextMatrix(ref gridEdit.row, ref gridEdit.Col))); if (kView == "YES" | kView == "NO") { k_ID = Conversion.Val(gridEdit.get_TextMatrix(ref gridEdit.row, ref gridEdit.Col + 1)); if (kView == "YES") { inres = Interaction.MsgBox("Do you want to hide Key on Keyboard", MsgBoxStyle.ApplicationModal + MsgBoxStyle.YesNo + MsgBoxStyle.Question, _4PosBackOffice.NET.My.MyProject.Application.Info.Title); if (inres == MsgBoxResult.Yes) { modRecordSet.cnnDB.Execute("UPDATE Keyboard SET Keyboard_Show = 0 WHERE KeyboardID = " + k_ID); gridEdit.set_TextMatrix(ref gridEdit.row, ref gridEdit.Col, ref "NO"); } } else if (kView == "NO") { inres = Interaction.MsgBox("Do you want to show Key on Keyboard", MsgBoxStyle.ApplicationModal + MsgBoxStyle.YesNo + MsgBoxStyle.Question, _4PosBackOffice.NET.My.MyProject.Application.Info.Title); if (inres == MsgBoxResult.Yes) { modRecordSet.cnnDB.Execute("UPDATE Keyboard SET Keyboard_Show = 1 WHERE KeyboardID = " + k_ID); gridEdit.set_TextMatrix(ref gridEdit.row, ref gridEdit.Col, ref "YES"); } } return; } lName = gridEdit.get_TextMatrix(ref gridEdit.row, ref 0); k_ID = Conversion.Val(gridEdit.get_TextMatrix(ref gridEdit.row, ref 6)); //Do Display Option..... if (gridEdit.Col > 0) { if (Conversion.Val(kView) > 0) { if (Conversion.Val(kView) < 100) { My.MyProject.Forms.frmChangeDisplay.lblName.Text = lName; My.MyProject.Forms.frmChangeDisplay.txtNumber.Text = Strings.Trim(kView); My.MyProject.Forms.frmChangeDisplay.ShowDialog(); if (modApplication.InKeyboard == 200) { } else { modRecordSet.cnnDB.Execute("UPDATE Keyboard SET keyboard_Order = " + modApplication.InKeyboard + " WHERE KeyboardID = " + k_ID); var _with2 = gridEdit; _with2.Text = Conversion.Str(modApplication.InKeyboard); loadKeys(); } } return; } } lName = gridEdit.get_TextMatrix(ref gridEdit.row, ref 0); lKey = Convert.ToInt16(gridEdit.get_TextMatrix(ref gridEdit.row, ref 3)); lShift = Convert.ToInt16(gridEdit.get_TextMatrix(ref gridEdit.row, ref 2)); My.MyProject.Forms.frmKeyboardGet.getKeyboardValue(ref lName, ref lKey, ref lShift); if (lKey != 0) { //Set rs = getRS("SELECT keyboard.* From keyboard WHERE (((keyboard.keyboard_Shift)=" & lShift & ") AND ((keyboard.keyboard_Key)=" & lKey & "));") rs = modRecordSet.getRS(ref "SELECT keyboard.keyboardID, keyboard.keyboard_Name, KeyboardKeyboardLayoutLnk.* FROM KeyboardKeyboardLayoutLnk INNER JOIN keyboard ON KeyboardKeyboardLayoutLnk.KeyboardKeyboardLayoutLnk_KeyboardID = keyboard.KeyboardID Where (((KeyboardKeyboardLayoutLnk.KeyboardKeyboardLayoutLnk_KeyboardLayoutID) = " + gParentID + ") AND ((KeyboardKeyboardLayoutLnk.KeyboardKeyboardLayoutLnk_Shift)=" + lShift + ") AND ((KeyboardKeyboardLayoutLnk.KeyboardKeyboardLayoutLnk_Key)=" + lKey + "))"); if (rs.RecordCount) { if (rs.Fields("KeyboardID").Value == gridEdit.get_RowData(ref gridEdit.row)) { } else { Interaction.MsgBox("Cannot allocate this key as it is allocated to '" + rs.Fields("keyboard_Name").Value + "!", MsgBoxStyle.Exclamation, "KEYBOARD LAYOUT"); } } else { lName = getKeyDescription(ref lKey, ref lShift); modRecordSet.cnnDB.Execute("UPDATE KeyboardKeyboardLayoutLnk SET KeyboardKeyboardLayoutLnk.KeyboardKeyboardLayoutLnk_Shift = " + lShift + ", KeyboardKeyboardLayoutLnk.KeyboardKeyboardLayoutLnk_Key = " + lKey + ", KeyboardKeyboardLayoutLnk.KeyboardKeyboardLayoutLnk_Description = '" + lName + "' WHERE (((KeyboardKeyboardLayoutLnk.KeyboardKeyboardLayoutLnk_KeyboardLayoutID)=" + gParentID + ") AND ((KeyboardKeyboardLayoutLnk.KeyboardKeyboardLayoutLnk_KeyboardID)=" + gridEdit.get_RowData(ref gridEdit.row) + "));"); gridEdit.set_TextMatrix(ref gridEdit.row, ref 3, ref lKey); gridEdit.set_TextMatrix(ref gridEdit.row, ref 2, ref lShift); gridEdit.set_TextMatrix(ref gridEdit.row, ref 1, ref lName); } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // ConcurrentStack.cs // // A lock-free, concurrent stack primitive, and its associated debugger view type. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace System.Collections.Concurrent { // A stack that uses CAS operations internally to maintain thread-safety in a lock-free // manner. Attempting to push or pop concurrently from the stack will not trigger waiting, // although some optimistic concurrency and retry is used, possibly leading to lack of // fairness and/or livelock. The stack uses spinning and backoff to add some randomization, // in hopes of statistically decreasing the possibility of livelock. // // Note that we currently allocate a new node on every push. This avoids having to worry // about potential ABA issues, since the CLR GC ensures that a memory address cannot be // reused before all references to it have died. /// <summary> /// Represents a thread-safe last-in, first-out collection of objects. /// </summary> /// <typeparam name="T">Specifies the type of elements in the stack.</typeparam> /// <remarks> /// All public and protected members of <see cref="ConcurrentStack{T}"/> are thread-safe and may be used /// concurrently from multiple threads. /// </remarks> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(IProducerConsumerCollectionDebugView<>))] public class ConcurrentStack<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T> { /// <summary> /// A simple (internal) node type used to store elements of concurrent stacks and queues. /// </summary> private class Node { internal readonly T _value; // Value of the node. internal Node _next; // Next pointer. /// <summary> /// Constructs a new node with the specified value and no next node. /// </summary> /// <param name="value">The value of the node.</param> internal Node(T value) { _value = value; _next = null; } } private volatile Node _head; // The stack is a singly linked list, and only remembers the head. private const int BACKOFF_MAX_YIELDS = 8; // Arbitrary number to cap backoff. /// <summary> /// Initializes a new instance of the <see cref="ConcurrentStack{T}"/> /// class. /// </summary> public ConcurrentStack() { } /// <summary> /// Initializes a new instance of the <see cref="ConcurrentStack{T}"/> /// class that contains elements copied from the specified collection /// </summary> /// <param name="collection">The collection whose elements are copied to the new <see /// cref="ConcurrentStack{T}"/>.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="collection"/> argument is /// null.</exception> public ConcurrentStack(IEnumerable<T> collection) { if (collection == null) { throw new ArgumentNullException("collection"); } InitializeFromCollection(collection); } /// <summary> /// Initializes the contents of the stack from an existing collection. /// </summary> /// <param name="collection">A collection from which to copy elements.</param> private void InitializeFromCollection(IEnumerable<T> collection) { // We just copy the contents of the collection to our stack. Node lastNode = null; foreach (T element in collection) { Node newNode = new Node(element); newNode._next = lastNode; lastNode = newNode; } _head = lastNode; } /// <summary> /// Gets a value that indicates whether the <see cref="ConcurrentStack{T}"/> is empty. /// </summary> /// <value>true if the <see cref="ConcurrentStack{T}"/> is empty; otherwise, false.</value> /// <remarks> /// For determining whether the collection contains any items, use of this property is recommended /// rather than retrieving the number of items from the <see cref="Count"/> property and comparing it /// to 0. However, as this collection is intended to be accessed concurrently, it may be the case /// that another thread will modify the collection after <see cref="IsEmpty"/> returns, thus invalidating /// the result. /// </remarks> public bool IsEmpty { // Checks whether the stack is empty. Clearly the answer may be out of date even prior to // the function returning (i.e. if another thread concurrently adds to the stack). It does // guarantee, however, that, if another thread does not mutate the stack, a subsequent call // to TryPop will return true -- i.e. it will also read the stack as non-empty. get { return _head == null; } } /// <summary> /// Gets the number of elements contained in the <see cref="ConcurrentStack{T}"/>. /// </summary> /// <value>The number of elements contained in the <see cref="ConcurrentStack{T}"/>.</value> /// <remarks> /// For determining whether the collection contains any items, use of the <see cref="IsEmpty"/> /// property is recommended rather than retrieving the number of items from the <see cref="Count"/> /// property and comparing it to 0. /// </remarks> public int Count { // Counts the number of entries in the stack. This is an O(n) operation. The answer may be out // of date before returning, but guarantees to return a count that was once valid. Conceptually, // the implementation snaps a copy of the list and then counts the entries, though physically // this is not what actually happens. get { int count = 0; // Just whip through the list and tally up the number of nodes. We rely on the fact that // node next pointers are immutable after being enqueued for the first time, even as // they are being dequeued. If we ever changed this (e.g. to pool nodes somehow), // we'd need to revisit this implementation. for (Node curr = _head; curr != null; curr = curr._next) { count++; //we don't handle overflow, to be consistent with existing generic collection types in CLR } return count; } } /// <summary> /// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is /// synchronized with the SyncRoot. /// </summary> /// <value>true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized /// with the SyncRoot; otherwise, false. For <see cref="ConcurrentStack{T}"/>, this property always /// returns false.</value> bool ICollection.IsSynchronized { // Gets a value indicating whether access to this collection is synchronized. Always returns // false. The reason is subtle. While access is in face thread safe, it's not the case that // locking on the SyncRoot would have prevented concurrent pushes and pops, as this property // would typically indicate; that's because we internally use CAS operations vs. true locks. get { return false; } } /// <summary> /// Gets an object that can be used to synchronize access to the <see /// cref="T:System.Collections.ICollection"/>. This property is not supported. /// </summary> /// <exception cref="T:System.NotSupportedException">The SyncRoot property is not supported</exception> object ICollection.SyncRoot { get { throw new NotSupportedException(SR.ConcurrentCollection_SyncRoot_NotSupported); } } /// <summary> /// Removes all objects from the <see cref="ConcurrentStack{T}"/>. /// </summary> public void Clear() { // Clear the list by setting the head to null. We don't need to use an atomic // operation for this: anybody who is mutating the head by pushing or popping // will need to use an atomic operation to guarantee they serialize and don't // overwrite our setting of the head to null. _head = null; } /// <summary> /// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an <see /// cref="T:System.Array"/>, starting at a particular /// <see cref="T:System.Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of /// the elements copied from the /// <see cref="ConcurrentStack{T}"/>. The <see cref="T:System.Array"/> must /// have zero-based indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying /// begins.</param> /// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in /// Visual Basic).</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than /// zero.</exception> /// <exception cref="ArgumentException"> /// <paramref name="array"/> is multidimensional. -or- /// <paramref name="array"/> does not have zero-based indexing. -or- /// <paramref name="index"/> is equal to or greater than the length of the <paramref name="array"/> /// -or- The number of elements in the source <see cref="T:System.Collections.ICollection"/> is /// greater than the available space from <paramref name="index"/> to the end of the destination /// <paramref name="array"/>. -or- The type of the source <see /// cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the /// destination <paramref name="array"/>. /// </exception> void ICollection.CopyTo(Array array, int index) { // Validate arguments. if (array == null) { throw new ArgumentNullException("array"); } // We must be careful not to corrupt the array, so we will first accumulate an // internal list of elements that we will then copy to the array. This requires // some extra allocation, but is necessary since we don't know up front whether // the array is sufficiently large to hold the stack's contents. ((ICollection)ToList()).CopyTo(array, index); } /// <summary> /// Copies the <see cref="ConcurrentStack{T}"/> elements to an existing one-dimensional <see /// cref="T:System.Array"/>, starting at the specified array index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of /// the elements copied from the /// <see cref="ConcurrentStack{T}"/>. The <see cref="T:System.Array"/> must have zero-based /// indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying /// begins.</param> /// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in /// Visual Basic).</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than /// zero.</exception> /// <exception cref="ArgumentException"><paramref name="index"/> is equal to or greater than the /// length of the <paramref name="array"/> /// -or- The number of elements in the source <see cref="ConcurrentStack{T}"/> is greater than the /// available space from <paramref name="index"/> to the end of the destination <paramref /// name="array"/>. /// </exception> public void CopyTo(T[] array, int index) { if (array == null) { throw new ArgumentNullException("array"); } // We must be careful not to corrupt the array, so we will first accumulate an // internal list of elements that we will then copy to the array. This requires // some extra allocation, but is necessary since we don't know up front whether // the array is sufficiently large to hold the stack's contents. ToList().CopyTo(array, index); } #pragma warning disable 0420 // No warning for Interlocked.xxx if compiled with new managed compiler (Roslyn) /// <summary> /// Inserts an object at the top of the <see cref="ConcurrentStack{T}"/>. /// </summary> /// <param name="item">The object to push onto the <see cref="ConcurrentStack{T}"/>. The value can be /// a null reference (Nothing in Visual Basic) for reference types. /// </param> public void Push(T item) { // Pushes a node onto the front of the stack thread-safely. Internally, this simply // swaps the current head pointer using a (thread safe) CAS operation to accomplish // lock freedom. If the CAS fails, we add some back off to statistically decrease // contention at the head, and then go back around and retry. Node newNode = new Node(item); newNode._next = _head; if (Interlocked.CompareExchange(ref _head, newNode, newNode._next) == newNode._next) { return; } // If we failed, go to the slow path and loop around until we succeed. PushCore(newNode, newNode); } /// <summary> /// Inserts multiple objects at the top of the <see cref="ConcurrentStack{T}"/> atomically. /// </summary> /// <param name="items">The objects to push onto the <see cref="ConcurrentStack{T}"/>.</param> /// <exception cref="ArgumentNullException"><paramref name="items"/> is a null reference /// (Nothing in Visual Basic).</exception> /// <remarks> /// When adding multiple items to the stack, using PushRange is a more efficient /// mechanism than using <see cref="Push"/> one item at a time. Additionally, PushRange /// guarantees that all of the elements will be added atomically, meaning that no other threads will /// be able to inject elements between the elements being pushed. Items at lower indices in /// the <paramref name="items"/> array will be pushed before items at higher indices. /// </remarks> public void PushRange(T[] items) { if (items == null) { throw new ArgumentNullException("items"); } PushRange(items, 0, items.Length); } /// <summary> /// Inserts multiple objects at the top of the <see cref="ConcurrentStack{T}"/> atomically. /// </summary> /// <param name="items">The objects to push onto the <see cref="ConcurrentStack{T}"/>.</param> /// <param name="startIndex">The zero-based offset in <paramref name="items"/> at which to begin /// inserting elements onto the top of the <see cref="ConcurrentStack{T}"/>.</param> /// <param name="count">The number of elements to be inserted onto the top of the <see /// cref="ConcurrentStack{T}"/>.</param> /// <exception cref="ArgumentNullException"><paramref name="items"/> is a null reference /// (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="startIndex"/> or <paramref /// name="count"/> is negative. Or <paramref name="startIndex"/> is greater than or equal to the length /// of <paramref name="items"/>.</exception> /// <exception cref="ArgumentException"><paramref name="startIndex"/> + <paramref name="count"/> is /// greater than the length of <paramref name="items"/>.</exception> /// <remarks> /// When adding multiple items to the stack, using PushRange is a more efficient /// mechanism than using <see cref="Push"/> one item at a time. Additionally, PushRange /// guarantees that all of the elements will be added atomically, meaning that no other threads will /// be able to inject elements between the elements being pushed. Items at lower indices in the /// <paramref name="items"/> array will be pushed before items at higher indices. /// </remarks> public void PushRange(T[] items, int startIndex, int count) { ValidatePushPopRangeInput(items, startIndex, count); // No op if the count is zero if (count == 0) return; Node head, tail; head = tail = new Node(items[startIndex]); for (int i = startIndex + 1; i < startIndex + count; i++) { Node node = new Node(items[i]); node._next = head; head = node; } tail._next = _head; if (Interlocked.CompareExchange(ref _head, head, tail._next) == tail._next) { return; } // If we failed, go to the slow path and loop around until we succeed. PushCore(head, tail); } /// <summary> /// Push one or many nodes into the stack, if head and tails are equal then push one node to the stack other wise push the list between head /// and tail to the stack /// </summary> /// <param name="head">The head pointer to the new list</param> /// <param name="tail">The tail pointer to the new list</param> private void PushCore(Node head, Node tail) { SpinWait spin = new SpinWait(); // Keep trying to CAS the exising head with the new node until we succeed. do { spin.SpinOnce(); // Reread the head and link our new node. tail._next = _head; } while (Interlocked.CompareExchange( ref _head, head, tail._next) != tail._next); #if FEATURE_TRACING if (CDSCollectionETWBCLProvider.Log.IsEnabled()) { CDSCollectionETWBCLProvider.Log.ConcurrentStack_FastPushFailed(spin.Count); } #endif } /// <summary> /// Local helper function to validate the Pop Push range methods input /// </summary> private static void ValidatePushPopRangeInput(T[] items, int startIndex, int count) { if (items == null) { throw new ArgumentNullException("items"); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ConcurrentStack_PushPopRange_CountOutOfRange); } int length = items.Length; if (startIndex >= length || startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex", SR.ConcurrentStack_PushPopRange_StartOutOfRange); } if (length - count < startIndex) //instead of (startIndex + count > items.Length) to prevent overflow { throw new ArgumentException(SR.ConcurrentStack_PushPopRange_InvalidCount); } } /// <summary> /// Attempts to add an object to the <see /// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>. /// </summary> /// <param name="item">The object to add to the <see /// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>. The value can be a null /// reference (Nothing in Visual Basic) for reference types. /// </param> /// <returns>true if the object was added successfully; otherwise, false.</returns> /// <remarks>For <see cref="ConcurrentStack{T}"/>, this operation /// will always insert the object onto the top of the <see cref="ConcurrentStack{T}"/> /// and return true.</remarks> bool IProducerConsumerCollection<T>.TryAdd(T item) { Push(item); return true; } /// <summary> /// Attempts to return an object from the top of the <see cref="ConcurrentStack{T}"/> /// without removing it. /// </summary> /// <param name="result">When this method returns, <paramref name="result"/> contains an object from /// the top of the <see cref="T:System.Collections.Concurrent.ConccurrentStack{T}"/> or an /// unspecified value if the operation failed.</param> /// <returns>true if and object was returned successfully; otherwise, false.</returns> public bool TryPeek(out T result) { Node head = _head; // If the stack is empty, return false; else return the element and true. if (head == null) { result = default(T); return false; } else { result = head._value; return true; } } /// <summary> /// Attempts to pop and return the object at the top of the <see cref="ConcurrentStack{T}"/>. /// </summary> /// <param name="result"> /// When this method returns, if the operation was successful, <paramref name="result"/> contains the /// object removed. If no object was available to be removed, the value is unspecified. /// </param> /// <returns>true if an element was removed and returned from the top of the <see /// cref="ConcurrentStack{T}"/> /// succesfully; otherwise, false.</returns> public bool TryPop(out T result) { Node head = _head; //stack is empty if (head == null) { result = default(T); return false; } if (Interlocked.CompareExchange(ref _head, head._next, head) == head) { result = head._value; return true; } // Fall through to the slow path. return TryPopCore(out result); } /// <summary> /// Attempts to pop and return multiple objects from the top of the <see cref="ConcurrentStack{T}"/> /// atomically. /// </summary> /// <param name="items"> /// The <see cref="T:System.Array"/> to which objects popped from the top of the <see /// cref="ConcurrentStack{T}"/> will be added. /// </param> /// <returns>The number of objects successfully popped from the top of the <see /// cref="ConcurrentStack{T}"/> and inserted in /// <paramref name="items"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="items"/> is a null argument (Nothing /// in Visual Basic).</exception> /// <remarks> /// When popping multiple items, if there is little contention on the stack, using /// TryPopRange can be more efficient than using <see cref="TryPop"/> /// once per item to be removed. Nodes fill the <paramref name="items"/> /// with the first node to be popped at the startIndex, the second node to be popped /// at startIndex + 1, and so on. /// </remarks> public int TryPopRange(T[] items) { if (items == null) { throw new ArgumentNullException("items"); } return TryPopRange(items, 0, items.Length); } /// <summary> /// Attempts to pop and return multiple objects from the top of the <see cref="ConcurrentStack{T}"/> /// atomically. /// </summary> /// <param name="items"> /// The <see cref="T:System.Array"/> to which objects popped from the top of the <see /// cref="ConcurrentStack{T}"/> will be added. /// </param> /// <param name="startIndex">The zero-based offset in <paramref name="items"/> at which to begin /// inserting elements from the top of the <see cref="ConcurrentStack{T}"/>.</param> /// <param name="count">The number of elements to be popped from top of the <see /// cref="ConcurrentStack{T}"/> and inserted into <paramref name="items"/>.</param> /// <returns>The number of objects successfully popped from the top of /// the <see cref="ConcurrentStack{T}"/> and inserted in <paramref name="items"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="items"/> is a null reference /// (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="startIndex"/> or <paramref /// name="count"/> is negative. Or <paramref name="startIndex"/> is greater than or equal to the length /// of <paramref name="items"/>.</exception> /// <exception cref="ArgumentException"><paramref name="startIndex"/> + <paramref name="count"/> is /// greater than the length of <paramref name="items"/>.</exception> /// <remarks> /// When popping multiple items, if there is little contention on the stack, using /// TryPopRange can be more efficient than using <see cref="TryPop"/> /// once per item to be removed. Nodes fill the <paramref name="items"/> /// with the first node to be popped at the startIndex, the second node to be popped /// at startIndex + 1, and so on. /// </remarks> public int TryPopRange(T[] items, int startIndex, int count) { ValidatePushPopRangeInput(items, startIndex, count); // No op if the count is zero if (count == 0) return 0; Node poppedHead; int nodesCount = TryPopCore(count, out poppedHead); if (nodesCount > 0) { CopyRemovedItems(poppedHead, items, startIndex, nodesCount); } return nodesCount; } /// <summary> /// Local helper function to Pop an item from the stack, slow path /// </summary> /// <param name="result">The popped item</param> /// <returns>True if succeeded, false otherwise</returns> private bool TryPopCore(out T result) { Node poppedNode; if (TryPopCore(1, out poppedNode) == 1) { result = poppedNode._value; return true; } result = default(T); return false; } /// <summary> /// Slow path helper for TryPop. This method assumes an initial attempt to pop an element /// has already occurred and failed, so it begins spinning right away. /// </summary> /// <param name="count">The number of items to pop.</param> /// <param name="poppedHead"> /// When this method returns, if the pop succeeded, contains the removed object. If no object was /// available to be removed, the value is unspecified. This parameter is passed uninitialized. /// </param> /// <returns>True if an element was removed and returned; otherwise, false.</returns> private int TryPopCore(int count, out Node poppedHead) { SpinWait spin = new SpinWait(); // Try to CAS the head with its current next. We stop when we succeed or // when we notice that the stack is empty, whichever comes first. Node head; Node next; int backoff = 1; Random r = new Random(Environment.TickCount & Int32.MaxValue); // avoid the case where TickCount could return Int32.MinValue while (true) { head = _head; // Is the stack empty? if (head == null) { #if FEATURE_TRACING if (count == 1 && CDSCollectionETWBCLProvider.Log.IsEnabled()) { CDSCollectionETWBCLProvider.Log.ConcurrentStack_FastPopFailed(spin.Count); } #endif poppedHead = null; return 0; } next = head; int nodesCount = 1; for (; nodesCount < count && next._next != null; nodesCount++) { next = next._next; } // Try to swap the new head. If we succeed, break out of the loop. if (Interlocked.CompareExchange(ref _head, next._next, head) == head) { #if FEATURE_TRACING if (count == 1 && CDSCollectionETWBCLProvider.Log.IsEnabled()) { CDSCollectionETWBCLProvider.Log.ConcurrentStack_FastPopFailed(spin.Count); } #endif // Return the popped Node. poppedHead = head; return nodesCount; } // We failed to CAS the new head. Spin briefly and retry. for (int i = 0; i < backoff; i++) { spin.SpinOnce(); } backoff = spin.NextSpinWillYield ? r.Next(1, BACKOFF_MAX_YIELDS) : backoff * 2; } } #pragma warning restore 0420 /// <summary> /// Local helper function to copy the poped elements into a given collection /// </summary> /// <param name="head">The head of the list to be copied</param> /// <param name="collection">The collection to place the popped items in</param> /// <param name="startIndex">the beginning of index of where to place the popped items</param> /// <param name="nodesCount">The number of nodes.</param> private static void CopyRemovedItems(Node head, T[] collection, int startIndex, int nodesCount) { Node current = head; for (int i = startIndex; i < startIndex + nodesCount; i++) { collection[i] = current._value; current = current._next; } } /// <summary> /// Attempts to remove and return an object from the <see /// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>. /// </summary> /// <param name="item"> /// When this method returns, if the operation was successful, <paramref name="item"/> contains the /// object removed. If no object was available to be removed, the value is unspecified. /// </param> /// <returns>true if an element was removed and returned succesfully; otherwise, false.</returns> /// <remarks>For <see cref="ConcurrentStack{T}"/>, this operation will attempt to pope the object at /// the top of the <see cref="ConcurrentStack{T}"/>. /// </remarks> bool IProducerConsumerCollection<T>.TryTake(out T item) { return TryPop(out item); } /// <summary> /// Copies the items stored in the <see cref="ConcurrentStack{T}"/> to a new array. /// </summary> /// <returns>A new array containing a snapshot of elements copied from the <see /// cref="ConcurrentStack{T}"/>.</returns> public T[] ToArray() { return ToList().ToArray(); } /// <summary> /// Returns an array containing a snapshot of the list's contents, using /// the target list node as the head of a region in the list. /// </summary> /// <returns>An array of the list's contents.</returns> private List<T> ToList() { List<T> list = new List<T>(); Node curr = _head; while (curr != null) { list.Add(curr._value); curr = curr._next; } return list; } /// <summary> /// Returns an enumerator that iterates through the <see cref="ConcurrentStack{T}"/>. /// </summary> /// <returns>An enumerator for the <see cref="ConcurrentStack{T}"/>.</returns> /// <remarks> /// The enumeration represents a moment-in-time snapshot of the contents /// of the stack. It does not reflect any updates to the collection after /// <see cref="GetEnumerator"/> was called. The enumerator is safe to use /// concurrently with reads from and writes to the stack. /// </remarks> public IEnumerator<T> GetEnumerator() { // Returns an enumerator for the stack. This effectively takes a snapshot // of the stack's contents at the time of the call, i.e. subsequent modifications // (pushes or pops) will not be reflected in the enumerator's contents. //If we put yield-return here, the iterator will be lazily evaluated. As a result a snapshot of //the stack is not taken when GetEnumerator is initialized but when MoveNext() is first called. //This is inconsistent with existing generic collections. In order to prevent it, we capture the //value of _head in a buffer and call out to a helper method return GetEnumerator(_head); } private IEnumerator<T> GetEnumerator(Node head) { Node current = head; while (current != null) { yield return current._value; current = current._next; } } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns>An <see cref="T:System.Collections.IEnumerator"/> that can be used to iterate through /// the collection.</returns> /// <remarks> /// The enumeration represents a moment-in-time snapshot of the contents of the stack. It does not /// reflect any updates to the collection after /// <see cref="GetEnumerator"/> was called. The enumerator is safe to use concurrently with reads /// from and writes to the stack. /// </remarks> IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<T>)this).GetEnumerator(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using Microsoft.CSharp.RuntimeBinder.Errors; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal sealed class TypeManager { private BSYMMGR _BSymmgr; private PredefinedTypes _predefTypes; private readonly TypeFactory _typeFactory; private readonly TypeTable _typeTable; private SymbolTable _symbolTable; // Special types private readonly VoidType _voidType; private readonly NullType _nullType; private readonly OpenTypePlaceholderType _typeUnit; private readonly BoundLambdaType _typeAnonMeth; private readonly MethodGroupType _typeMethGrp; private readonly ArgumentListType _argListType; private readonly ErrorType _errorType; private readonly StdTypeVarColl _stvcMethod; private readonly StdTypeVarColl _stvcClass; public TypeManager() { _predefTypes = null; // Initialized via the Init call. _BSymmgr = null; // Initialized via the Init call. _typeFactory = new TypeFactory(); _typeTable = new TypeTable(); // special types with their own symbol kind. _errorType = _typeFactory.CreateError(null, null, null, null, null); _voidType = _typeFactory.CreateVoid(); _nullType = _typeFactory.CreateNull(); _typeUnit = _typeFactory.CreateUnit(); _typeAnonMeth = _typeFactory.CreateAnonMethod(); _typeMethGrp = _typeFactory.CreateMethodGroup(); _argListType = _typeFactory.CreateArgList(); InitType(_errorType); _errorType.SetErrors(true); InitType(_voidType); InitType(_nullType); InitType(_typeUnit); InitType(_typeAnonMeth); InitType(_typeMethGrp); _stvcMethod = new StdTypeVarColl(); _stvcClass = new StdTypeVarColl(); } public void InitTypeFactory(SymbolTable table) { _symbolTable = table; } private void InitType(CType at) { } public static bool TypeContainsAnonymousTypes(CType type) { CType ctype = (CType)type; LRecurse: // Label used for "tail" recursion. switch (ctype.GetTypeKind()) { default: Debug.Assert(false, "Bad Symbol kind in TypeContainsAnonymousTypes"); return false; case TypeKind.TK_NullType: case TypeKind.TK_VoidType: case TypeKind.TK_NullableType: case TypeKind.TK_TypeParameterType: case TypeKind.TK_UnboundLambdaType: case TypeKind.TK_MethodGroupType: return false; case TypeKind.TK_ArrayType: case TypeKind.TK_ParameterModifierType: case TypeKind.TK_PointerType: ctype = (CType)ctype.GetBaseOrParameterOrElementType(); goto LRecurse; case TypeKind.TK_AggregateType: if (ctype.AsAggregateType().getAggregate().IsAnonymousType()) { return true; } TypeArray typeArgsAll = ctype.AsAggregateType().GetTypeArgsAll(); for (int i = 0; i < typeArgsAll.Count; i++) { CType typeArg = typeArgsAll[i]; if (TypeContainsAnonymousTypes(typeArg)) { return true; } } return false; case TypeKind.TK_ErrorType: if (ctype.AsErrorType().HasTypeParent()) { ctype = ctype.AsErrorType().GetTypeParent(); goto LRecurse; } return false; } } private sealed class StdTypeVarColl { private readonly List<TypeParameterType> prgptvs; public StdTypeVarColl() { prgptvs = new List<TypeParameterType>(); } //////////////////////////////////////////////////////////////////////////////// // Get the standard type variable (eg, !0, !1, or !!0, !!1). // // iv is the index. // pbsm is the containing symbol manager // fMeth designates whether this is a method type var or class type var // // The standard class type variables are useful during emit, but not for type // comparison when binding. The standard method type variables are useful during // binding for signature comparison. public TypeParameterType GetTypeVarSym(int iv, TypeManager pTypeManager, bool fMeth) { Debug.Assert(iv >= 0); TypeParameterType tpt = null; if (iv >= this.prgptvs.Count) { TypeParameterSymbol pTypeParameter = new TypeParameterSymbol(); pTypeParameter.SetIsMethodTypeParameter(fMeth); pTypeParameter.SetIndexInOwnParameters(iv); pTypeParameter.SetIndexInTotalParameters(iv); pTypeParameter.SetAccess(ACCESS.ACC_PRIVATE); tpt = pTypeManager.GetTypeParameter(pTypeParameter); this.prgptvs.Add(tpt); } else { tpt = this.prgptvs[iv]; } Debug.Assert(tpt != null); return tpt; } } public ArrayType GetArray(CType elementType, int args, bool isSZArray) { Name name; Debug.Assert(args > 0 && args < 32767); Debug.Assert(args == 1 || !isSZArray); switch (args) { case 1: if (isSZArray) { goto case 2; } else { goto default; } case 2: name = NameManager.GetPredefinedName(PredefinedName.PN_ARRAY0 + args); break; default: name = _BSymmgr.GetNameManager().Add("[X" + args + 1); break; } // See if we already have an array type of this element type and rank. ArrayType pArray = _typeTable.LookupArray(name, elementType); if (pArray == null) { // No existing array symbol. Create a new one. pArray = _typeFactory.CreateArray(name, elementType, args, isSZArray); pArray.InitFromParent(); _typeTable.InsertArray(name, elementType, pArray); } else { Debug.Assert(pArray.HasErrors() == elementType.HasErrors()); Debug.Assert(pArray.IsUnresolved() == elementType.IsUnresolved()); } Debug.Assert(pArray.rank == args); Debug.Assert(pArray.GetElementType() == elementType); return pArray; } public AggregateType GetAggregate(AggregateSymbol agg, AggregateType atsOuter, TypeArray typeArgs) { Debug.Assert(agg.GetTypeManager() == this); Debug.Assert(atsOuter == null || atsOuter.getAggregate() == agg.Parent, ""); if (typeArgs == null) { typeArgs = BSYMMGR.EmptyTypeArray(); } Debug.Assert(agg.GetTypeVars().Count == typeArgs.Count); Name name = _BSymmgr.GetNameFromPtrs(typeArgs, atsOuter); Debug.Assert(name != null); AggregateType pAggregate = _typeTable.LookupAggregate(name, agg); if (pAggregate == null) { pAggregate = _typeFactory.CreateAggregateType( name, agg, typeArgs, atsOuter ); Debug.Assert(!pAggregate.fConstraintsChecked && !pAggregate.fConstraintError); pAggregate.SetErrors(false); _typeTable.InsertAggregate(name, agg, pAggregate); // If we have a generic type definition, then we need to set the // base class to be our current base type, and use that to calculate // our agg type and its base, then set it to be the generic version of the // base type. This is because: // // Suppose we have Foo<T> : IFoo<T> // // Initially, the BaseType will be IFoo<Foo.T>, which gives us the substitution // that we want to use for our agg type's base type. However, in the Symbol chain, // we want the base type to be IFoo<IFoo.T>. Thats why we need to do this little trick. // // If we don't have a generic type definition, then we just need to set our base // class. This is so that if we have a base type that's generic, we'll be // getting the correctly instantiated base type. var baseType = pAggregate.AssociatedSystemType?.BaseType; if (baseType != null) { // Store the old base class. AggregateType oldBaseType = agg.GetBaseClass(); agg.SetBaseClass(_symbolTable.GetCTypeFromType(baseType).AsAggregateType()); pAggregate.GetBaseClass(); // Get the base type for the new agg type we're making. agg.SetBaseClass(oldBaseType); } } else { Debug.Assert(!pAggregate.HasErrors()); } Debug.Assert(pAggregate.getAggregate() == agg); Debug.Assert(pAggregate.GetTypeArgsThis() != null && pAggregate.GetTypeArgsAll() != null); Debug.Assert(pAggregate.GetTypeArgsThis() == typeArgs); return pAggregate; } public AggregateType GetAggregate(AggregateSymbol agg, TypeArray typeArgsAll) { Debug.Assert(typeArgsAll != null && typeArgsAll.Count == agg.GetTypeVarsAll().Count); if (typeArgsAll.Count == 0) return agg.getThisType(); AggregateSymbol aggOuter = agg.GetOuterAgg(); if (aggOuter == null) return GetAggregate(agg, null, typeArgsAll); int cvarOuter = aggOuter.GetTypeVarsAll().Count; Debug.Assert(cvarOuter <= typeArgsAll.Count); TypeArray typeArgsOuter = _BSymmgr.AllocParams(cvarOuter, typeArgsAll, 0); TypeArray typeArgsInner = _BSymmgr.AllocParams(agg.GetTypeVars().Count, typeArgsAll, cvarOuter); AggregateType atsOuter = GetAggregate(aggOuter, typeArgsOuter); return GetAggregate(agg, atsOuter, typeArgsInner); } public PointerType GetPointer(CType baseType) { PointerType pPointer = _typeTable.LookupPointer(baseType); if (pPointer == null) { // No existing type. Create a new one. Name namePtr = NameManager.GetPredefinedName(PredefinedName.PN_PTR); pPointer = _typeFactory.CreatePointer(namePtr, baseType); pPointer.InitFromParent(); _typeTable.InsertPointer(baseType, pPointer); } else { Debug.Assert(pPointer.HasErrors() == baseType.HasErrors()); Debug.Assert(pPointer.IsUnresolved() == baseType.IsUnresolved()); } Debug.Assert(pPointer.GetReferentType() == baseType); return pPointer; } public NullableType GetNullable(CType pUnderlyingType) { NullableType pNullableType = _typeTable.LookupNullable(pUnderlyingType); if (pNullableType == null) { Name pName = NameManager.GetPredefinedName(PredefinedName.PN_NUB); pNullableType = _typeFactory.CreateNullable(pName, pUnderlyingType, _BSymmgr, this); pNullableType.InitFromParent(); _typeTable.InsertNullable(pUnderlyingType, pNullableType); } return pNullableType; } public NullableType GetNubFromNullable(AggregateType ats) { Debug.Assert(ats.isPredefType(PredefinedType.PT_G_OPTIONAL)); return GetNullable(ats.GetTypeArgsAll()[0]); } public ParameterModifierType GetParameterModifier(CType paramType, bool isOut) { Name name = NameManager.GetPredefinedName(isOut ? PredefinedName.PN_OUTPARAM : PredefinedName.PN_REFPARAM); ParameterModifierType pParamModifier = _typeTable.LookupParameterModifier(name, paramType); if (pParamModifier == null) { // No existing parammod symbol. Create a new one. pParamModifier = _typeFactory.CreateParameterModifier(name, paramType); pParamModifier.isOut = isOut; pParamModifier.InitFromParent(); _typeTable.InsertParameterModifier(name, paramType, pParamModifier); } else { Debug.Assert(pParamModifier.HasErrors() == paramType.HasErrors()); Debug.Assert(pParamModifier.IsUnresolved() == paramType.IsUnresolved()); } Debug.Assert(pParamModifier.GetParameterType() == paramType); return pParamModifier; } public ErrorType GetErrorType( CType pParentType, AssemblyQualifiedNamespaceSymbol pParentNS, Name nameText, TypeArray typeArgs) { Debug.Assert(nameText != null); Debug.Assert(pParentType == null || pParentNS == null); if (pParentType == null && pParentNS == null) { // Use the root namespace as the parent. pParentNS = _BSymmgr.GetRootNsAid(KAID.kaidGlobal); } if (typeArgs == null) { typeArgs = BSYMMGR.EmptyTypeArray(); } Name name = _BSymmgr.GetNameFromPtrs(nameText, typeArgs); Debug.Assert(name != null); ErrorType pError = null; if (pParentType != null) { pError = _typeTable.LookupError(name, pParentType); } else { Debug.Assert(pParentNS != null); pError = _typeTable.LookupError(name, pParentNS); } if (pError == null) { // No existing error symbol. Create a new one. pError = _typeFactory.CreateError(name, pParentType, pParentNS, nameText, typeArgs); pError.SetErrors(true); if (pParentType != null) { _typeTable.InsertError(name, pParentType, pError); } else { _typeTable.InsertError(name, pParentNS, pError); } } else { Debug.Assert(pError.HasErrors()); Debug.Assert(pError.nameText == nameText); Debug.Assert(pError.typeArgs == typeArgs); } Debug.Assert(!pError.IsUnresolved()); return pError; } public VoidType GetVoid() { return _voidType; } public NullType GetNullType() { return _nullType; } private OpenTypePlaceholderType GetUnitType() { return _typeUnit; } public BoundLambdaType GetAnonMethType() { return _typeAnonMeth; } public MethodGroupType GetMethGrpType() { return _typeMethGrp; } public ArgumentListType GetArgListType() { return _argListType; } public ErrorType GetErrorSym() { return _errorType; } public AggregateSymbol GetNullable() { return this.GetOptPredefAgg(PredefinedType.PT_G_OPTIONAL); } private CType SubstType(CType typeSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth, SubstTypeFlags grfst) { if (typeSrc == null) return null; var ctx = new SubstContext(typeArgsCls, typeArgsMeth, grfst); return ctx.FNop() ? typeSrc : SubstTypeCore(typeSrc, ctx); } public CType SubstType(CType typeSrc, TypeArray typeArgsCls) { return SubstType(typeSrc, typeArgsCls, null, SubstTypeFlags.NormNone); } private CType SubstType(CType typeSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth) { return SubstType(typeSrc, typeArgsCls, typeArgsMeth, SubstTypeFlags.NormNone); } public TypeArray SubstTypeArray(TypeArray taSrc, SubstContext pctx) { if (taSrc == null || taSrc.Count == 0 || pctx == null || pctx.FNop()) return taSrc; CType[] prgpts = new CType[taSrc.Count]; for (int ipts = 0; ipts < taSrc.Count; ipts++) { prgpts[ipts] = this.SubstTypeCore(taSrc[ipts], pctx); } return _BSymmgr.AllocParams(taSrc.Count, prgpts); } private TypeArray SubstTypeArray(TypeArray taSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth, SubstTypeFlags grfst) { if (taSrc == null || taSrc.Count == 0) return taSrc; var ctx = new SubstContext(typeArgsCls, typeArgsMeth, grfst); if (ctx.FNop()) return taSrc; CType[] prgpts = new CType[taSrc.Count]; for (int ipts = 0; ipts < taSrc.Count; ipts++) { prgpts[ipts] = SubstTypeCore(taSrc[ipts], ctx); } return _BSymmgr.AllocParams(taSrc.Count, prgpts); } public TypeArray SubstTypeArray(TypeArray taSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth) { return this.SubstTypeArray(taSrc, typeArgsCls, typeArgsMeth, SubstTypeFlags.NormNone); } public TypeArray SubstTypeArray(TypeArray taSrc, TypeArray typeArgsCls) { return this.SubstTypeArray(taSrc, typeArgsCls, (TypeArray)null, SubstTypeFlags.NormNone); } private CType SubstTypeCore(CType type, SubstContext pctx) { CType typeSrc; CType typeDst; switch (type.GetTypeKind()) { default: Debug.Assert(false); return type; case TypeKind.TK_NullType: case TypeKind.TK_VoidType: case TypeKind.TK_OpenTypePlaceholderType: case TypeKind.TK_MethodGroupType: case TypeKind.TK_BoundLambdaType: case TypeKind.TK_UnboundLambdaType: case TypeKind.TK_NaturalIntegerType: case TypeKind.TK_ArgumentListType: return type; case TypeKind.TK_ParameterModifierType: typeDst = SubstTypeCore(typeSrc = type.AsParameterModifierType().GetParameterType(), pctx); return (typeDst == typeSrc) ? type : GetParameterModifier(typeDst, type.AsParameterModifierType().isOut); case TypeKind.TK_ArrayType: typeDst = SubstTypeCore(typeSrc = type.AsArrayType().GetElementType(), pctx); return (typeDst == typeSrc) ? type : GetArray(typeDst, type.AsArrayType().rank, type.AsArrayType().IsSZArray); case TypeKind.TK_PointerType: typeDst = SubstTypeCore(typeSrc = type.AsPointerType().GetReferentType(), pctx); return (typeDst == typeSrc) ? type : GetPointer(typeDst); case TypeKind.TK_NullableType: typeDst = SubstTypeCore(typeSrc = type.AsNullableType().GetUnderlyingType(), pctx); return (typeDst == typeSrc) ? type : GetNullable(typeDst); case TypeKind.TK_AggregateType: if (type.AsAggregateType().GetTypeArgsAll().Count > 0) { AggregateType ats = type.AsAggregateType(); TypeArray typeArgs = SubstTypeArray(ats.GetTypeArgsAll(), pctx); if (ats.GetTypeArgsAll() != typeArgs) return GetAggregate(ats.getAggregate(), typeArgs); } return type; case TypeKind.TK_ErrorType: if (type.AsErrorType().HasParent()) { ErrorType err = type.AsErrorType(); Debug.Assert(err.nameText != null && err.typeArgs != null); CType pParentType = null; if (err.HasTypeParent()) { pParentType = SubstTypeCore(err.GetTypeParent(), pctx); } TypeArray typeArgs = SubstTypeArray(err.typeArgs, pctx); if (typeArgs != err.typeArgs || (err.HasTypeParent() && pParentType != err.GetTypeParent())) { return GetErrorType(pParentType, err.GetNSParent(), err.nameText, typeArgs); } } return type; case TypeKind.TK_TypeParameterType: { TypeParameterSymbol tvs = type.AsTypeParameterType().GetTypeParameterSymbol(); int index = tvs.GetIndexInTotalParameters(); if (tvs.IsMethodTypeParameter()) { if ((pctx.grfst & SubstTypeFlags.DenormMeth) != 0 && tvs.parent != null) return type; Debug.Assert(tvs.GetIndexInOwnParameters() == tvs.GetIndexInTotalParameters()); if (index < pctx.ctypeMeth) { Debug.Assert(pctx.prgtypeMeth != null); return pctx.prgtypeMeth[index]; } else { return ((pctx.grfst & SubstTypeFlags.NormMeth) != 0 ? GetStdMethTypeVar(index) : type); } } if ((pctx.grfst & SubstTypeFlags.DenormClass) != 0 && tvs.parent != null) return type; return index < pctx.ctypeCls ? pctx.prgtypeCls[index] : ((pctx.grfst & SubstTypeFlags.NormClass) != 0 ? GetStdClsTypeVar(index) : type); } } } public bool SubstEqualTypes(CType typeDst, CType typeSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth, SubstTypeFlags grfst) { if (typeDst.Equals(typeSrc)) { Debug.Assert(typeDst.Equals(SubstType(typeSrc, typeArgsCls, typeArgsMeth, grfst))); return true; } var ctx = new SubstContext(typeArgsCls, typeArgsMeth, grfst); return !ctx.FNop() && SubstEqualTypesCore(typeDst, typeSrc, ctx); } public bool SubstEqualTypeArrays(TypeArray taDst, TypeArray taSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth, SubstTypeFlags grfst) { // Handle the simple common cases first. if (taDst == taSrc || (taDst != null && taDst.Equals(taSrc))) { // The following assertion is not always true and indicates a problem where // the signature of override method does not match the one inherited from // the base class. The method match we have found does not take the type // arguments of the base class into account. So actually we are not overriding // the method that we "intend" to. // Debug.Assert(taDst == SubstTypeArray(taSrc, typeArgsCls, typeArgsMeth, grfst)); return true; } if (taDst.Count != taSrc.Count) return false; if (taDst.Count == 0) return true; var ctx = new SubstContext(typeArgsCls, typeArgsMeth, grfst); if (ctx.FNop()) return false; for (int i = 0; i < taDst.Count; i++) { if (!SubstEqualTypesCore(taDst[i], taSrc[i], ctx)) return false; } return true; } private bool SubstEqualTypesCore(CType typeDst, CType typeSrc, SubstContext pctx) { LRecurse: // Label used for "tail" recursion. if (typeDst == typeSrc || typeDst.Equals(typeSrc)) { return true; } switch (typeSrc.GetTypeKind()) { default: Debug.Assert(false, "Bad Symbol kind in SubstEqualTypesCore"); return false; case TypeKind.TK_NullType: case TypeKind.TK_VoidType: case TypeKind.TK_OpenTypePlaceholderType: // There should only be a single instance of these. Debug.Assert(typeDst.GetTypeKind() != typeSrc.GetTypeKind()); return false; case TypeKind.TK_ArrayType: if (typeDst.GetTypeKind() != TypeKind.TK_ArrayType || typeDst.AsArrayType().rank != typeSrc.AsArrayType().rank || typeDst.AsArrayType().IsSZArray != typeSrc.AsArrayType().IsSZArray) return false; goto LCheckBases; case TypeKind.TK_ParameterModifierType: if (typeDst.GetTypeKind() != TypeKind.TK_ParameterModifierType || ((pctx.grfst & SubstTypeFlags.NoRefOutDifference) == 0 && typeDst.AsParameterModifierType().isOut != typeSrc.AsParameterModifierType().isOut)) return false; goto LCheckBases; case TypeKind.TK_PointerType: case TypeKind.TK_NullableType: if (typeDst.GetTypeKind() != typeSrc.GetTypeKind()) return false; LCheckBases: typeSrc = typeSrc.GetBaseOrParameterOrElementType(); typeDst = typeDst.GetBaseOrParameterOrElementType(); goto LRecurse; case TypeKind.TK_AggregateType: if (typeDst.GetTypeKind() != TypeKind.TK_AggregateType) return false; { // BLOCK AggregateType atsSrc = typeSrc.AsAggregateType(); AggregateType atsDst = typeDst.AsAggregateType(); if (atsSrc.getAggregate() != atsDst.getAggregate()) return false; Debug.Assert(atsSrc.GetTypeArgsAll().Count == atsDst.GetTypeArgsAll().Count); // All the args must unify. for (int i = 0; i < atsSrc.GetTypeArgsAll().Count; i++) { if (!SubstEqualTypesCore(atsDst.GetTypeArgsAll()[i], atsSrc.GetTypeArgsAll()[i], pctx)) return false; } } return true; case TypeKind.TK_ErrorType: if (!typeDst.IsErrorType() || !typeSrc.AsErrorType().HasParent() || !typeDst.AsErrorType().HasParent()) return false; { ErrorType errSrc = typeSrc.AsErrorType(); ErrorType errDst = typeDst.AsErrorType(); Debug.Assert(errSrc.nameText != null && errSrc.typeArgs != null); Debug.Assert(errDst.nameText != null && errDst.typeArgs != null); if (errSrc.nameText != errDst.nameText || errSrc.typeArgs.Count != errDst.typeArgs.Count) return false; if (errSrc.HasTypeParent() != errDst.HasTypeParent()) { return false; } if (errSrc.HasTypeParent()) { if (errSrc.GetTypeParent() != errDst.GetTypeParent()) { return false; } if (!SubstEqualTypesCore(errDst.GetTypeParent(), errSrc.GetTypeParent(), pctx)) { return false; } } else { if (errSrc.GetNSParent() != errDst.GetNSParent()) { return false; } } // All the args must unify. for (int i = 0; i < errSrc.typeArgs.Count; i++) { if (!SubstEqualTypesCore(errDst.typeArgs[i], errSrc.typeArgs[i], pctx)) return false; } } return true; case TypeKind.TK_TypeParameterType: { // BLOCK TypeParameterSymbol tvs = typeSrc.AsTypeParameterType().GetTypeParameterSymbol(); int index = tvs.GetIndexInTotalParameters(); if (tvs.IsMethodTypeParameter()) { if ((pctx.grfst & SubstTypeFlags.DenormMeth) != 0 && tvs.parent != null) { // typeDst == typeSrc was handled above. Debug.Assert(typeDst != typeSrc); return false; } Debug.Assert(tvs.GetIndexInOwnParameters() == tvs.GetIndexInTotalParameters()); Debug.Assert(pctx.prgtypeMeth == null || tvs.GetIndexInTotalParameters() < pctx.ctypeMeth); if (index < pctx.ctypeMeth && pctx.prgtypeMeth != null) { return typeDst == pctx.prgtypeMeth[index]; } if ((pctx.grfst & SubstTypeFlags.NormMeth) != 0) { return typeDst == GetStdMethTypeVar(index); } } else { if ((pctx.grfst & SubstTypeFlags.DenormClass) != 0 && tvs.parent != null) { // typeDst == typeSrc was handled above. Debug.Assert(typeDst != typeSrc); return false; } Debug.Assert(pctx.prgtypeCls == null || tvs.GetIndexInTotalParameters() < pctx.ctypeCls); if (index < pctx.ctypeCls) return typeDst == pctx.prgtypeCls[index]; if ((pctx.grfst & SubstTypeFlags.NormClass) != 0) return typeDst == GetStdClsTypeVar(index); } } return false; } } public void ReportMissingPredefTypeError(ErrorHandling errorContext, PredefinedType pt) { _predefTypes.ReportMissingPredefTypeError(errorContext, pt); } public static bool TypeContainsType(CType type, CType typeFind) { LRecurse: // Label used for "tail" recursion. if (type == typeFind || type.Equals(typeFind)) return true; switch (type.GetTypeKind()) { default: Debug.Assert(false, "Bad Symbol kind in TypeContainsType"); return false; case TypeKind.TK_NullType: case TypeKind.TK_VoidType: case TypeKind.TK_OpenTypePlaceholderType: // There should only be a single instance of these. Debug.Assert(typeFind.GetTypeKind() != type.GetTypeKind()); return false; case TypeKind.TK_ArrayType: case TypeKind.TK_NullableType: case TypeKind.TK_ParameterModifierType: case TypeKind.TK_PointerType: type = type.GetBaseOrParameterOrElementType(); goto LRecurse; case TypeKind.TK_AggregateType: { // BLOCK AggregateType ats = type.AsAggregateType(); for (int i = 0; i < ats.GetTypeArgsAll().Count; i++) { if (TypeContainsType(ats.GetTypeArgsAll()[i], typeFind)) return true; } } return false; case TypeKind.TK_ErrorType: if (type.AsErrorType().HasParent()) { ErrorType err = type.AsErrorType(); Debug.Assert(err.nameText != null && err.typeArgs != null); for (int i = 0; i < err.typeArgs.Count; i++) { if (TypeContainsType(err.typeArgs[i], typeFind)) return true; } if (err.HasTypeParent()) { type = err.GetTypeParent(); goto LRecurse; } } return false; case TypeKind.TK_TypeParameterType: return false; } } public static bool TypeContainsTyVars(CType type, TypeArray typeVars) { LRecurse: // Label used for "tail" recursion. switch (type.GetTypeKind()) { default: Debug.Assert(false, "Bad Symbol kind in TypeContainsTyVars"); return false; case TypeKind.TK_UnboundLambdaType: case TypeKind.TK_BoundLambdaType: case TypeKind.TK_NullType: case TypeKind.TK_VoidType: case TypeKind.TK_OpenTypePlaceholderType: case TypeKind.TK_MethodGroupType: return false; case TypeKind.TK_ArrayType: case TypeKind.TK_NullableType: case TypeKind.TK_ParameterModifierType: case TypeKind.TK_PointerType: type = type.GetBaseOrParameterOrElementType(); goto LRecurse; case TypeKind.TK_AggregateType: { // BLOCK AggregateType ats = type.AsAggregateType(); for (int i = 0; i < ats.GetTypeArgsAll().Count; i++) { if (TypeContainsTyVars(ats.GetTypeArgsAll()[i], typeVars)) { return true; } } } return false; case TypeKind.TK_ErrorType: if (type.AsErrorType().HasParent()) { ErrorType err = type.AsErrorType(); Debug.Assert(err.nameText != null && err.typeArgs != null); for (int i = 0; i < err.typeArgs.Count; i++) { if (TypeContainsTyVars(err.typeArgs[i], typeVars)) { return true; } } if (err.HasTypeParent()) { type = err.GetTypeParent(); goto LRecurse; } } return false; case TypeKind.TK_TypeParameterType: if (typeVars != null && typeVars.Count > 0) { int ivar = type.AsTypeParameterType().GetIndexInTotalParameters(); return ivar < typeVars.Count && type == typeVars[ivar]; } return true; } } public static bool ParametersContainTyVar(TypeArray @params, TypeParameterType typeFind) { Debug.Assert(@params != null); Debug.Assert(typeFind != null); for (int p = 0; p < @params.Count; p++) { CType sym = @params[p]; if (TypeContainsType(sym, typeFind)) { return true; } } return false; } public AggregateSymbol GetReqPredefAgg(PredefinedType pt) { return _predefTypes.GetReqPredefAgg(pt); } public AggregateSymbol GetOptPredefAgg(PredefinedType pt) { return _predefTypes.GetOptPredefAgg(pt); } public TypeArray CreateArrayOfUnitTypes(int cSize) { CType[] ppArray = new CType[cSize]; for (int i = 0; i < cSize; i++) { ppArray[i] = GetUnitType(); } return _BSymmgr.AllocParams(cSize, ppArray); } public TypeArray ConcatenateTypeArrays(TypeArray pTypeArray1, TypeArray pTypeArray2) { return _BSymmgr.ConcatParams(pTypeArray1, pTypeArray2); } public TypeArray GetStdMethTyVarArray(int cTyVars) { TypeParameterType[] prgvar = new TypeParameterType[cTyVars]; for (int ivar = 0; ivar < cTyVars; ivar++) { prgvar[ivar] = GetStdMethTypeVar(ivar); } return _BSymmgr.AllocParams(cTyVars, (CType[])prgvar); } public CType SubstType(CType typeSrc, SubstContext pctx) { return (pctx == null || pctx.FNop()) ? typeSrc : SubstTypeCore(typeSrc, pctx); } public CType SubstType(CType typeSrc, AggregateType atsCls) { return SubstType(typeSrc, atsCls, (TypeArray)null); } public CType SubstType(CType typeSrc, AggregateType atsCls, TypeArray typeArgsMeth) { return SubstType(typeSrc, atsCls?.GetTypeArgsAll(), typeArgsMeth); } public CType SubstType(CType typeSrc, CType typeCls, TypeArray typeArgsMeth) { return SubstType(typeSrc, typeCls.IsAggregateType() ? typeCls.AsAggregateType().GetTypeArgsAll() : null, typeArgsMeth); } public TypeArray SubstTypeArray(TypeArray taSrc, AggregateType atsCls, TypeArray typeArgsMeth) { return SubstTypeArray(taSrc, atsCls?.GetTypeArgsAll(), typeArgsMeth); } public TypeArray SubstTypeArray(TypeArray taSrc, AggregateType atsCls) { return this.SubstTypeArray(taSrc, atsCls, (TypeArray)null); } private bool SubstEqualTypes(CType typeDst, CType typeSrc, CType typeCls, TypeArray typeArgsMeth) { return SubstEqualTypes(typeDst, typeSrc, typeCls.IsAggregateType() ? typeCls.AsAggregateType().GetTypeArgsAll() : null, typeArgsMeth, SubstTypeFlags.NormNone); } public bool SubstEqualTypes(CType typeDst, CType typeSrc, CType typeCls) { return SubstEqualTypes(typeDst, typeSrc, typeCls, (TypeArray)null); } //public bool SubstEqualTypeArrays(TypeArray taDst, TypeArray taSrc, AggregateType atsCls, TypeArray typeArgsMeth) //{ // return SubstEqualTypeArrays(taDst, taSrc, atsCls != null ? atsCls.GetTypeArgsAll() : (TypeArray)null, typeArgsMeth, SubstTypeFlags.NormNone); //} public TypeParameterType GetStdMethTypeVar(int iv) { return _stvcMethod.GetTypeVarSym(iv, this, true); } private TypeParameterType GetStdClsTypeVar(int iv) { return _stvcClass.GetTypeVarSym(iv, this, false); } public TypeParameterType GetTypeParameter(TypeParameterSymbol pSymbol) { // These guys should be singletons for each. TypeParameterType pTypeParameter = _typeTable.LookupTypeParameter(pSymbol); if (pTypeParameter == null) { pTypeParameter = _typeFactory.CreateTypeParameter(pSymbol); _typeTable.InsertTypeParameter(pSymbol, pTypeParameter); } return pTypeParameter; } internal void Init(BSYMMGR bsymmgr, PredefinedTypes predefTypes) { _BSymmgr = bsymmgr; _predefTypes = predefTypes; } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // RUNTIME BINDER ONLY CHANGE // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! internal bool GetBestAccessibleType(CSemanticChecker semanticChecker, BindingContext bindingContext, CType typeSrc, out CType typeDst) { // This method implements the "best accessible type" algorithm for determining the type // of untyped arguments in the runtime binder. It is also used in method type inference // to fix type arguments to types that are accessible. // The new type is returned in an out parameter. The result will be true (and the out param // non-null) only when the algorithm could find a suitable accessible type. Debug.Assert(semanticChecker != null); Debug.Assert(bindingContext != null); Debug.Assert(typeSrc != null); typeDst = null; if (semanticChecker.CheckTypeAccess(typeSrc, bindingContext.ContextForMemberLookup)) { // If we already have an accessible type, then use it. This is the terminal point of the recursion. typeDst = typeSrc; return true; } // These guys have no accessibility concerns. Debug.Assert(!typeSrc.IsVoidType() && !typeSrc.IsErrorType() && !typeSrc.IsTypeParameterType()); if (typeSrc.IsParameterModifierType() || typeSrc.IsPointerType()) { // We cannot vary these. return false; } CType intermediateType; if ((typeSrc.isInterfaceType() || typeSrc.isDelegateType()) && TryVarianceAdjustmentToGetAccessibleType(semanticChecker, bindingContext, typeSrc.AsAggregateType(), out intermediateType)) { // If we have an interface or delegate type, then it can potentially be varied by its type arguments // to produce an accessible type, and if that's the case, then return that. // Example: IEnumerable<PrivateConcreteFoo> --> IEnumerable<PublicAbstractFoo> typeDst = intermediateType; Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup)); return true; } if (typeSrc.IsArrayType() && TryArrayVarianceAdjustmentToGetAccessibleType(semanticChecker, bindingContext, typeSrc.AsArrayType(), out intermediateType)) { // Similarly to the interface and delegate case, arrays are covariant in their element type and // so we can potentially produce an array type that is accessible. // Example: PrivateConcreteFoo[] --> PublicAbstractFoo[] typeDst = intermediateType; Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup)); return true; } if (typeSrc.IsNullableType()) { // We have an inaccessible nullable type, which means that the best we can do is System.ValueType. typeDst = this.GetOptPredefAgg(PredefinedType.PT_VALUE).getThisType(); Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup)); return true; } if (typeSrc.IsArrayType()) { // We have an inaccessible array type for which we could not earlier find a better array type // with a covariant conversion, so the best we can do is System.Array. typeDst = this.GetReqPredefAgg(PredefinedType.PT_ARRAY).getThisType(); Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup)); return true; } Debug.Assert(typeSrc.IsAggregateType()); if (typeSrc.IsAggregateType()) { // We have an AggregateType, so recurse on its base class. AggregateType aggType = typeSrc.AsAggregateType(); AggregateType baseType = aggType.GetBaseClass(); if (baseType == null) { // This happens with interfaces, for instance. But in that case, the // conversion to object does exist, is an implicit reference conversion, // and so we will use it. baseType = this.GetReqPredefAgg(PredefinedType.PT_OBJECT).getThisType(); } return GetBestAccessibleType(semanticChecker, bindingContext, baseType, out typeDst); } return false; } private bool TryVarianceAdjustmentToGetAccessibleType(CSemanticChecker semanticChecker, BindingContext bindingContext, AggregateType typeSrc, out CType typeDst) { Debug.Assert(typeSrc != null); Debug.Assert(typeSrc.isInterfaceType() || typeSrc.isDelegateType()); typeDst = null; AggregateSymbol aggSym = typeSrc.GetOwningAggregate(); AggregateType aggOpenType = aggSym.getThisType(); if (!semanticChecker.CheckTypeAccess(aggOpenType, bindingContext.ContextForMemberLookup)) { // if the aggregate symbol itself is not accessible, then forget it, there is no // variance that will help us arrive at an accessible type. return false; } TypeArray typeArgs = typeSrc.GetTypeArgsThis(); TypeArray typeParams = aggOpenType.GetTypeArgsThis(); CType[] newTypeArgsTemp = new CType[typeArgs.Count]; for (int i = 0; i < typeArgs.Count; i++) { if (semanticChecker.CheckTypeAccess(typeArgs[i], bindingContext.ContextForMemberLookup)) { // we have an accessible argument, this position is not a problem. newTypeArgsTemp[i] = typeArgs[i]; continue; } if (!typeArgs[i].IsRefType() || !typeParams[i].AsTypeParameterType().Covariant) { // This guy is inaccessible, and we are not going to be able to vary him, so we need to fail. return false; } CType intermediateTypeArg; if (GetBestAccessibleType(semanticChecker, bindingContext, typeArgs[i], out intermediateTypeArg)) { // now we either have a value type (which must be accessible due to the above // check, OR we have an inaccessible type (which must be a ref type). In either // case, the recursion worked out and we are OK to vary this argument. newTypeArgsTemp[i] = intermediateTypeArg; continue; } else { Debug.Assert(false, "GetBestAccessibleType unexpectedly failed on a type that was used as a type parameter"); return false; } } TypeArray newTypeArgs = semanticChecker.getBSymmgr().AllocParams(typeArgs.Count, newTypeArgsTemp); CType intermediateType = this.GetAggregate(aggSym, typeSrc.outerType, newTypeArgs); // All type arguments were varied successfully, which means now we must be accessible. But we could // have violated constraints. Let's check that out. if (!TypeBind.CheckConstraints(semanticChecker, null/*ErrorHandling*/, intermediateType, CheckConstraintsFlags.NoErrors)) { return false; } typeDst = intermediateType; Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup)); return true; } private bool TryArrayVarianceAdjustmentToGetAccessibleType(CSemanticChecker semanticChecker, BindingContext bindingContext, ArrayType typeSrc, out CType typeDst) { Debug.Assert(typeSrc != null); typeDst = null; // We are here because we have an array type with an inaccessible element type. If possible, // we should create a new array type that has an accessible element type for which a // conversion exists. CType elementType = typeSrc.GetElementType(); if (!elementType.IsRefType()) { // Covariant array conversions exist for reference types only. return false; } CType intermediateType; if (GetBestAccessibleType(semanticChecker, bindingContext, elementType, out intermediateType)) { typeDst = this.GetArray(intermediateType, typeSrc.rank, typeSrc.IsSZArray); Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup)); return true; } return false; } private readonly Dictionary<Tuple<Assembly, Assembly>, bool> _internalsVisibleToCalculated = new Dictionary<Tuple<Assembly, Assembly>, bool>(); internal bool InternalsVisibleTo(Assembly assemblyThatDefinesAttribute, Assembly assemblyToCheck) { bool result; var key = Tuple.Create(assemblyThatDefinesAttribute, assemblyToCheck); if (!_internalsVisibleToCalculated.TryGetValue(key, out result)) { AssemblyName assyName = null; // Assembly.GetName() requires FileIOPermission to FileIOPermissionAccess.PathDiscovery. // If we don't have that (we're in low trust), then we are going to effectively turn off // InternalsVisibleTo. The alternative is to crash when this happens. try { assyName = assemblyToCheck.GetName(); } catch (System.Security.SecurityException) { result = false; goto SetMemo; } result = assemblyThatDefinesAttribute.GetCustomAttributes() .OfType<InternalsVisibleToAttribute>() .Select(ivta => new AssemblyName(ivta.AssemblyName)) .Any(an => AssemblyName.ReferenceMatchesDefinition(an, assyName)); SetMemo: _internalsVisibleToCalculated[key] = result; } return result; } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // END RUNTIME BINDER ONLY CHANGE // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.XWPF.UserModel { using System; using NPOI.OpenXmlFormats.Wordprocessing; using System.Collections.Generic; /** * A row within an {@link XWPFTable}. Rows mostly just have * sizings and stylings, the interesting content lives inside * the child {@link XWPFTableCell}s */ public class XWPFTableRow { private CT_Row ctRow; private XWPFTable table; private List<XWPFTableCell> tableCells; public XWPFTableRow(CT_Row row, XWPFTable table) { this.table = table; this.ctRow = row; GetTableCells(); } public CT_Row GetCTRow() { return ctRow; } /** * create a new XWPFTableCell and add it to the tableCell-list of this tableRow * @return the newly Created XWPFTableCell */ public XWPFTableCell CreateCell() { XWPFTableCell tableCell = new XWPFTableCell(ctRow.AddNewTc(), this, table.Body); tableCells.Add(tableCell); return tableCell; } public void MergeCells(int startIndex, int endIndex) { if (startIndex >= endIndex) { throw new ArgumentOutOfRangeException("Start index must be smaller than end index"); } if (startIndex < 0 || endIndex >= this.tableCells.Count) { throw new ArgumentOutOfRangeException("Invalid start index and end index"); } XWPFTableCell startCell = this.GetCell(startIndex); //remove merged cells for (int i = endIndex; i >startIndex; i--) this.RemoveCell(i); if (!startCell.GetCTTc().IsSetTcPr()) { startCell.GetCTTc().AddNewTcPr(); } CT_TcPr tcPr = startCell.GetCTTc().tcPr; if(tcPr.gridSpan==null) tcPr.AddNewGridspan(); CT_DecimalNumber gridspan = tcPr.gridSpan; gridspan.val = (endIndex - startIndex+1).ToString(); } public XWPFTableCell GetCell(int pos) { if (pos >= 0 && pos < ctRow.SizeOfTcArray()) { return GetTableCells()[(pos)]; } return null; } public void RemoveCell(int pos) { if (pos >= 0 && pos < ctRow.SizeOfTcArray()) { tableCells.RemoveAt(pos); ctRow.RemoveTc(pos); } } /** * Adds a new TableCell at the end of this tableRow */ public XWPFTableCell AddNewTableCell() { CT_Tc cell = ctRow.AddNewTc(); XWPFTableCell tableCell = new XWPFTableCell(cell, this, table.Body); tableCells.Add(tableCell); return tableCell; } /** * This element specifies the height of the current table row within the * current table. This height shall be used to determine the resulting * height of the table row, which may be absolute or relative (depending on * its attribute values). If omitted, then the table row shall automatically * resize its height to the height required by its contents (the equivalent * of an hRule value of auto). * * @return height */ public int Height { get { CT_TrPr properties = GetTrPr(); return properties.SizeOfTrHeightArray() == 0 ? 0 : (int)properties.GetTrHeightArray(0).val; } set { CT_TrPr properties = GetTrPr(); CT_Height h = properties.SizeOfTrHeightArray() == 0 ? properties.AddNewTrHeight() : properties.GetTrHeightArray(0); h.val = (ulong)value; } } private CT_TrPr GetTrPr() { return (ctRow.IsSetTrPr()) ? ctRow.trPr : ctRow.AddNewTrPr(); } public XWPFTable GetTable() { return table; } /** * create and return a list of all XWPFTableCell * who belongs to this row * @return a list of {@link XWPFTableCell} */ public List<ICell> GetTableICells() { List<ICell> cells = new List<ICell>(); //Can't use ctRow.getTcList because that only gets table cells //Can't use ctRow.getSdtList because that only gets sdts that are at cell level foreach(object o in ctRow.Items) { if (o is CT_Tc) { cells.Add(new XWPFTableCell((CT_Tc)o, this, table.Body)); } else if (o is CT_SdtCell) { cells.Add(new XWPFSDTCell((CT_SdtCell)o, this, table.Body)); } } return cells; } /** * create and return a list of all XWPFTableCell * who belongs to this row * @return a list of {@link XWPFTableCell} */ public List<XWPFTableCell> GetTableCells() { if (tableCells == null) { List<XWPFTableCell> cells = new List<XWPFTableCell>(); foreach (CT_Tc tableCell in ctRow.GetTcList()) { cells.Add(new XWPFTableCell(tableCell, this, table.Body)); } //TODO: it is possible to have an SDT that contains a cell in within a row //need to modify this code so that it pulls out SDT wrappers around cells, too. this.tableCells = cells; } return tableCells; } /** * returns the XWPFTableCell which belongs to the CTTC cell * if there is no XWPFTableCell which belongs to the parameter CTTc cell null will be returned */ public XWPFTableCell GetTableCell(CT_Tc cell) { for (int i = 0; i < tableCells.Count; i++) { if (tableCells[(i)].GetCTTc() == cell) return tableCells[(i)]; } return null; } /** * Return true if the "can't split row" value is true. The logic for this * attribute is a little unusual: a TRUE value means DON'T allow rows to * split, FALSE means allow rows to split. * @return true if rows can't be split, false otherwise. */ public bool IsCantSplitRow { get { bool isCant = false; CT_TrPr trpr = GetTrPr(); if (trpr.SizeOfCantSplitArray() > 0) { CT_OnOff onoff = trpr.GetCantSplitList()[0]; isCant = onoff.val; } return isCant; } set { CT_TrPr trpr = GetTrPr(); CT_OnOff onoff = trpr.AddNewCantSplit(); onoff.val = value; } } /** * Return true if a table's header row should be repeated at the top of a * table split across pages. * @return true if table's header row should be repeated at the top of each * page of table, false otherwise. */ public bool IsRepeatHeader { get { bool repeat = false; CT_TrPr trpr = GetTrPr(); if (trpr.SizeOfTblHeaderArray() > 0) { CT_OnOff rpt = trpr.GetTblHeaderList()[0]; repeat = rpt.val; } return repeat; } set { CT_TrPr trpr = GetTrPr(); CT_OnOff onoff = trpr.AddNewTblHeader(); onoff.val = value; } } }// end class }
// 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.Linq; using System.Linq.Expressions; namespace Microsoft.AspNetCore.Components.Forms { /// <summary> /// Holds metadata related to a data editing process, such as flags to indicate which /// fields have been modified and the current set of validation messages. /// </summary> public sealed class EditContext { // Note that EditContext tracks state for any FieldIdentifier you give to it, plus // the underlying storage is sparse. As such, none of the APIs have a "field not found" // error state. If you give us an unrecognized FieldIdentifier, that just means we // didn't yet track any state for it, so we behave as if it's in the default state // (valid and unmodified). private readonly Dictionary<FieldIdentifier, FieldState> _fieldStates = new Dictionary<FieldIdentifier, FieldState>(); /// <summary> /// Constructs an instance of <see cref="EditContext"/>. /// </summary> /// <param name="model">The model object for the <see cref="EditContext"/>. This object should hold the data being edited, for example as a set of properties.</param> public EditContext(object model) { // The only reason we disallow null is because you'd almost always want one, and if you // really don't, you can pass an empty object then ignore it. Ensuring it's nonnull // simplifies things for all consumers of EditContext. Model = model ?? throw new ArgumentNullException(nameof(model)); Properties = new EditContextProperties(); } /// <summary> /// An event that is raised when a field value changes. /// </summary> public event EventHandler<FieldChangedEventArgs>? OnFieldChanged; /// <summary> /// An event that is raised when validation is requested. /// </summary> public event EventHandler<ValidationRequestedEventArgs>? OnValidationRequested; /// <summary> /// An event that is raised when validation state has changed. /// </summary> public event EventHandler<ValidationStateChangedEventArgs>? OnValidationStateChanged; /// <summary> /// Supplies a <see cref="FieldIdentifier"/> corresponding to a specified field name /// on this <see cref="EditContext"/>'s <see cref="Model"/>. /// </summary> /// <param name="fieldName">The name of the editable field.</param> /// <returns>A <see cref="FieldIdentifier"/> corresponding to a specified field name on this <see cref="EditContext"/>'s <see cref="Model"/>.</returns> public FieldIdentifier Field(string fieldName) => new FieldIdentifier(Model, fieldName); /// <summary> /// Gets the model object for this <see cref="EditContext"/>. /// </summary> public object Model { get; } /// <summary> /// Gets a collection of arbitrary properties associated with this instance. /// </summary> public EditContextProperties Properties { get; } /// <summary> /// Signals that the value for the specified field has changed. /// </summary> /// <param name="fieldIdentifier">Identifies the field whose value has been changed.</param> public void NotifyFieldChanged(in FieldIdentifier fieldIdentifier) { GetOrAddFieldState(fieldIdentifier).IsModified = true; OnFieldChanged?.Invoke(this, new FieldChangedEventArgs(fieldIdentifier)); } /// <summary> /// Signals that some aspect of validation state has changed. /// </summary> public void NotifyValidationStateChanged() { OnValidationStateChanged?.Invoke(this, ValidationStateChangedEventArgs.Empty); } /// <summary> /// Clears any modification flag that may be tracked for the specified field. /// </summary> /// <param name="fieldIdentifier">Identifies the field whose modification flag (if any) should be cleared.</param> public void MarkAsUnmodified(in FieldIdentifier fieldIdentifier) { if (_fieldStates.TryGetValue(fieldIdentifier, out var state)) { state.IsModified = false; } } /// <summary> /// Clears all modification flags within this <see cref="EditContext"/>. /// </summary> public void MarkAsUnmodified() { foreach (var state in _fieldStates) { state.Value.IsModified = false; } } /// <summary> /// Determines whether any of the fields in this <see cref="EditContext"/> have been modified. /// </summary> /// <returns>True if any of the fields in this <see cref="EditContext"/> have been modified; otherwise false.</returns> public bool IsModified() { // If necessary, we could consider caching the overall "is modified" state and only recomputing // when there's a call to NotifyFieldModified/NotifyFieldUnmodified foreach (var state in _fieldStates) { if (state.Value.IsModified) { return true; } } return false; } /// <summary> /// Gets the current validation messages across all fields. /// /// This method does not perform validation itself. It only returns messages determined by previous validation actions. /// </summary> /// <returns>The current validation messages.</returns> public IEnumerable<string> GetValidationMessages() { // Since we're only enumerating the fields for which we have a non-null state, the cost of this grows // based on how many fields have been modified or have associated validation messages foreach (var state in _fieldStates) { foreach (var message in state.Value.GetValidationMessages()) { yield return message; } } } /// <summary> /// Gets the current validation messages for the specified field. /// /// This method does not perform validation itself. It only returns messages determined by previous validation actions. /// </summary> /// <param name="fieldIdentifier">Identifies the field whose current validation messages should be returned.</param> /// <returns>The current validation messages for the specified field.</returns> public IEnumerable<string> GetValidationMessages(FieldIdentifier fieldIdentifier) { if (_fieldStates.TryGetValue(fieldIdentifier, out var state)) { foreach (var message in state.GetValidationMessages()) { yield return message; } } } /// <summary> /// Gets the current validation messages for the specified field. /// /// This method does not perform validation itself. It only returns messages determined by previous validation actions. /// </summary> /// <param name="accessor">Identifies the field whose current validation messages should be returned.</param> /// <returns>The current validation messages for the specified field.</returns> public IEnumerable<string> GetValidationMessages(Expression<Func<object>> accessor) => GetValidationMessages(FieldIdentifier.Create(accessor)); /// <summary> /// Determines whether the specified fields in this <see cref="EditContext"/> has been modified. /// </summary> /// <returns>True if the field has been modified; otherwise false.</returns> public bool IsModified(in FieldIdentifier fieldIdentifier) => _fieldStates.TryGetValue(fieldIdentifier, out var state) ? state.IsModified : false; /// <summary> /// Determines whether the specified fields in this <see cref="EditContext"/> has been modified. /// </summary> /// <param name="accessor">Identifies the field whose current validation messages should be returned.</param> /// <returns>True if the field has been modified; otherwise false.</returns> public bool IsModified(Expression<Func<object>> accessor) => IsModified(FieldIdentifier.Create(accessor)); /// <summary> /// Validates this <see cref="EditContext"/>. /// </summary> /// <returns>True if there are no validation messages after validation; otherwise false.</returns> public bool Validate() { OnValidationRequested?.Invoke(this, ValidationRequestedEventArgs.Empty); return !GetValidationMessages().Any(); } internal FieldState? GetFieldState(in FieldIdentifier fieldIdentifier) { _fieldStates.TryGetValue(fieldIdentifier, out var state); return state; } internal FieldState GetOrAddFieldState(in FieldIdentifier fieldIdentifier) { if (!_fieldStates.TryGetValue(fieldIdentifier, out var state)) { state = new FieldState(fieldIdentifier); _fieldStates.Add(fieldIdentifier, state); } return state; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Xunit; internal class Outside { public class Inside { } } internal class Outside<T> { public class Inside<U> { } } public static class TypeTests { [Theory] [InlineData(typeof(int), null)] [InlineData(typeof(int[]), null)] [InlineData(typeof(Outside.Inside), typeof(Outside))] [InlineData(typeof(Outside.Inside[]), null)] [InlineData(typeof(Outside<int>), null)] [InlineData(typeof(Outside<int>.Inside<double>), typeof(Outside<>))] public static void TestDeclaringType(Type t, Type expected) { Assert.Equal(expected, t.DeclaringType); } [Theory] [InlineData(typeof(int))] [InlineData(typeof(int[]))] [InlineData(typeof(IList<int>))] [InlineData(typeof(IList<>))] public static void TestGenericParameterPositionInvalid(Type t) { Assert.Throws<InvalidOperationException>(() => t.GenericParameterPosition); } [Theory] [InlineData(typeof(int), new Type[0])] [InlineData(typeof(IDictionary<int, string>), new[] { typeof(int), typeof(string) })] [InlineData(typeof(IList<int>), new[] { typeof(int) })] [InlineData(typeof(IList<>), new Type[0])] public static void TestGenericTypeArguments(Type t, Type[] expected) { Type[] result = t.GenericTypeArguments; Assert.Equal(expected.Length, result.Length); for (int i = 0; i < expected.Length; i++) { Assert.Equal(expected[i], result[i]); } } [Theory] [InlineData(typeof(int), false)] [InlineData(typeof(int[]), true)] [InlineData(typeof(IList<int>), false)] [InlineData(typeof(IList<>), false)] public static void TestHasElementType(Type t, bool expected) { Assert.Equal(expected, t.HasElementType); } [Theory] [InlineData(typeof(int), false)] [InlineData(typeof(int[]), true)] [InlineData(typeof(IList<int>), false)] [InlineData(typeof(IList<>), false)] public static void TestIsArray(Type t, bool expected) { Assert.Equal(expected, t.IsArray); } [Theory] [InlineData(typeof(int), false)] [InlineData(typeof(int[]), false)] [InlineData(typeof(IList<int>), false)] [InlineData(typeof(IList<>), false)] public static void TestIsByRef(Type t, bool expected) { Assert.Equal(expected, t.IsByRef); Assert.True(t.MakeByRefType().IsByRef); } [Theory] [InlineData(typeof(int), false)] [InlineData(typeof(int[]), false)] [InlineData(typeof(IList<int>), false)] [InlineData(typeof(IList<>), false)] [InlineData(typeof(int *), true)] public static void testIsPointer(Type t, bool expected) { Assert.Equal(expected, t.IsPointer); Assert.True(t.MakePointerType().IsPointer); } [Theory] [InlineData(typeof(int), false)] [InlineData(typeof(int[]), false)] [InlineData(typeof(IList<int>), true)] [InlineData(typeof(IList<>), false)] public static void TestIsConstructedGenericType(Type t, bool expected) { Assert.Equal(expected, t.IsConstructedGenericType); } [Theory] [InlineData(typeof(int), false)] [InlineData(typeof(int[]), false)] [InlineData(typeof(IList<int>), false)] [InlineData(typeof(IList<>), false)] public static void TestIsGenericParameter(Type t, bool expected) { Assert.Equal(expected, t.IsGenericParameter); } [Theory] [InlineData(typeof(int), false)] [InlineData(typeof(int[]), false)] [InlineData(typeof(Outside.Inside), true)] [InlineData(typeof(Outside.Inside[]), false)] [InlineData(typeof(Outside<int>), false)] [InlineData(typeof(Outside<int>.Inside<double>), true)] public static void TestIsNested(Type t, bool expected) { Assert.Equal(expected, t.IsNested); } [Theory] [InlineData(typeof(int), typeof(int))] [InlineData(typeof(int[]), typeof(int[]))] [InlineData(typeof(Outside<int>), typeof(Outside<int>))] public static void TestTypeHandle(Type t1, Type t2) { RuntimeTypeHandle r1 = t1.TypeHandle; RuntimeTypeHandle r2 = t2.TypeHandle; Assert.Equal(r1, r2); Assert.Equal(t1, Type.GetTypeFromHandle(r1)); Assert.Equal(t1, Type.GetTypeFromHandle(r2)); } [Fact] public static void TestGetTypeFromDefaultHandle() { Assert.Null(Type.GetTypeFromHandle(default(RuntimeTypeHandle))); } [Theory] [InlineData(typeof(int[]), 1)] [InlineData(typeof(int[,,]), 3)] public static void TestGetArrayRank(Type t, int expected) { Assert.Equal(expected, t.GetArrayRank()); } [Theory] [InlineData(typeof(int))] [InlineData(typeof(IList<int>))] [InlineData(typeof(IList<>))] public static void TestGetArrayRankInvalid(Type t) { Assert.Throws<ArgumentException>(() => t.GetArrayRank()); } [Theory] [InlineData(typeof(int), null)] [InlineData(typeof(Outside.Inside), null)] [InlineData(typeof(int[]), typeof(int))] [InlineData(typeof(Outside<int>.Inside<double>[]), typeof(Outside<int>.Inside<double>))] [InlineData(typeof(Outside<int>), null)] [InlineData(typeof(Outside<int>.Inside<double>), null)] public static void TestGetElementType(Type t, Type expected) { Assert.Equal(expected, t.GetElementType()); } [Theory] [InlineData(typeof(int), typeof(int[]))] public static void TestMakeArrayType(Type t, Type tArrayExpected) { Type tArray = t.MakeArrayType(); Assert.Equal(tArrayExpected, tArray); Assert.Equal(t, tArray.GetElementType()); Assert.True(tArray.IsArray); Assert.True(tArray.HasElementType); string s1 = t.ToString(); string s2 = tArray.ToString(); Assert.Equal(s2, s1 + "[]"); } [Theory] [InlineData(typeof(int))] public static void TestMakeByRefType(Type t) { Type tRef1 = t.MakeByRefType(); Type tRef2 = t.MakeByRefType(); Assert.Equal(tRef1, tRef2); Assert.True(tRef1.IsByRef); Assert.True(tRef1.HasElementType); Assert.Equal(t, tRef1.GetElementType()); string s1 = t.ToString(); string s2 = tRef1.ToString(); Assert.Equal(s2, s1 + "&"); } [Theory] [InlineData("System.Nullable`1[System.Int32]", typeof(int?))] [InlineData("System.Int32*", typeof(int*))] [InlineData("System.Int32**", typeof(int**))] [InlineData("Outside`1", typeof(Outside<>))] [InlineData("Outside`1+Inside`1", typeof(Outside<>.Inside<>))] [InlineData("Outside[]", typeof(Outside[]))] [InlineData("Outside[,,]", typeof(Outside[,,]))] [InlineData("Outside[][]", typeof(Outside[][]))] [InlineData("Outside`1[System.Nullable`1[System.Boolean]]", typeof(Outside<bool?>))] public static void TestGetTypeByName(string typeName, Type expectedType) { Type t = Type.GetType(typeName, throwOnError: false, ignoreCase: false); Assert.Equal(expectedType, t); t = Type.GetType(typeName.ToLower(), throwOnError: false, ignoreCase: true); Assert.Equal(expectedType, t); } [Theory] [InlineData("system.nullable`1[system.int32]", typeof(TypeLoadException), false)] [InlineData("System.NonExistingType", typeof(TypeLoadException), false)] [InlineData("", typeof(TypeLoadException), false)] [InlineData("System.Int32[,*,]", typeof(ArgumentException), false)] [InlineData("Outside`2", typeof(TypeLoadException), false)] [InlineData("Outside`1[System.Boolean, System.Int32]", typeof(ArgumentException), true)] public static void TestGetTypeByNameInvalid(string typeName, Type expectedException, bool alwaysThrowsException) { if (!alwaysThrowsException) { Type t = Type.GetType(typeName, throwOnError: false, ignoreCase: false); Assert.Null(t); } Assert.Throws(expectedException, () => Type.GetType(typeName, throwOnError: true, ignoreCase: false)); } [Fact] public static void Delimiter() { Assert.NotNull(Type.Delimiter); } [Theory] [InlineData(typeof(bool), TypeCode.Boolean)] [InlineData(typeof(byte), TypeCode.Byte)] [InlineData(typeof(char), TypeCode.Char)] [InlineData(typeof(DateTime), TypeCode.DateTime)] [InlineData(typeof(decimal), TypeCode.Decimal)] [InlineData(typeof(double), TypeCode.Double)] [InlineData(null, TypeCode.Empty)] [InlineData(typeof(short), TypeCode.Int16)] [InlineData(typeof(int), TypeCode.Int32)] [InlineData(typeof(long), TypeCode.Int64)] [InlineData(typeof(object), TypeCode.Object)] [InlineData(typeof(System.Nullable), TypeCode.Object)] [InlineData(typeof(Nullable<int>), TypeCode.Object)] [InlineData(typeof(Dictionary<,>), TypeCode.Object)] [InlineData(typeof(Exception), TypeCode.Object)] [InlineData(typeof(sbyte), TypeCode.SByte)] [InlineData(typeof(float), TypeCode.Single)] [InlineData(typeof(string), TypeCode.String)] [InlineData(typeof(ushort), TypeCode.UInt16)] [InlineData(typeof(uint), TypeCode.UInt32)] [InlineData(typeof(ulong), TypeCode.UInt64)] public static void GetTypeCode(Type t, TypeCode typeCode) { Assert.Equal(typeCode, Type.GetTypeCode(t)); } }
// Copyright (c) 2002-2003, Sony Computer Entertainment America // Copyright (c) 2002-2003, Craig Reynolds <[email protected]> // Copyright (C) 2007 Bjoern Graf <[email protected]> // Copyright (C) 2007 Michael Coles <[email protected]> // All rights reserved. // // This software is licensed as described in the file license.txt, which // you should have received as part of this distribution. The terms // are also available at http://www.codeplex.com/SharpSteer/Project/License.aspx. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Demo.PlugIns.AirCombat; using Demo.PlugIns.Arrival; using Demo.PlugIns.Boids; using Demo.PlugIns.Ctf; using Demo.PlugIns.FlowField; using Demo.PlugIns.GatewayPathFollowing; using Demo.PlugIns.LowSpeedTurn; using Demo.PlugIns.MapDrive; using Demo.PlugIns.MeshPathFollowing; using Demo.PlugIns.MultiplePursuit; using Demo.PlugIns.OneTurning; using Demo.PlugIns.Pedestrian; using Demo.PlugIns.Soccer; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using SharpSteer2; using SharpSteer2.Helpers; namespace Demo { /// <summary> /// This is the main type for your game /// </summary> public class Demo : Game { // these are the size of the offscreen drawing surface // in general, no one wants to change these as there // are all kinds of UI calculations and positions based // on these dimensions. // these are the size of the output window, ignored // on Xbox 360 private const int PREFERRED_WINDOW_WIDTH = 1024; private const int PREFERRED_WINDOW_HEIGHT = 640; public readonly GraphicsDeviceManager Graphics; private Effect _effect; EffectParameter _effectParamWorldViewProjection; readonly ContentManager _content; SpriteFont _font; SpriteBatch _spriteBatch; public Matrix WorldMatrix; public Matrix ViewMatrix; public Matrix ProjectionMatrix; // currently selected plug-in (user can choose or cycle through them) private static PlugIn _selectedPlugIn = null; // currently selected vehicle. Generally the one the camera follows and // for which additional information may be displayed. Clicking the mouse // near a vehicle causes it to become the Selected Vehicle. public static IVehicle SelectedVehicle = null; public static readonly Clock Clock = new Clock(); public static readonly Camera Camera = new Camera(); // some camera-related default constants public const float CAMERA2_D_ELEVATION = 8; public const float CAMERA_TARGET_DISTANCE = 13; public static readonly Vector3 CameraTargetOffset = new Vector3(0, CAMERA2_D_ELEVATION, 0); readonly Annotation _annotations = new Annotation(); public Demo() { Drawing.Game = this; Graphics = new GraphicsDeviceManager(this); _content = new ContentManager(Services); Graphics.PreferredBackBufferWidth = PREFERRED_WINDOW_WIDTH; Graphics.PreferredBackBufferHeight = PREFERRED_WINDOW_HEIGHT; _texts = new List<TextEntry>(); //FIXME: eijeijei. Annotation.Drawer = new Drawing(); // ReSharper disable ObjectCreationAsStatement //Constructing these silently updates a static list of all constructed plugins (euch) new FlowFieldPlugIn(_annotations); new ArrivalPlugIn(_annotations); new MeshPathFollowingPlugin(_annotations); new GatewayPathFollowingPlugin(_annotations); new AirCombatPlugin(_annotations); new BoidsPlugIn(_annotations); new LowSpeedTurnPlugIn(_annotations); new PedestrianPlugIn(_annotations); new CtfPlugIn(_annotations); new MapDrivePlugIn(_annotations); new MpPlugIn(_annotations); new SoccerPlugIn(_annotations); new OneTurningPlugIn(_annotations); // ReSharper restore ObjectCreationAsStatement IsFixedTimeStep = true; } public static void Init2dCamera(IVehicle selected, float distance = CAMERA_TARGET_DISTANCE, float elevation = CAMERA2_D_ELEVATION) { Position2dCamera(selected, distance, elevation); Camera.FixedDistanceDistance = distance; Camera.FixedDistanceVerticalOffset = elevation; Camera.Mode = Camera.CameraMode.FixedDistanceOffset; } public static void Init3dCamera(IVehicle selected, float distance = CAMERA_TARGET_DISTANCE, float elevation = CAMERA2_D_ELEVATION) { Position3dCamera(selected, distance); Camera.FixedDistanceDistance = distance; Camera.FixedDistanceVerticalOffset = elevation; Camera.Mode = Camera.CameraMode.FixedDistanceOffset; } public static void Position2dCamera(IVehicle selected, float distance = CAMERA_TARGET_DISTANCE, float elevation = CAMERA2_D_ELEVATION) { // position the camera as if in 3d: Position3dCamera(selected, distance); // then adjust for 3d: var position3D = Camera.Position; position3D.Y += elevation; Camera.Position = (position3D); } public static void Position3dCamera(IVehicle selected, float distance = CAMERA_TARGET_DISTANCE) { SelectedVehicle = selected; if (selected != null) { var behind = selected.Forward * -distance; Camera.Position = (selected.Position + behind); Camera.Target = selected.Position; } } // camera updating utility used by several (all?) plug-ins public static void UpdateCamera(float elapsedTime, IVehicle selected) { Camera.VehicleToTrack = selected; Camera.Update(elapsedTime, Clock.PausedState); } // ground plane grid-drawing utility used by several plug-ins public static void GridUtility(System.Numerics.Vector3 gridTarget) { // Math.Round off target to the nearest multiple of 2 (because the // checkboard grid with a pitch of 1 tiles with a period of 2) // then lower the grid a bit to put it under 2d annotation lines Vector3 gridCenter = new Vector3((float)(Math.Round(gridTarget.X * 0.5f) * 2), (float)(Math.Round(gridTarget.Y * 0.5f) * 2) - .05f, (float)(Math.Round(gridTarget.Z * 0.5f) * 2)); // colors for checkboard Color gray1 = new Color(new Vector3(0.27f)); Color gray2 = new Color(new Vector3(0.30f)); // draw 50x50 checkerboard grid with 50 squares along each side Drawing.DrawXZCheckerboardGrid(50, 50, gridCenter.FromXna(), gray1, gray2); // alternate style //Bnoerj.AI.Steering.Draw.drawXZLineGrid(50, 50, gridCenter, Color.Black); } // draws a gray disk on the XZ plane under a given vehicle public static void HighlightVehicleUtility(IVehicle vehicle) { if (vehicle != null) { Drawing.DrawXZDisk(vehicle.Radius, vehicle.Position, Color.LightGray, 20); } } // draws a gray circle on the XZ plane under a given vehicle public static void CircleHighlightVehicleUtility(IVehicle vehicle) { if (vehicle != null) { Drawing.DrawXZCircle(vehicle.Radius * 1.1f, vehicle.Position, Color.LightGray, 20); } } // draw a box around a vehicle aligned with its local space // xxx not used as of 11-20-02 public static void DrawBoxHighlightOnVehicle(IVehicle v, Color color) { if (v != null) { float diameter = v.Radius * 2; Vector3 size = new Vector3(diameter, diameter, diameter); Drawing.DrawBoxOutline(v, size.FromXna(), color); } } // draws a colored circle (perpendicular to view axis) around the center // of a given vehicle. The circle's radius is the vehicle's radius times // radiusMultiplier. public static void DrawCircleHighlightOnVehicle(IVehicle v, float radiusMultiplier, Color color) { if (v != null) { var cPosition = Camera.Position; Drawing.Draw3dCircle( v.Radius * radiusMultiplier, // adjusted radius v.Position, // center v.Position - cPosition, // view axis color, // drawing color 20); // circle segments } } // Find the AbstractVehicle whose screen position is nearest the current the // mouse position. Returns NULL if mouse is outside this window or if // there are no AbstractVehicle. internal static IVehicle VehicleNearestToMouse() { return null;//findVehicleNearestScreenPosition(mouseX, mouseY); } // Find the AbstractVehicle whose screen position is nearest the given window // coordinates, typically the mouse position. Returns NULL if there are no // AbstractVehicles. // // This works by constructing a line in 3d space between the camera location // and the "mouse point". Then it measures the distance from that line to the // centers of each AbstractVehicle. It returns the AbstractVehicle whose // distance is smallest. // // xxx Issues: Should the distanceFromLine test happen in "perspective space" // xxx or in "screen space"? Also: I think this would be happy to select a // xxx vehicle BEHIND the camera location. internal static IVehicle findVehicleNearestScreenPosition(int x, int y) { // find the direction from the camera position to the given pixel Vector3 direction = DirectionFromCameraToScreenPosition(x, y); // iterate over all vehicles to find the one whose center is nearest the // "eye-mouse" selection line float minDistance = float.MaxValue; // smallest distance found so far IVehicle nearest = null; // vehicle whose distance is smallest IEnumerable<IVehicle> vehicles = AllVehiclesOfSelectedPlugIn(); foreach (IVehicle vehicle in vehicles) { // distance from this vehicle's center to the selection line: float d = vehicle.Position.DistanceFromLine(Camera.Position, direction.FromXna()); // if this vehicle-to-line distance is the smallest so far, // store it and this vehicle in the selection registers. if (d < minDistance) { minDistance = d; nearest = vehicle; } } return nearest; } // return a normalized direction vector pointing from the camera towards a // given point on the screen: the ray that would be traced for that pixel static Vector3 DirectionFromCameraToScreenPosition(int x, int y) { #if TODO // Get window height, viewport, modelview and projection matrices // Unproject mouse position at near and far clipping planes gluUnProject(x, h - y, 0, mMat, pMat, vp, &un0x, &un0y, &un0z); gluUnProject(x, h - y, 1, mMat, pMat, vp, &un1x, &un1y, &un1z); // "direction" is the normalized difference between these far and near // unprojected points. Its parallel to the "eye-mouse" selection line. Vector3 diffNearFar = new Vector3(un1x - un0x, un1y - un0y, un1z - un0z); Vector3 direction = diffNearFar.normalize(); return direction; #else return Vector3.Up; #endif } // select the "next" plug-in, cycling through "plug-in selection order" static void SelectDefaultPlugIn() { PlugIn.SortBySelectionOrder(); _selectedPlugIn = PlugIn.FindDefault(); } // open the currently selected plug-in static void OpenSelectedPlugIn() { Camera.Reset(); SelectedVehicle = null; _selectedPlugIn.Open(); } static void ResetSelectedPlugIn() { _selectedPlugIn.Reset(); } static void CloseSelectedPlugIn() { _selectedPlugIn.Close(); SelectedVehicle = null; } // return a group (an STL vector of AbstractVehicle pointers) of all // vehicles(/agents/characters) defined by the currently selected PlugIn static IEnumerable<IVehicle> AllVehiclesOfSelectedPlugIn() { return _selectedPlugIn.Vehicles; } // select the "next" vehicle: the one listed after the currently selected one // in allVehiclesOfSelectedPlugIn static void SelectNextVehicle() { if (SelectedVehicle != null) { // get a container of all vehicles IVehicle[] all = AllVehiclesOfSelectedPlugIn().ToArray(); // find selected vehicle in container int i = Array.FindIndex(all, v => v != null && v == SelectedVehicle); if (i >= 0 && i < all.Length) { SelectedVehicle = i == all.Length - 1 ? all[0] : all[i + 1]; } else { // if the search failed, use NULL SelectedVehicle = null; } } } static void UpdateSelectedPlugIn(float currentTime, float elapsedTime) { // switch to Update phase PushPhase(Phase.Update); // service queued reset request, if any DoDelayedResetPlugInXXX(); // if no vehicle is selected, and some exist, select the first one if (SelectedVehicle == null) { IVehicle[] all = AllVehiclesOfSelectedPlugIn().ToArray(); if (all.Length > 0) SelectedVehicle = all[0]; } // invoke selected PlugIn's Update method _selectedPlugIn.Update(currentTime, elapsedTime); // return to previous phase PopPhase(); } static bool _delayedResetPlugInXXX = false; internal static void QueueDelayedResetPlugInXXX() { _delayedResetPlugInXXX = true; } static void DoDelayedResetPlugInXXX() { if (_delayedResetPlugInXXX) { ResetSelectedPlugIn(); _delayedResetPlugInXXX = false; } } static void PushPhase(Phase newPhase) { // update timer for current (old) phase: add in time since last switch UpdatePhaseTimers(); // save old phase _phaseStack[_phaseStackIndex++] = _phase; // set new phase _phase = newPhase; // check for stack overflow if (_phaseStackIndex >= PHASE_STACK_SIZE) { throw new InvalidOperationException("Phase stack has overflowed"); } } static void PopPhase() { // update timer for current (old) phase: add in time since last switch UpdatePhaseTimers(); // restore old phase _phase = _phaseStack[--_phaseStackIndex]; } // redraw graphics for the currently selected plug-in static void RedrawSelectedPlugIn(float currentTime, float elapsedTime) { // switch to Draw phase PushPhase(Phase.Draw); // invoke selected PlugIn's Draw method _selectedPlugIn.Redraw(currentTime, elapsedTime); // draw any annotation queued up during selected PlugIn's Update method Drawing.AllDeferredLines(); Drawing.AllDeferredCirclesOrDisks(); // return to previous phase PopPhase(); } int _frameRatePresetIndex = 0; // cycle through frame rate presets (XXX move this to OpenSteerDemo) void SelectNextPresetFrameRate() { // note that the cases are listed in reverse order, and that // the default is case 0 which causes the index to wrap around switch (++_frameRatePresetIndex) { case 3: // animation mode at 60 fps Clock.FixedFrameRate = 60; Clock.AnimationMode = true; Clock.VariableFrameRateMode = false; break; case 2: // real-time fixed frame rate mode at 60 fps Clock.FixedFrameRate = 60; Clock.AnimationMode = false; Clock.VariableFrameRateMode = false; break; case 1: // real-time fixed frame rate mode at 24 fps Clock.FixedFrameRate = 24; Clock.AnimationMode = false; Clock.VariableFrameRateMode = false; break; default: // real-time variable frame rate mode ("as fast as possible") _frameRatePresetIndex = 0; Clock.FixedFrameRate = 0; Clock.AnimationMode = false; Clock.VariableFrameRateMode = true; break; } } private static void SelectNextPlugin() { CloseSelectedPlugIn(); _selectedPlugIn = _selectedPlugIn.Next(); OpenSelectedPlugIn(); } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { SelectDefaultPlugIn(); OpenSelectedPlugIn(); base.Initialize(); } /// <summary> /// Load your graphics content. If loadAllContent is true, you should /// load content from both ResourceManagementMode pools. Otherwise, just /// load ResourceManagementMode.Manual content. /// </summary> protected override void LoadContent() { base.LoadContent(); _font = _content.Load<SpriteFont>("Content/Fonts/SegoeUiMono"); _spriteBatch = new SpriteBatch(Graphics.GraphicsDevice); _effect = new BasicEffect(GraphicsDevice) { VertexColorEnabled = true, }; _effectParamWorldViewProjection = _effect.Parameters["WorldViewProj"]; } /// <summary> /// Unload your graphics content. If unloadAllContent is true, you should /// unload content from both ResourceManagementMode pools. Otherwise, just /// unload ResourceManagementMode.Manual content. Manual content will get /// Disposed by the GraphicsDevice during a Reset. /// </summary> protected override void UnloadContent() { _content.Unload(); } KeyboardState _prevKeyState = new KeyboardState(); bool IsKeyDown(KeyboardState keyState, Keys key) { return _prevKeyState.IsKeyDown(key) == false && keyState.IsKeyDown(key); } protected override void Update(GameTime gameTime) { GamePadState padState = GamePad.GetState(PlayerIndex.One); KeyboardState keyState = Keyboard.GetState(); if (padState.Buttons.Back == ButtonState.Pressed || keyState.IsKeyDown(Keys.Escape)) Exit(); if (IsKeyDown(keyState, Keys.R)) ResetSelectedPlugIn(); if (IsKeyDown(keyState, Keys.S)) SelectNextVehicle(); if (IsKeyDown(keyState, Keys.A)) _annotations.IsEnabled = !_annotations.IsEnabled; if (IsKeyDown(keyState, Keys.Space)) Clock.TogglePausedState(); if (IsKeyDown(keyState, Keys.C)) Camera.SelectNextMode(); if (IsKeyDown(keyState, Keys.F)) SelectNextPresetFrameRate(); if (IsKeyDown(keyState, Keys.Tab)) SelectNextPlugin(); for (Keys key = Keys.F1; key <= Keys.F10; key++) { if (IsKeyDown(keyState, key)) { _selectedPlugIn.HandleFunctionKeys(key); } } _prevKeyState = keyState; // update global simulation clock Clock.Update(); // start the phase timer (XXX to accurately measure "overhead" time this // should be in displayFunc, or somehow account for time outside this // routine) InitPhaseTimers(); // run selected PlugIn (with simulation's current time and step size) UpdateSelectedPlugIn(Clock.TotalSimulationTime, Clock.ElapsedSimulationTime); WorldMatrix = Matrix.Identity; Vector3 pos = Camera.Position.ToXna(); Vector3 lookAt = Camera.Target.ToXna(); Vector3 up = Camera.Up.ToXna(); ViewMatrix = Matrix.CreateLookAt(new Vector3(pos.X, pos.Y, pos.Z), new Vector3(lookAt.X, lookAt.Y, lookAt.Z), new Vector3(up.X, up.Y, up.Z)); ProjectionMatrix = Matrix.CreatePerspectiveFieldOfView( MathHelper.ToRadians(45), // 45 degree angle Graphics.GraphicsDevice.Viewport.Width / (float)Graphics.GraphicsDevice.Viewport.Height, 1.0f, 400.0f); base.Update(gameTime); } /// <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) { Graphics.GraphicsDevice.Clear(Color.CornflowerBlue); Graphics.GraphicsDevice.DepthStencilState = DepthStencilState.DepthRead; Graphics.GraphicsDevice.BlendState = BlendState.NonPremultiplied; Graphics.GraphicsDevice.RasterizerState = RasterizerState.CullNone; Matrix worldViewProjection = WorldMatrix * ViewMatrix * ProjectionMatrix; _effectParamWorldViewProjection.SetValue(worldViewProjection); _effect.CurrentTechnique.Passes[0].Apply(); // redraw selected PlugIn (based on real time) RedrawSelectedPlugIn(Clock.TotalRealTime, Clock.ElapsedRealTime); // Draw some sample text. _spriteBatch.Begin(); float cw = _font.MeasureString("M").X; float lh = _font.LineSpacing; foreach (TextEntry text in _texts) _spriteBatch.DrawString(_font, text.Text, text.Position.ToXna(), text.Color); _texts.Clear(); // get smoothed phase timer information float ptd = PhaseTimerDraw; float ptu = PhaseTimerUpdate; float pto = PhaseTimerOverhead; float smoothRate = Clock.SmoothingRate; Utilities.BlendIntoAccumulator(smoothRate, ptd, ref _smoothedTimerDraw); Utilities.BlendIntoAccumulator(smoothRate, ptu, ref _smoothedTimerUpdate); Utilities.BlendIntoAccumulator(smoothRate, pto, ref _smoothedTimerOverhead); // keep track of font metrics and start of next line Vector2 screenLocation = new Vector2(cw, lh / 2); _spriteBatch.DrawString(_font, String.Format("Camera: {0}", Camera.ModeName), screenLocation, Color.White); screenLocation.Y += lh; _spriteBatch.DrawString(_font, String.Format("PlugIn: {0}", _selectedPlugIn.Name), screenLocation, Color.White); screenLocation = new Vector2(cw, PREFERRED_WINDOW_HEIGHT - 5.5f * lh); _spriteBatch.DrawString(_font, String.Format("Update: {0}", GetPhaseTimerFps(_smoothedTimerUpdate)), screenLocation, Color.White); screenLocation.Y += lh; _spriteBatch.DrawString(_font, String.Format("Draw: {0}", GetPhaseTimerFps(_smoothedTimerDraw)), screenLocation, Color.White); screenLocation.Y += lh; _spriteBatch.DrawString(_font, String.Format("Other: {0}", GetPhaseTimerFps(_smoothedTimerOverhead)), screenLocation, Color.White); screenLocation.Y += 1.5f * lh; // target and recent average frame rates int targetFPS = Clock.FixedFrameRate; float smoothedFPS = Clock.SmoothedFPS; // describe clock mode and frame rate statistics StringBuilder sb = new StringBuilder(); sb.Append("Clock: "); if (Clock.AnimationMode) { float ratio = smoothedFPS / targetFPS; sb.AppendFormat("animation mode ({0} fps, display {1} fps {2}% of nominal speed)", targetFPS, Math.Round(smoothedFPS), (int)(100 * ratio)); } else { sb.Append("real-time mode, "); if (Clock.VariableFrameRateMode) { sb.AppendFormat("variable frame rate ({0} fps)", Math.Round(smoothedFPS)); } else { sb.AppendFormat("fixed frame rate (target: {0} actual: {1}, ", targetFPS, Math.Round(smoothedFPS)); // create usage description character string var str = String.Format("usage: {0:0}%", Clock.SmoothedUsage); float x = screenLocation.X + sb.Length * cw; for (int i = 0; i < str.Length; i++) sb.Append(" "); sb.Append(")"); // display message in lower left corner of window // (draw in red if the instantaneous usage is 100% or more) float usage = Clock.Usage; _spriteBatch.DrawString(_font, str, new Vector2(x, screenLocation.Y), (usage >= 100) ? Color.Red : Color.White); } } _spriteBatch.DrawString(_font, sb.ToString(), screenLocation, Color.White); _spriteBatch.End(); base.Draw(gameTime); } static String GetPhaseTimerFps(float phaseTimer) { // different notation for variable and fixed frame rate if (Clock.VariableFrameRateMode) { // express as FPS (inverse of phase time) return String.Format("{0:0.00000} ({1:0} FPS)", phaseTimer, 1 / phaseTimer); } // quantify time as a percentage of frame time double fps = Clock.FixedFrameRate;// 1.0f / TargetElapsedTime.TotalSeconds; return String.Format("{0:0.00000} ({1:0}% of 1/{2}sec)", phaseTimer, (100.0f * phaseTimer) / (1.0f / fps), (int)fps); } private enum Phase { Overhead, Update, Draw, Count } static Phase _phase; const int PHASE_STACK_SIZE = 5; static readonly Phase[] _phaseStack = new Phase[PHASE_STACK_SIZE]; static int _phaseStackIndex = 0; static readonly float[] _phaseTimers = new float[(int)Phase.Count]; static float _phaseTimerBase = 0; // draw text showing (smoothed, rounded) "frames per second" rate // (and later a bunch of related stuff was dumped here, a reorg would be nice) static float _smoothedTimerDraw = 0; static float _smoothedTimerUpdate = 0; static float _smoothedTimerOverhead = 0; public static bool IsDrawPhase { get { return _phase == Phase.Draw; } } static float PhaseTimerDraw { get { return _phaseTimers[(int)Phase.Draw]; } } static float PhaseTimerUpdate { get { return _phaseTimers[(int)Phase.Update]; } } // XXX get around shortcomings in current implementation, see note // XXX in updateSimulationAndRedraw #if IGNORE float phaseTimerOverhead { get { return phaseTimers[(int)Phase.overheadPhase]; } } #else static float PhaseTimerOverhead { get { return Clock.ElapsedRealTime - (PhaseTimerDraw + PhaseTimerUpdate); } } #endif static void InitPhaseTimers() { _phaseTimers[(int)Phase.Draw] = 0; _phaseTimers[(int)Phase.Update] = 0; _phaseTimers[(int)Phase.Overhead] = 0; _phaseTimerBase = Clock.TotalRealTime; } static void UpdatePhaseTimers() { float currentRealTime = Clock.RealTimeSinceFirstClockUpdate(); _phaseTimers[(int)_phase] += currentRealTime - _phaseTimerBase; _phaseTimerBase = currentRealTime; } readonly List<TextEntry> _texts; public void AddText(TextEntry text) { _texts.Add(text); } } }
//--------------------------------------------------------------------- // <copyright file="Session.cs" company="Microsoft Corporation"> // Copyright (c) 1999, Microsoft Corporation. All rights reserved. // </copyright> // <summary> // Part of the Deployment Tools Foundation project. // </summary> //--------------------------------------------------------------------- namespace Microsoft.PackageManagement.Msi.Internal.Deployment.WindowsInstaller { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; /// <summary> /// The Session object controls the installation process. It opens the /// install database, which contains the installation tables and data. /// </summary> /// <remarks><p> /// This object is associated with a standard set of action functions, /// each performing particular operations on data from one or more tables. Additional /// custom actions may be added for particular product installations. The basic engine /// function is a sequencer that fetches sequential records from a designated sequence /// table, evaluates any specified condition expression, and executes the designated /// action. Actions not recognized by the engine are deferred to the UI handler object /// for processing, usually dialog box sequences. /// </p><p> /// Note that only one Session object can be opened by a single process. /// </p></remarks> internal sealed class Session : InstallerHandle, IFormatProvider { private Database database; private CustomActionData customActionData; private bool sessionAccessValidated = false; internal Session(IntPtr handle, bool ownsHandle) : base(handle, ownsHandle) { } /// <summary> /// Gets the Database for the install session. /// </summary> /// <exception cref="InvalidHandleException">the Session handle is invalid</exception> /// <exception cref="InstallerException">the Database cannot be accessed</exception> /// <remarks><p> /// Normally there is no need to close this Database object. The same object can be /// used throughout the lifetime of the Session, and it will be closed when the Session /// is closed. /// </p><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msigetactivedatabase.asp">MsiGetActiveDatabase</a> /// </p></remarks> [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public Database Database { get { if (this.database == null || this.database.IsClosed) { lock (this.Sync) { if (this.database == null || this.database.IsClosed) { this.ValidateSessionAccess(); int hDb = RemotableNativeMethods.MsiGetActiveDatabase((int) this.Handle); if (hDb == 0) { throw new InstallerException(); } this.database = new Database((IntPtr) hDb, true, "", DatabaseOpenMode.ReadOnly); } } } return this.database; } } /// <summary> /// Gets the numeric language ID used by the current install session. /// </summary> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msigetlanguage.asp">MsiGetLanguage</a> /// </p></remarks> public int Language { get { return (int) RemotableNativeMethods.MsiGetLanguage((int) this.Handle); } } /// <summary> /// Gets or sets the string value of a named installer property, as maintained by the /// Session object in the in-memory Property table, or, if it is prefixed with a percent /// sign (%), the value of a system environment variable for the current process. /// </summary> /// <exception cref="InvalidHandleException">the Session handle is invalid</exception> /// <remarks><p> /// Win32 MSI APIs: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msigetproperty.asp">MsiGetProperty</a>, /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msisetproperty.asp">MsiSetProperty</a> /// </p></remarks> public string this[string property] { get { if (string.IsNullOrWhiteSpace(property)) { throw new ArgumentNullException("property"); } if (!this.sessionAccessValidated && !Session.NonImmediatePropertyNames.Contains(property)) { this.ValidateSessionAccess(); } StringBuilder buf = new StringBuilder(); uint bufSize = 0; uint ret = RemotableNativeMethods.MsiGetProperty((int) this.Handle, property, buf, ref bufSize); if (ret == (uint) NativeMethods.Error.MORE_DATA) { buf.Capacity = (int) ++bufSize; ret = RemotableNativeMethods.MsiGetProperty((int) this.Handle, property, buf, ref bufSize); } if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } return buf.ToString(); } set { if (string.IsNullOrWhiteSpace(property)) { throw new ArgumentNullException("property"); } this.ValidateSessionAccess(); if (value == null) { value = String.Empty; } uint ret = RemotableNativeMethods.MsiSetProperty((int) this.Handle, property, value); if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } } } /// <summary> /// Creates a new Session object from an integer session handle. /// </summary> /// <param name="handle">Integer session handle</param> /// <param name="ownsHandle">true to close the handle when this object is disposed or finalized</param> /// <remarks><p> /// This method is only provided for interop purposes. A Session object /// should normally be obtained by calling <see cref="Installer.OpenPackage(Database,bool)"/> /// or <see cref="Installer.OpenProduct"/>. /// </p></remarks> public static Session FromHandle(IntPtr handle, bool ownsHandle) { return new Session(handle, ownsHandle); } /// <summary> /// Performs any enabled logging operations and defers execution to the UI handler /// object associated with the engine. /// </summary> /// <param name="messageType">Type of message to be processed</param> /// <param name="record">Contains message-specific fields</param> /// <returns>A message-dependent return value</returns> /// <exception cref="InvalidHandleException">the Session or Record handle is invalid</exception> /// <exception cref="ArgumentOutOfRangeException">an invalid message kind is specified</exception> /// <exception cref="InstallCanceledException">the user exited the installation</exception> /// <exception cref="InstallerException">the message-handler failed for an unknown reason</exception> /// <remarks><p> /// Logging may be selectively enabled for the various message types. /// See the <see cref="Installer.EnableLog(InstallLogModes,string)"/> method. /// </p><p> /// If record field 0 contains a formatting string, it is used to format the data in /// the other fields. Else if the message is an error, warning, or user message, an attempt /// is made to find a message template in the Error table for the current database using the /// error number found in field 1 of the record for message types and return values. /// </p><p> /// The <paramref name="messageType"/> parameter may also include message-box flags from /// the following enumerations: System.Windows.Forms.MessageBoxButtons, /// System.Windows.Forms.MessageBoxDefaultButton, System.Windows.Forms.MessageBoxIcon. These /// flags can be combined with the InstallMessage with a bitwise OR. /// </p><p> /// Note, this method never returns Cancel or Error values. Instead, appropriate /// exceptions are thrown in those cases. /// </p><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiprocessmessage.asp">MsiProcessMessage</a> /// </p></remarks> [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] public MessageResult Message(InstallMessage messageType, Record record) { if (record == null) { throw new ArgumentNullException("record"); } int ret = RemotableNativeMethods.MsiProcessMessage((int) this.Handle, (uint) messageType, (int) record.Handle); if (ret < 0) { throw new InstallerException(); } else if (ret == (int) MessageResult.Cancel) { throw new InstallCanceledException(); } return (MessageResult) ret; } /// <summary> /// Writes a message to the log, if logging is enabled. /// </summary> /// <param name="msg">The line to be written to the log</param> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiprocessmessage.asp">MsiProcessMessage</a> /// </p></remarks> public void Log(string msg) { if (msg == null) { throw new ArgumentNullException("msg"); } using (Record rec = new Record(0)) { rec.FormatString = msg; this.Message(InstallMessage.Info, rec); } } /// <summary> /// Writes a formatted message to the log, if logging is enabled. /// </summary> /// <param name="format">The line to be written to the log, containing 0 or more format specifiers</param> /// <param name="args">An array containing 0 or more objects to be formatted</param> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiprocessmessage.asp">MsiProcessMessage</a> /// </p></remarks> public void Log(string format, params object[] args) { this.Log(String.Format(CultureInfo.InvariantCulture, format, args)); } /// <summary> /// Evaluates a logical expression containing symbols and values. /// </summary> /// <param name="condition">conditional expression</param> /// <returns>The result of the condition evaluation</returns> /// <exception cref="InvalidHandleException">the Session handle is invalid</exception> /// <exception cref="ArgumentNullException">the condition is null or empty</exception> /// <exception cref="InvalidOperationException">the conditional expression is invalid</exception> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msievaluatecondition.asp">MsiEvaluateCondition</a> /// </p></remarks> public bool EvaluateCondition(string condition) { if (string.IsNullOrWhiteSpace(condition)) { throw new ArgumentNullException("condition"); } uint value = RemotableNativeMethods.MsiEvaluateCondition((int) this.Handle, condition); if (value == 0) { return false; } else if (value == 1) { return true; } else { throw new InvalidOperationException(); } } /// <summary> /// Evaluates a logical expression containing symbols and values, specifying a default /// value to be returned in case the condition is empty. /// </summary> /// <param name="condition">conditional expression</param> /// <param name="defaultValue">value to return if the condition is empty</param> /// <returns>The result of the condition evaluation</returns> /// <exception cref="InvalidHandleException">the Session handle is invalid</exception> /// <exception cref="InvalidOperationException">the conditional expression is invalid</exception> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msievaluatecondition.asp">MsiEvaluateCondition</a> /// </p></remarks> public bool EvaluateCondition(string condition, bool defaultValue) { if (condition == null) { throw new ArgumentNullException("condition"); } else if (condition.Length == 0) { return defaultValue; } else { this.ValidateSessionAccess(); return this.EvaluateCondition(condition); } } /// <summary> /// Formats a string containing installer properties. /// </summary> /// <param name="format">A format string containing property tokens</param> /// <returns>A formatted string containing property data</returns> /// <exception cref="InvalidHandleException">the Record handle is invalid</exception> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiformatrecord.asp">MsiFormatRecord</a> /// </p></remarks> [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] public string Format(string format) { if (format == null) { throw new ArgumentNullException("format"); } using (Record formatRec = new Record(0)) { formatRec.FormatString = format; return formatRec.ToString(this); } } /// <summary> /// Returns a formatted string from record data. /// </summary> /// <param name="record">Record object containing a template and data to be formatted. /// The template string must be set in field 0 followed by any referenced data parameters.</param> /// <returns>A formatted string containing the record data</returns> /// <exception cref="InvalidHandleException">the Record handle is invalid</exception> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiformatrecord.asp">MsiFormatRecord</a> /// </p></remarks> public string FormatRecord(Record record) { if (record == null) { throw new ArgumentNullException("record"); } return record.ToString(this); } /// <summary> /// Returns a formatted string from record data using a specified format. /// </summary> /// <param name="record">Record object containing a template and data to be formatted</param> /// <param name="format">Format string to be used instead of field 0 of the Record</param> /// <returns>A formatted string containing the record data</returns> /// <exception cref="InvalidHandleException">the Record handle is invalid</exception> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiformatrecord.asp">MsiFormatRecord</a> /// </p></remarks> [Obsolete("This method is obsolete because it has undesirable side-effects. As an alternative, set the Record's " + "FormatString property separately before calling the FormatRecord() override that takes only the Record parameter.")] public string FormatRecord(Record record, string format) { if (record == null) { throw new ArgumentNullException("record"); } return record.ToString(format, this); } /// <summary> /// Retrieves product properties (not session properties) from the product database. /// </summary> /// <returns>Value of the property, or an empty string if the property is not set.</returns> /// <remarks><p> /// Note this is not the correct method for getting ordinary session properties. For that, /// see the indexer on the Session class. /// </p><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msigetproductproperty.asp">MsiGetProductProperty</a> /// </p></remarks> public string GetProductProperty(string property) { if (string.IsNullOrWhiteSpace(property)) { throw new ArgumentNullException("property"); } this.ValidateSessionAccess(); StringBuilder buf = new StringBuilder(); uint bufSize = (uint) buf.Capacity; uint ret = NativeMethods.MsiGetProductProperty((int) this.Handle, property, buf, ref bufSize); if (ret == (uint) NativeMethods.Error.MORE_DATA) { buf.Capacity = (int) ++bufSize; ret = NativeMethods.MsiGetProductProperty((int) this.Handle, property, buf, ref bufSize); } if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } return buf.ToString(); } /// <summary> /// Gets an accessor for components in the current session. /// </summary> public ComponentInfoCollection Components { get { this.ValidateSessionAccess(); return new ComponentInfoCollection(this); } } /// <summary> /// Gets an accessor for features in the current session. /// </summary> public FeatureInfoCollection Features { get { this.ValidateSessionAccess(); return new FeatureInfoCollection(this); } } /// <summary> /// Checks to see if sufficient disk space is present for the current installation. /// </summary> /// <returns>True if there is sufficient disk space; false otherwise.</returns> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiverifydiskspace.asp">MsiVerifyDiskSpace</a> /// </p></remarks> public bool VerifyDiskSpace() { this.ValidateSessionAccess(); uint ret = RemotableNativeMethods.MsiVerifyDiskSpace((int)this.Handle); if (ret == (uint) NativeMethods.Error.DISK_FULL) { return false; } else if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } return true; } /// <summary> /// Gets the total disk space per drive required for the installation. /// </summary> /// <returns>A list of InstallCost structures, specifying the cost for each drive</returns> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msienumcomponentcosts.asp">MsiEnumComponentCosts</a> /// </p></remarks> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public IList<InstallCost> GetTotalCost() { this.ValidateSessionAccess(); IList<InstallCost> costs = new List<InstallCost>(); StringBuilder driveBuf = new StringBuilder(20); for (uint i = 0; true; i++) { int cost, tempCost; uint driveBufSize = (uint) driveBuf.Capacity; uint ret = RemotableNativeMethods.MsiEnumComponentCosts( (int) this.Handle, null, i, (int) InstallState.Default, driveBuf, ref driveBufSize, out cost, out tempCost); if (ret == (uint) NativeMethods.Error.NO_MORE_ITEMS) break; if (ret == (uint) NativeMethods.Error.MORE_DATA) { driveBuf.Capacity = (int) ++driveBufSize; ret = RemotableNativeMethods.MsiEnumComponentCosts( (int) this.Handle, null, i, (int) InstallState.Default, driveBuf, ref driveBufSize, out cost, out tempCost); } if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } costs.Add(new InstallCost(driveBuf.ToString(), cost * 512L, tempCost * 512L)); } return costs; } /// <summary> /// Gets the designated mode flag for the current install session. /// </summary> /// <param name="mode">The type of mode to be checked.</param> /// <returns>The value of the designated mode flag.</returns> /// <exception cref="InvalidHandleException">the Session handle is invalid</exception> /// <exception cref="ArgumentOutOfRangeException">an invalid mode flag was specified</exception> /// <remarks><p> /// Note that only the following run modes are available to read from /// a deferred custom action:<list type="bullet"> /// <item><description><see cref="InstallRunMode.Scheduled"/></description></item> /// <item><description><see cref="InstallRunMode.Rollback"/></description></item> /// <item><description><see cref="InstallRunMode.Commit"/></description></item> /// </list> /// </p><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msigetmode.asp">MsiGetMode</a> /// </p></remarks> public bool GetMode(InstallRunMode mode) { return RemotableNativeMethods.MsiGetMode((int) this.Handle, (uint) mode); } /// <summary> /// Sets the designated mode flag for the current install session. /// </summary> /// <param name="mode">The type of mode to be set.</param> /// <param name="value">The desired value of the mode.</param> /// <exception cref="InvalidHandleException">the Session handle is invalid</exception> /// <exception cref="ArgumentOutOfRangeException">an invalid mode flag was specified</exception> /// <exception cref="InvalidOperationException">the mode cannot not be set</exception> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msisetmode.asp">MsiSetMode</a> /// </p></remarks> public void SetMode(InstallRunMode mode, bool value) { this.ValidateSessionAccess(); uint ret = RemotableNativeMethods.MsiSetMode((int) this.Handle, (uint) mode, value); if (ret != 0) { if (ret == (uint) NativeMethods.Error.ACCESS_DENIED) { throw new InvalidOperationException(); } else { throw InstallerException.ExceptionFromReturnCode(ret); } } } /// <summary> /// Gets the full path to the designated folder on the source media or server image. /// </summary> /// <exception cref="ArgumentException">the folder was not found in the Directory table</exception> /// <exception cref="InvalidHandleException">the Session handle is invalid</exception> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msigetsourcepath.asp">MsiGetSourcePath</a> /// </p></remarks> public string GetSourcePath(string directory) { if (string.IsNullOrWhiteSpace(directory)) { throw new ArgumentNullException("directory"); } this.ValidateSessionAccess(); StringBuilder buf = new StringBuilder(); uint bufSize = 0; uint ret = RemotableNativeMethods.MsiGetSourcePath((int) this.Handle, directory, buf, ref bufSize); if (ret == (uint) NativeMethods.Error.MORE_DATA) { buf.Capacity = (int) ++bufSize; ret = ret = RemotableNativeMethods.MsiGetSourcePath((int) this.Handle, directory, buf, ref bufSize); } if (ret != 0) { if (ret == (uint) NativeMethods.Error.DIRECTORY) { throw InstallerException.ExceptionFromReturnCode(ret, directory); } else { throw InstallerException.ExceptionFromReturnCode(ret); } } return buf.ToString(); } /// <summary> /// Gets the full path to the designated folder on the installation target drive. /// </summary> /// <exception cref="ArgumentException">the folder was not found in the Directory table</exception> /// <exception cref="InvalidHandleException">the Session handle is invalid</exception> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msigettargetpath.asp">MsiGetTargetPath</a> /// </p></remarks> public string GetTargetPath(string directory) { if (string.IsNullOrWhiteSpace(directory)) { throw new ArgumentNullException("directory"); } this.ValidateSessionAccess(); StringBuilder buf = new StringBuilder(); uint bufSize = 0; uint ret = RemotableNativeMethods.MsiGetTargetPath((int) this.Handle, directory, buf, ref bufSize); if (ret == (uint) NativeMethods.Error.MORE_DATA) { buf.Capacity = (int) ++bufSize; ret = ret = RemotableNativeMethods.MsiGetTargetPath((int) this.Handle, directory, buf, ref bufSize); } if (ret != 0) { if (ret == (uint) NativeMethods.Error.DIRECTORY) { throw InstallerException.ExceptionFromReturnCode(ret, directory); } else { throw InstallerException.ExceptionFromReturnCode(ret); } } return buf.ToString(); } /// <summary> /// Sets the full path to the designated folder on the installation target drive. /// </summary> /// <exception cref="ArgumentException">the folder was not found in the Directory table</exception> /// <exception cref="InvalidHandleException">the Session handle is invalid</exception> /// <remarks><p> /// Setting the target path of a directory changes the path specification for the directory /// in the in-memory Directory table. Also, the path specifications of all other path objects /// in the table that are either subordinate or equivalent to the changed path are updated /// to reflect the change. The properties for each affected path are also updated. /// </p><p> /// If an error occurs in this function, all updated paths and properties revert to /// their previous values. Therefore, it is safe to treat errors returned by this function /// as non-fatal. /// </p><p> /// Do not attempt to configure the target path if the components using those paths /// are already installed for the current user or for a different user. Check the /// ProductState property before setting the target path to determine if the product /// containing this component is installed. /// </p><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msisettargetpath.asp">MsiSetTargetPath</a> /// </p></remarks> public void SetTargetPath(string directory, string value) { if (string.IsNullOrWhiteSpace(directory)) { throw new ArgumentNullException("directory"); } if (value == null) { throw new ArgumentNullException("value"); } this.ValidateSessionAccess(); uint ret = RemotableNativeMethods.MsiSetTargetPath((int) this.Handle, directory, value); if (ret != 0) { if (ret == (uint) NativeMethods.Error.DIRECTORY) { throw InstallerException.ExceptionFromReturnCode(ret, directory); } else { throw InstallerException.ExceptionFromReturnCode(ret); } } } /// <summary> /// Sets the install level for the current installation to a specified value and /// recalculates the Select and Installed states for all features in the Feature /// table. Also sets the Action state of each component in the Component table based /// on the new level. /// </summary> /// <param name="installLevel">New install level</param> /// <exception cref="InvalidHandleException">the Session handle is invalid</exception> /// <remarks><p> /// The SetInstallLevel method sets the following:<list type="bullet"> /// <item><description>The installation level for the current installation to a specified value</description></item> /// <item><description>The Select and Installed states for all features in the Feature table</description></item> /// <item><description>The Action state of each component in the Component table, based on the new level</description></item> /// </list> /// If 0 or a negative number is passed in the ilnstallLevel parameter, /// the current installation level does not change, but all features are still /// updated based on the current installation level. /// </p><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msisetinstalllevel.asp">MsiSetInstallLevel</a> /// </p></remarks> public void SetInstallLevel(int installLevel) { this.ValidateSessionAccess(); uint ret = RemotableNativeMethods.MsiSetInstallLevel((int) this.Handle, installLevel); if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } } /// <summary> /// Executes a built-in action, custom action, or user-interface wizard action. /// </summary> /// <param name="action">Name of the action to execute. Case-sensitive.</param> /// <exception cref="InvalidHandleException">the Session handle is invalid</exception> /// <exception cref="InstallCanceledException">the user exited the installation</exception> /// <remarks><p> /// The DoAction method executes the action that corresponds to the name supplied. If the /// name is not recognized by the installer as a built-in action or as a custom action in /// the CustomAction table, the name is passed to the user-interface handler object, which /// can invoke a function or a dialog box. If a null action name is supplied, the installer /// uses the upper-case value of the ACTION property as the action to perform. If no property /// value is defined, the default action is performed, defined as "INSTALL". /// </p><p> /// Actions that update the system, such as the InstallFiles and WriteRegistryValues /// actions, cannot be run by calling MsiDoAction. The exception to this rule is if DoAction /// is called from a custom action that is scheduled in the InstallExecuteSequence table /// between the InstallInitialize and InstallFinalize actions. Actions that do not update the /// system, such as AppSearch or CostInitialize, can be called. /// </p><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msidoaction.asp">MsiDoAction</a> /// </p></remarks> public void DoAction(string action) { this.DoAction(action, null); } /// <summary> /// Executes a built-in action, custom action, or user-interface wizard action. /// </summary> /// <param name="action">Name of the action to execute. Case-sensitive.</param> /// <param name="actionData">Optional data to be passed to a deferred custom action.</param> /// <exception cref="InvalidHandleException">the Session handle is invalid</exception> /// <exception cref="InstallCanceledException">the user exited the installation</exception> /// <remarks><p> /// The DoAction method executes the action that corresponds to the name supplied. If the /// name is not recognized by the installer as a built-in action or as a custom action in /// the CustomAction table, the name is passed to the user-interface handler object, which /// can invoke a function or a dialog box. If a null action name is supplied, the installer /// uses the upper-case value of the ACTION property as the action to perform. If no property /// value is defined, the default action is performed, defined as "INSTALL". /// </p><p> /// Actions that update the system, such as the InstallFiles and WriteRegistryValues /// actions, cannot be run by calling MsiDoAction. The exception to this rule is if DoAction /// is called from a custom action that is scheduled in the InstallExecuteSequence table /// between the InstallInitialize and InstallFinalize actions. Actions that do not update the /// system, such as AppSearch or CostInitialize, can be called. /// </p><p> /// If the called action is a deferred, rollback, or commit custom action, then the supplied /// <paramref name="actionData"/> will be available via the <see cref="CustomActionData"/> /// property of that custom action's session. /// </p><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msidoaction.asp">MsiDoAction</a> /// </p></remarks> public void DoAction(string action, CustomActionData actionData) { if (string.IsNullOrWhiteSpace(action)) { throw new ArgumentNullException("action"); } this.ValidateSessionAccess(); if (actionData != null) { this[action] = actionData.ToString(); } uint ret = RemotableNativeMethods.MsiDoAction((int) this.Handle, action); if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } } /// <summary> /// Executes an action sequence described in the specified table. /// </summary> /// <param name="sequenceTable">Name of the table containing the action sequence.</param> /// <exception cref="InvalidHandleException">the Session handle is invalid</exception> /// <exception cref="InstallCanceledException">the user exited the installation</exception> /// <remarks><p> /// This method queries the specified table, ordering the actions by the numbers in the Sequence column. /// For each row retrieved, an action is executed, provided that any supplied condition expression does /// not evaluate to FALSE. /// </p><p> /// An action sequence containing any actions that update the system, such as the InstallFiles and /// WriteRegistryValues actions, cannot be run by calling DoActionSequence. The exception to this rule is if /// DoActionSequence is called from a custom action that is scheduled in the InstallExecuteSequence table /// between the InstallInitialize and InstallFinalize actions. Actions that do not update the system, such /// as AppSearch or CostInitialize, can be called. /// </p><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msisequence.asp">MsiSequence</a> /// </p></remarks> public void DoActionSequence(string sequenceTable) { if (string.IsNullOrWhiteSpace(sequenceTable)) { throw new ArgumentNullException("sequenceTable"); } this.ValidateSessionAccess(); uint ret = RemotableNativeMethods.MsiSequence((int) this.Handle, sequenceTable, 0); if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } } /// <summary> /// Gets custom action data for the session that was supplied by the caller. /// </summary> /// <seealso cref="DoAction(string,CustomActionData)"/> public CustomActionData CustomActionData { get { if (this.customActionData == null) { this.customActionData = new CustomActionData(this[CustomActionData.PropertyName]); } return this.customActionData; } } /// <summary> /// Implements formatting for <see cref="Record" /> data. /// </summary> /// <param name="formatType">Type of format object to get.</param> /// <returns>The the current instance, if <paramref name="formatType"/> is the same type /// as the current instance; otherwise, null.</returns> object IFormatProvider.GetFormat(Type formatType) { return formatType == typeof(Session) ? this : null; } /// <summary> /// Closes the session handle. Also closes the active database handle, if it is open. /// After closing a handle, further method calls may throw an <see cref="InvalidHandleException"/>. /// </summary> /// <param name="disposing">If true, the method has been called directly /// or indirectly by a user's code, so managed and unmanaged resources will /// be disposed. If false, only unmanaged resources will be disposed.</param> protected override void Dispose(bool disposing) { try { if (disposing) { if (this.database != null) { this.database.Dispose(); this.database = null; } } } finally { base.Dispose(disposing); } } /// <summary> /// Gets the (short) list of properties that are available from non-immediate custom actions. /// </summary> private static IList<string> NonImmediatePropertyNames { get { return new string[] { CustomActionData.PropertyName, "ProductCode", "UserSID" }; } } /// <summary> /// Throws an exception if the custom action is not able to access immediate session details. /// </summary> private void ValidateSessionAccess() { if (!this.sessionAccessValidated) { if (this.GetMode(InstallRunMode.Scheduled) || this.GetMode(InstallRunMode.Rollback) || this.GetMode(InstallRunMode.Commit)) { throw new InstallerException("Cannot access session details from a non-immediate custom action"); } this.sessionAccessValidated = true; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.Collections.Generic { // A simple Queue of generic objects. Internally it is implemented as a // circular buffer, so Enqueue can be O(n). Dequeue is O(1). public class Queue<T> : IEnumerable<T>, System.Collections.ICollection, IReadOnlyCollection<T> { private T[] _array; private int _head; // First valid element in the queue private int _tail; // Last valid element in the queue private int _size; // Number of elements. private int _version; private const int MinimumGrow = 4; private const int GrowFactor = 200; // double each time private const int DefaultCapacity = 4; // Creates a queue with room for capacity objects. The default initial // capacity and grow factor are used. public Queue() { _array = new T[0]; } // Creates a queue with room for capacity objects. The default grow factor // is used. public Queue(int capacity) { if (capacity < 0) throw new ArgumentOutOfRangeException("capacity", "Non-negative number required."); _array = new T[capacity]; } // Fills a Queue with the elements of an ICollection. Uses the enumerator // to get each of the elements. public Queue(IEnumerable<T> collection) { if (collection == null) throw new ArgumentNullException("collection"); _array = new T[DefaultCapacity]; using (IEnumerator<T> en = collection.GetEnumerator()) { while (en.MoveNext()) { Enqueue(en.Current); } } } public int Count { get { return _size; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return this; } } public bool IsReadOnly { get { return false; } } /// <summary> /// Copies the <see cref="Queue{T}"/> elements to an existing one-dimensional Array, starting at the specified array index. /// </summary> /// <param name="array">The one-dimensional Array that is the destination of the elements copied from <see cref="Queue{T}"/>. The Array must have zero-based indexing.</param> /// <param name="index">The zero-based index in array at which copying begins.</param> public virtual void CopyTo(Array array, int index) { if (array == null) { throw new ArgumentNullException("array"); } if (array.Rank != 1) { throw new ArgumentException("Only single dimensional arrays are supported for the requested action."); } if (index < 0) { throw new ArgumentOutOfRangeException("index"); } int arrayLen = array.Length; if (arrayLen - index < _size) { throw new ArgumentException("Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection."); } int numToCopy = _size; if (numToCopy == 0) { return; } int firstPart = (_array.Length - _head < numToCopy) ? _array.Length - _head : numToCopy; Array.Copy(_array, _head, array, index, firstPart); numToCopy -= firstPart; if (numToCopy > 0) { Array.Copy(_array, 0, array, index + _array.Length - _head, numToCopy); } } // Removes all Objects from the queue. public void Clear() { if (_head < _tail) Array.Clear(_array, _head, _size); else { Array.Clear(_array, _head, _array.Length - _head); Array.Clear(_array, 0, _tail); } _head = 0; _tail = 0; _size = 0; _version++; } // CopyTo copies a collection into an Array, starting at a particular // index into the array. public void CopyTo(T[] array, int arrayIndex) { if (array == null) { throw new ArgumentNullException("array"); } if (arrayIndex < 0 || arrayIndex > array.Length) { throw new ArgumentOutOfRangeException("arrayIndex", "Index was out of range. Must be non-negative and less than the size of the collection."); } int arrayLen = array.Length; if (arrayLen - arrayIndex < _size) { throw new ArgumentException("Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection."); } int numToCopy = (arrayLen - arrayIndex < _size) ? (arrayLen - arrayIndex) : _size; if (numToCopy == 0) return; int firstPart = (_array.Length - _head < numToCopy) ? _array.Length - _head : numToCopy; Array.Copy(_array, _head, array, arrayIndex, firstPart); numToCopy -= firstPart; if (numToCopy > 0) { Array.Copy(_array, 0, array, arrayIndex + _array.Length - _head, numToCopy); } } // Adds item to the tail of the queue. public void Enqueue(T item) { if (_size == _array.Length) { int newcapacity = _array.Length * GrowFactor / 100; if (newcapacity < _array.Length + MinimumGrow) { newcapacity = _array.Length + MinimumGrow; } SetCapacity(newcapacity); } _array[_tail] = item; _tail = MoveNext(_tail); _size++; _version++; } // GetEnumerator returns an IEnumerator over this Queue. This // Enumerator will support removing. public Enumerator GetEnumerator() { return new Enumerator(this); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new Enumerator(this); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new Enumerator(this); } // Removes the object at the head of the queue and returns it. If the queue // is empty, this method simply returns null. public T Dequeue() { if (_size == 0) throw new InvalidOperationException("Queue empty."); T removed = _array[_head]; _array[_head] = default(T); _head = MoveNext(_head); _size--; _version++; return removed; } // Returns the object at the head of the queue. The object remains in the // queue. If the queue is empty, this method throws an // InvalidOperationException. public T Peek() { if (_size == 0) throw new InvalidOperationException("Queue empty."); return _array[_head]; } // Returns true if the queue contains at least one object equal to item. // Equality is determined using item.Equals(). // // Exceptions: ArgumentNullException if item == null. public bool Contains(T item) { int index = _head; int count = _size; EqualityComparer<T> c = EqualityComparer<T>.Default; while (count-- > 0) { if (item == null) { if (_array[index] == null) return true; } else if (_array[index] != null && c.Equals(_array[index], item)) { return true; } index = MoveNext(index); } return false; } private T GetElement(int i) { return _array[(_head + i) % _array.Length]; } // Iterates over the objects in the queue, returning an array of the // objects in the Queue, or an empty array if the queue is empty. // The order of elements in the array is first in to last in, the same // order produced by successive calls to Dequeue. public T[] ToArray() { T[] arr = new T[_size]; if (_size == 0) return arr; // consider replacing with Array.Empty<T>() to be consistent with non-generic Queue if (_head < _tail) { Array.Copy(_array, _head, arr, 0, _size); } else { Array.Copy(_array, _head, arr, 0, _array.Length - _head); Array.Copy(_array, 0, arr, _array.Length - _head, _tail); } return arr; } // PRIVATE Grows or shrinks the buffer to hold capacity objects. Capacity // must be >= _size. private void SetCapacity(int capacity) { T[] newarray = new T[capacity]; if (_size > 0) { if (_head < _tail) { Array.Copy(_array, _head, newarray, 0, _size); } else { Array.Copy(_array, _head, newarray, 0, _array.Length - _head); Array.Copy(_array, 0, newarray, _array.Length - _head, _tail); } } _array = newarray; _head = 0; _tail = (_size == capacity) ? 0 : _size; _version++; } // Increments the index wrapping it if necessary. private int MoveNext(int index) { // It is tempting to use the remainder operator here but it is actually much slower // than a simple comparison and a rarely taken branch. int tmp = index + 1; return (tmp == _array.Length) ? 0 : tmp; } public void TrimExcess() { int threshold = (int)(_array.Length * 0.9); if (_size < threshold) { SetCapacity(_size); } } // Implements an enumerator for a Queue. The enumerator uses the // internal version number of the list to ensure that no modifications are // made to the list while an enumeration is in progress. public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator { private Queue<T> _q; private int _index; // -1 = not started, -2 = ended/disposed private int _version; private T _currentElement; internal Enumerator(Queue<T> q) { _q = q; _version = _q._version; _index = -1; _currentElement = default(T); } public void Dispose() { _index = -2; _currentElement = default(T); } public bool MoveNext() { if (_version != _q._version) throw new InvalidOperationException("Collection was modified; enumeration operation may not execute."); if (_index == -2) return false; _index++; if (_index == _q._size) { _index = -2; _currentElement = default(T); return false; } _currentElement = _q.GetElement(_index); return true; } public T Current { get { if (_index < 0) { if (_index == -1) throw new InvalidOperationException("Enumeration has not started. Call MoveNext."); else throw new InvalidOperationException("Enumeration already finished."); } return _currentElement; } } Object System.Collections.IEnumerator.Current { get { return Current; } } void System.Collections.IEnumerator.Reset() { if (_version != _q._version) throw new InvalidOperationException("Collection was modified; enumeration operation may not execute."); _index = -1; _currentElement = default(T); } } } }
/* * 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 copyrightD * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; using OMV = OpenMetaverse; namespace OpenSim.Region.Physics.BulletSPlugin { public abstract class BSLinkset { // private static string LogHeader = "[BULLETSIM LINKSET]"; public enum LinksetImplementation { Constraint = 0, // linkset tied together with constraints Compound = 1, // linkset tied together as a compound object Manual = 2 // linkset tied together manually (code moves all the pieces) } // Create the correct type of linkset for this child public static BSLinkset Factory(BSScene physScene, BSPrimLinkable parent) { BSLinkset ret = null; switch (parent.LinksetType) { case LinksetImplementation.Constraint: ret = new BSLinksetConstraints(physScene, parent); break; case LinksetImplementation.Compound: ret = new BSLinksetCompound(physScene, parent); break; case LinksetImplementation.Manual: // ret = new BSLinksetManual(physScene, parent); break; default: ret = new BSLinksetCompound(physScene, parent); break; } if (ret == null) { physScene.Logger.ErrorFormat("[BULLETSIM LINKSET] Factory could not create linkset. Parent name={1}, ID={2}", parent.Name, parent.LocalID); } return ret; } public class BSLinkInfo { public BSPrimLinkable member; public BSLinkInfo(BSPrimLinkable pMember) { member = pMember; } public virtual void ResetLink() { } public virtual void SetLinkParameters(BSConstraint constrain) { } // Returns 'true' if physical property updates from the child should be reported to the simulator public virtual bool ShouldUpdateChildProperties() { return false; } } public LinksetImplementation LinksetImpl { get; protected set; } public BSPrimLinkable LinksetRoot { get; protected set; } protected BSScene m_physicsScene { get; private set; } static int m_nextLinksetID = 1; public int LinksetID { get; private set; } // The children under the root in this linkset. // protected HashSet<BSPrimLinkable> m_children; protected Dictionary<BSPrimLinkable, BSLinkInfo> m_children; // We lock the diddling of linkset classes to prevent any badness. // This locks the modification of the instances of this class. Changes // to the physical representation is done via the tainting mechenism. protected object m_linksetActivityLock = new Object(); // We keep the prim's mass in the linkset structure since it could be dependent on other prims public float LinksetMass { get; protected set; } public virtual bool LinksetIsColliding { get { return false; } } public OMV.Vector3 CenterOfMass { get { return ComputeLinksetCenterOfMass(); } } public OMV.Vector3 GeometricCenter { get { return ComputeLinksetGeometricCenter(); } } protected BSLinkset(BSScene scene, BSPrimLinkable parent) { // A simple linkset of one (no children) LinksetID = m_nextLinksetID++; // We create LOTS of linksets. if (m_nextLinksetID <= 0) m_nextLinksetID = 1; m_physicsScene = scene; LinksetRoot = parent; m_children = new Dictionary<BSPrimLinkable, BSLinkInfo>(); LinksetMass = parent.RawMass; Rebuilding = false; RebuildScheduled = false; parent.ClearDisplacement(); } // Link to a linkset where the child knows the parent. // Parent changing should not happen so do some sanity checking. // We return the parent's linkset so the child can track its membership. // Called at runtime. public BSLinkset AddMeToLinkset(BSPrimLinkable child) { lock (m_linksetActivityLock) { // Don't add the root to its own linkset if (!IsRoot(child)) AddChildToLinkset(child); LinksetMass = ComputeLinksetMass(); } return this; } // Remove a child from a linkset. // Returns a new linkset for the child which is a linkset of one (just the // orphened child). // Called at runtime. public BSLinkset RemoveMeFromLinkset(BSPrimLinkable child, bool inTaintTime) { lock (m_linksetActivityLock) { if (IsRoot(child)) { // Cannot remove the root from a linkset. return this; } RemoveChildFromLinkset(child, inTaintTime); LinksetMass = ComputeLinksetMass(); } // The child is down to a linkset of just itself return BSLinkset.Factory(m_physicsScene, child); } // Return 'true' if the passed object is the root object of this linkset public bool IsRoot(BSPrimLinkable requestor) { return (requestor.LocalID == LinksetRoot.LocalID); } public int NumberOfChildren { get { return m_children.Count; } } // Return 'true' if this linkset has any children (more than the root member) public bool HasAnyChildren { get { return (m_children.Count > 0); } } // Return 'true' if this child is in this linkset public bool HasChild(BSPrimLinkable child) { bool ret = false; lock (m_linksetActivityLock) { ret = m_children.ContainsKey(child); } return ret; } // Perform an action on each member of the linkset including root prim. // Depends on the action on whether this should be done at taint time. public delegate bool ForEachMemberAction(BSPrimLinkable obj); public virtual bool ForEachMember(ForEachMemberAction action) { bool ret = false; lock (m_linksetActivityLock) { action(LinksetRoot); foreach (BSPrimLinkable po in m_children.Keys) { if (action(po)) break; } } return ret; } public bool TryGetLinkInfo(BSPrimLinkable child, out BSLinkInfo foundInfo) { bool ret = false; BSLinkInfo found = null; lock (m_linksetActivityLock) { ret = m_children.TryGetValue(child, out found); } foundInfo = found; return ret; } // Perform an action on each member of the linkset including root prim. // Depends on the action on whether this should be done at taint time. public delegate bool ForEachLinkInfoAction(BSLinkInfo obj); public virtual bool ForEachLinkInfo(ForEachLinkInfoAction action) { bool ret = false; lock (m_linksetActivityLock) { foreach (BSLinkInfo po in m_children.Values) { if (action(po)) break; } } return ret; } // Check the type of the link and return 'true' if the link is flexible and the // updates from the child should be sent to the simulator so things change. public virtual bool ShouldReportPropertyUpdates(BSPrimLinkable child) { bool ret = false; BSLinkInfo linkInfo; if (m_children.TryGetValue(child, out linkInfo)) { ret = linkInfo.ShouldUpdateChildProperties(); } return ret; } // Called after a simulation step to post a collision with this object. // Return 'true' if linkset processed the collision. 'false' says the linkset didn't have // anything to add for the collision and it should be passed through normal processing. // Default processing for a linkset. public virtual bool HandleCollide(uint collidingWith, BSPhysObject collidee, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth) { bool ret = false; // prims in the same linkset cannot collide with each other BSPrimLinkable convCollidee = collidee as BSPrimLinkable; if (convCollidee != null && (LinksetID == convCollidee.Linkset.LinksetID)) { // By returning 'true', we tell the caller the collision has been 'handled' so it won't // do anything about this collision and thus, effectivily, ignoring the collision. ret = true; } else { // Not a collision between members of the linkset. Must be a real collision. // So the linkset root can know if there is a collision anywhere in the linkset. LinksetRoot.SomeCollisionSimulationStep = m_physicsScene.SimulationStep; } return ret; } // I am the root of a linkset and a new child is being added // Called while LinkActivity is locked. protected abstract void AddChildToLinkset(BSPrimLinkable child); // I am the root of a linkset and one of my children is being removed. // Safe to call even if the child is not really in my linkset. protected abstract void RemoveChildFromLinkset(BSPrimLinkable child, bool inTaintTime); // When physical properties are changed the linkset needs to recalculate // its internal properties. // May be called at runtime or taint-time. public virtual void Refresh(BSPrimLinkable requestor) { LinksetMass = ComputeLinksetMass(); } // Flag denoting the linkset is in the process of being rebuilt. // Used to know not the schedule a rebuild in the middle of a rebuild. // Because of potential update calls that could want to schedule another rebuild. protected bool Rebuilding { get; set; } // Flag saying a linkset rebuild has been scheduled. // This is turned on when the rebuild is requested and turned off when // the rebuild is complete. Used to limit modifications to the // linkset parameters while the linkset is in an intermediate state. // Protected by a "lock(m_linsetActivityLock)" on the BSLinkset object public bool RebuildScheduled { get; protected set; } // The object is going dynamic (physical). Do any setup necessary // for a dynamic linkset. // Only the state of the passed object can be modified. The rest of the linkset // has not yet been fully constructed. // Return 'true' if any properties updated on the passed object. // Called at taint-time! public abstract bool MakeDynamic(BSPrimLinkable child); public virtual bool AllPartsComplete { get { bool ret = true; this.ForEachMember((member) => { if (member.IsIncomplete || member.PrimAssetState == BSPhysObject.PrimAssetCondition.Waiting) { ret = false; return true; // exit loop } return false; // continue loop }); return ret; } } // The object is going static (non-physical). Do any setup necessary // for a static linkset. // Return 'true' if any properties updated on the passed object. // Called at taint-time! public abstract bool MakeStatic(BSPrimLinkable child); // Called when a parameter update comes from the physics engine for any object // of the linkset is received. // Passed flag is update came from physics engine (true) or the user (false). // Called at taint-time!! public abstract void UpdateProperties(UpdatedProperties whichUpdated, BSPrimLinkable physObject); // Routine used when rebuilding the body of the root of the linkset // Destroy all the constraints have have been made to root. // This is called when the root body is changing. // Returns 'true' of something was actually removed and would need restoring // Called at taint-time!! public abstract bool RemoveDependencies(BSPrimLinkable child); // ================================================================ // Some physical setting happen to all members of the linkset public virtual void SetPhysicalFriction(float friction) { ForEachMember((member) => { if (member.PhysBody.HasPhysicalBody) m_physicsScene.PE.SetFriction(member.PhysBody, friction); return false; // 'false' says to continue looping } ); } public virtual void SetPhysicalRestitution(float restitution) { ForEachMember((member) => { if (member.PhysBody.HasPhysicalBody) m_physicsScene.PE.SetRestitution(member.PhysBody, restitution); return false; // 'false' says to continue looping } ); } public virtual void SetPhysicalGravity(OMV.Vector3 gravity) { ForEachMember((member) => { if (member.PhysBody.HasPhysicalBody) m_physicsScene.PE.SetGravity(member.PhysBody, gravity); return false; // 'false' says to continue looping } ); } public virtual void ComputeAndSetLocalInertia(OMV.Vector3 inertiaFactor, float linksetMass) { ForEachMember((member) => { if (member.PhysBody.HasPhysicalBody) { OMV.Vector3 inertia = m_physicsScene.PE.CalculateLocalInertia(member.PhysShape.physShapeInfo, linksetMass); member.Inertia = inertia * inertiaFactor; m_physicsScene.PE.SetMassProps(member.PhysBody, linksetMass, member.Inertia); m_physicsScene.PE.UpdateInertiaTensor(member.PhysBody); DetailLog("{0},BSLinkset.ComputeAndSetLocalInertia,m.mass={1}, inertia={2}", member.LocalID, linksetMass, member.Inertia); } return false; // 'false' says to continue looping } ); } public virtual void SetPhysicalCollisionFlags(CollisionFlags collFlags) { ForEachMember((member) => { if (member.PhysBody.HasPhysicalBody) m_physicsScene.PE.SetCollisionFlags(member.PhysBody, collFlags); return false; // 'false' says to continue looping } ); } public virtual void AddToPhysicalCollisionFlags(CollisionFlags collFlags) { ForEachMember((member) => { if (member.PhysBody.HasPhysicalBody) m_physicsScene.PE.AddToCollisionFlags(member.PhysBody, collFlags); return false; // 'false' says to continue looping } ); } public virtual void RemoveFromPhysicalCollisionFlags(CollisionFlags collFlags) { ForEachMember((member) => { if (member.PhysBody.HasPhysicalBody) m_physicsScene.PE.RemoveFromCollisionFlags(member.PhysBody, collFlags); return false; // 'false' says to continue looping } ); } // ================================================================ protected virtual float ComputeLinksetMass() { float mass = LinksetRoot.RawMass; if (HasAnyChildren) { lock (m_linksetActivityLock) { foreach (BSPrimLinkable bp in m_children.Keys) { mass += bp.RawMass; } } } return mass; } // Computes linkset's center of mass in world coordinates. protected virtual OMV.Vector3 ComputeLinksetCenterOfMass() { OMV.Vector3 com; lock (m_linksetActivityLock) { com = LinksetRoot.Position * LinksetRoot.RawMass; float totalMass = LinksetRoot.RawMass; foreach (BSPrimLinkable bp in m_children.Keys) { com += bp.Position * bp.RawMass; totalMass += bp.RawMass; } if (totalMass != 0f) com /= totalMass; } return com; } protected virtual OMV.Vector3 ComputeLinksetGeometricCenter() { OMV.Vector3 com; lock (m_linksetActivityLock) { com = LinksetRoot.Position; foreach (BSPrimLinkable bp in m_children.Keys) { com += bp.Position; } com /= (m_children.Count + 1); } return com; } #region Extension public virtual object Extension(string pFunct, params object[] pParams) { return null; } #endregion // Extension // Invoke the detailed logger and output something if it's enabled. protected void DetailLog(string msg, params Object[] args) { if (m_physicsScene.PhysicsLogging.Enabled) m_physicsScene.DetailLog(msg, args); } } }
// Copyright 2017 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using UnityEngine; using System.Collections; using System.Collections.Generic; public class menuManager : MonoBehaviour { public GameObject item; public GameObject rootNode; public GameObject trashNode; public GameObject settingsNode; public GameObject metronomeNode; public GameObject[] menuItems; public Dictionary<menuItem.deviceType, GameObject> refObjects; public AudioSource _audioSource; public AudioClip openClip; public AudioClip closeClip; public AudioClip selectClip; public AudioClip grabClip; public AudioClip simpleOpenClip; menuItem[] menuItemScripts; public static menuManager instance; bool active = false; int lastController = -1; public bool loaded = false; void Awake() { instance = this; refObjects = new Dictionary<menuItem.deviceType, GameObject>(); _audioSource = GetComponent<AudioSource>(); loadMenu(); loadNonMenuItems(); loaded = true; Activate(false, transform); if (!PlayerPrefs.HasKey("midiOut")) PlayerPrefs.SetInt("midiOut", 0); if (PlayerPrefs.GetInt("midiOut") == 1) { toggleMidiOut(true); } } void loadNonMenuItems() { GameObject temp = Instantiate(item, Vector3.zero, Quaternion.identity) as GameObject; temp.transform.parent = rootNode.transform; menuItem m = temp.GetComponent<menuItem>(); refObjects[menuItem.deviceType.TapeGroup] = m.Setup(menuItem.deviceType.TapeGroup); temp.SetActive(false); temp = Instantiate(item, Vector3.zero, Quaternion.identity) as GameObject; temp.transform.parent = rootNode.transform; m = temp.GetComponent<menuItem>(); refObjects[menuItem.deviceType.Pano] = m.Setup(menuItem.deviceType.Pano); temp.SetActive(false); } public void SetMenuActive(bool on) { active = on; } int rowLength = 5; void loadMenu() { menuItems = new GameObject[(int)menuItem.deviceType.Max]; menuItemScripts = new menuItem[menuItems.Length]; for (int i = 0; i < menuItems.Length; i++) { menuItems[i] = Instantiate(item, Vector3.zero, Quaternion.identity) as GameObject; menuItems[i].transform.parent = rootNode.transform; menuItem m = menuItems[i].GetComponent<menuItem>(); refObjects[(menuItem.deviceType)i] = m.Setup((menuItem.deviceType)i); menuItemScripts[i] = m; } int tempCount = 0; float h = 0; float arc = 37.5f; while (tempCount < menuItems.Length) { for (int i = 0; i < rowLength; i++) { if (tempCount < menuItems.Length) { menuItems[tempCount].transform.localPosition = Quaternion.Euler(0, (arc / rowLength) * (i - rowLength / 2f) + (arc / rowLength) / 2f, 0) * (Vector3.forward * -.5f) - (Vector3.forward * -.5f) + Vector3.up * h; menuItems[tempCount].transform.rotation = Quaternion.Euler(0, (arc / rowLength) * (i - rowLength / 2f) + (arc / rowLength) / 2f, 0); } tempCount++; } h += 0.07f; } metronomeNode.transform.localPosition = Quaternion.Euler(0, -arc / 2 - 10, 0) * (Vector3.forward * -.5f) - (Vector3.forward * -.5f) + Vector3.up * .014f; metronomeNode.transform.rotation = Quaternion.Euler(0, -arc / 2 - 10, 0); settingsNode.transform.localPosition = Quaternion.Euler(0, arc / 2 + 10, 0) * (Vector3.forward * -.5f) - (Vector3.forward * -.5f); settingsNode.transform.rotation = Quaternion.Euler(0, arc / 2 + 10, 0); } public void SelectAudio() { _audioSource.PlayOneShot(selectClip, .05f); } public void GrabAudio() { _audioSource.PlayOneShot(grabClip, .75f); } public bool midiOutEnabled = false; float openSpeed = 3; public void toggleMidiOut(bool on) { PlayerPrefs.SetInt("midiOut", on ? 1 : 0); midiOutEnabled = on; openSpeed = on ? 2 : 3; menuItemScripts[menuItemScripts.Length - 1].Appear(on); } Coroutine activationCoroutine; IEnumerator activationRoutine(bool on, Transform pad) { float timer = 0; if (on) { _audioSource.PlayOneShot(openClip); rootNode.SetActive(true); trashNode.SetActive(false); settingsNode.SetActive(false); metronomeNode.SetActive(false); List<int> remaining = new List<int>(); for (int i = 0; i < menuItemScripts.Length; i++) { remaining.Add(i); menuItemScripts[i].transform.localScale = Vector3.zero; } Vector3 startPos = transform.position = pad.position; while (timer < 1) { timer = Mathf.Clamp01(timer + Time.deltaTime * 1.5f); for (int i = 0; i < menuItemScripts.Length; i++) { if (remaining.Contains(i)) { if (timer / openSpeed > Vector3.Distance(startPos, menuItemScripts[i].transform.position)) { menuItemScripts[i].Appear(on); remaining.Remove(i); } } } transform.position = startPos + Vector3.Lerp(Vector3.zero, Vector3.up * .025f, timer); Vector3 camPos = Camera.main.transform.position; camPos.y -= .2f; transform.LookAt(camPos, Vector3.up); yield return null; } trashNode.SetActive(true); settingsNode.SetActive(true); metronomeNode.SetActive(true); } else { _audioSource.PlayOneShot(closeClip); Vector3 startPos = transform.position; trashNode.SetActive(false); settingsNode.SetActive(false); metronomeNode.SetActive(false); for (int i = 0; i < menuItems.Length; i++) { menuItemScripts[i].Appear(on); } while (timer < 1) { timer = Mathf.Clamp01(timer + Time.deltaTime * 4); transform.position = Vector3.Lerp(startPos, pad.position, timer); yield return null; } rootNode.SetActive(false); } } void Activate(bool on, Transform pad) { active = on; if (activationCoroutine != null) StopCoroutine(activationCoroutine); activationCoroutine = StartCoroutine(activationRoutine(on, pad)); } void SimpleActivate(bool on, Transform pad) { active = on; simpleMenu.toggleMenu(); if (on) _audioSource.PlayOneShot(simpleOpenClip); else _audioSource.PlayOneShot(closeClip); if (!active) return; transform.position = pad.position; Vector3 camPos = Camera.main.transform.position; camPos.y = transform.position.y; transform.LookAt(camPos); } public bool simple = false; public pauseMenu simpleMenu; public bool buttonEvent(int controller, Transform pad) { bool on = true; if (controller != lastController) { if (!simple) Activate(true, pad); else SimpleActivate(true, pad); } else { if (!simple) Activate(!active, pad); else SimpleActivate(!active, pad); on = active; } lastController = controller; return on; } }
using System; using System.Data; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using FirebirdSql.Data.FirebirdClient; using SouchProd.EntityFrameworkCore.Firebird.FunctionalTests.Models; using Xunit; namespace SouchProd.EntityFrameworkCore.Firebird.FunctionalTests.Tests.Models { public class ExpressionTest : IDisposable { private readonly AppDb _db; private readonly DataTypesSimple _simple; private readonly DataTypesSimple _simple2; private readonly DataTypesVariable _variable; public ExpressionTest() { _db = new AppDb(); // initialize simple data types _simple = new DataTypesSimple { TypeDateTime = new DateTime(2017, 1, 1, 0, 0, 0), TypeDouble = 3.1415, TypeDoubleN = -3.1415 }; _db.DataTypesSimple.Add(_simple); // initialize simple data types _simple2 = new DataTypesSimple { TypeDouble = 1, TypeDoubleN = -1 }; _db.DataTypesSimple.Add(_simple2); // initialize variable data types _variable = DataTypesVariable.CreateEmpty(); _variable.TypeString = "EntityFramework"; _db.DataTypesVariable.Add(_variable); _db.SaveChanges(); } public void Dispose() { try { _db.DataTypesSimple.Remove(_simple); _db.DataTypesVariable.Remove(_variable); _db.SaveChanges(); } finally { _db.Dispose(); } } [Fact] public async Task FirebirdContainsOptimizedTranslator() { var result = await _db.DataTypesVariable.Select(m => new { Id = m.Id, Contains = m.TypeString.Contains("Fram"), NotContains = m.TypeString.Contains("asdf") }).FirstOrDefaultAsync(m => m.Id == _variable.Id); Assert.True(result.Contains); Assert.False(result.NotContains); } [Fact] public async Task FirebirdDateAddTranslator() { var result = await _db.DataTypesSimple.Select(m => new { Id = m.Id, FutureYear = m.TypeDateTime.AddYears(1), FutureMonth = m.TypeDateTime.AddMonths(1), FutureDay = m.TypeDateTime.AddDays(1), FutureHour = m.TypeDateTime.AddHours(1), FutureMinute = m.TypeDateTime.AddMinutes(1), FutureSecond = m.TypeDateTime.AddSeconds(1), PastYear = m.TypeDateTime.AddYears(-1), PastMonth = m.TypeDateTime.AddMonths(-1), PastDay = m.TypeDateTime.AddDays(-1), PastHour = m.TypeDateTime.AddHours(-1), PastMinute = m.TypeDateTime.AddMinutes(-1), PastSecond = m.TypeDateTime.AddSeconds(-1), }).FirstOrDefaultAsync(m => m.Id == _simple.Id); Assert.Equal(_simple.TypeDateTime.AddYears(1), result.FutureYear); Assert.Equal(_simple.TypeDateTime.AddMonths(1), result.FutureMonth); Assert.Equal(_simple.TypeDateTime.AddDays(1), result.FutureDay); Assert.Equal(_simple.TypeDateTime.AddHours(1), result.FutureHour); Assert.Equal(_simple.TypeDateTime.AddMinutes(1), result.FutureMinute); Assert.Equal(_simple.TypeDateTime.AddSeconds(1), result.FutureSecond); Assert.Equal(_simple.TypeDateTime.AddYears(-1), result.PastYear); Assert.Equal(_simple.TypeDateTime.AddMonths(-1), result.PastMonth); Assert.Equal(_simple.TypeDateTime.AddDays(-1), result.PastDay); Assert.Equal(_simple.TypeDateTime.AddHours(-1), result.PastHour); Assert.Equal(_simple.TypeDateTime.AddMinutes(-1), result.PastMinute); Assert.Equal(_simple.TypeDateTime.AddSeconds(-1), result.PastSecond); } [Fact] public async Task FirebirdDatePartTranslator() { var result = await _db.DataTypesSimple.Select(m => new { Id = m.Id, Year = m.TypeDateTime.Year, Month = m.TypeDateTime.Month, Day = m.TypeDateTime.Day, Hour = m.TypeDateTime.Hour, Minute = m.TypeDateTime.Minute, Second = m.TypeDateTime.Second, }).FirstOrDefaultAsync(m => m.Id == _simple.Id); Assert.Equal(_simple.TypeDateTime.Year, result.Year); Assert.Equal(_simple.TypeDateTime.Month, result.Month); Assert.Equal(_simple.TypeDateTime.Day, result.Day); Assert.Equal(_simple.TypeDateTime.Hour, result.Hour); Assert.Equal(_simple.TypeDateTime.Minute, result.Minute); Assert.Equal(_simple.TypeDateTime.Second, result.Second); } [Fact] public async Task FirebirdDateTimeNowTranslator() { await _db.Database.OpenConnectionAsync(); var result = await _db.DataTypesSimple.Select(m => new { Id = m.Id, Now = DateTime.Now }).FirstOrDefaultAsync(m => m.Id == _simple.Id); _db.Database.CloseConnection(); Assert.InRange(result.Now, DateTime.Now - TimeSpan.FromSeconds(5), DateTime.Now + TimeSpan.FromSeconds(5)); } [Fact] public async Task FirebirdEndsWithOptimizedTranslator() { var result = await _db.DataTypesVariable.Select(m => new { Id = m.Id, EndsWith = m.TypeString.EndsWith("Framework"), NotEndsWith = m.TypeString.EndsWith("Entity") }).FirstOrDefaultAsync(m => m.Id == _variable.Id); Assert.True(result.EndsWith); Assert.False(result.NotEndsWith); } [Fact] public async Task FirebirdMathAbsTranslator() { var result = await _db.DataTypesSimple.Select(m => new { Id = m.Id, ValDbl = m.TypeDoubleN, Abs = Math.Abs(m.TypeDoubleN.Value), }).FirstOrDefaultAsync(m => (m.Id == _simple.Id) && (m.ValDbl != null)); Assert.Equal(Math.Abs(_simple.TypeDoubleN.Value), result.Abs); } [Fact] public async Task FirebirdMathCeilingTranslator() { var result = await _db.DataTypesSimple.Select(m => new { Id = m.Id, Ceiling = Math.Ceiling(m.TypeDouble), }).FirstOrDefaultAsync(m => m.Id == _simple.Id); Assert.Equal(Math.Ceiling(_simple.TypeDouble), result.Ceiling); } [Fact] public async Task FirebirdMathFloorTranslator() { var result = await _db.DataTypesSimple.Select(m => new { Id = m.Id, Floor = Math.Floor(m.TypeDouble), }).FirstOrDefaultAsync(m => m.Id == _simple.Id); Assert.Equal(Math.Floor(_simple.TypeDouble), result.Floor); } [Fact] public async Task FirebirdMathPowerTranslator() { var result = await _db.DataTypesSimple.Select(m => new { Id = m.Id, Pow = Math.Pow(m.TypeDouble, m.TypeDouble), }).FirstOrDefaultAsync(m => m.Id == _simple.Id); Assert.Equal(Math.Pow(_simple.TypeDouble, _simple.TypeDouble), result.Pow); } [Fact] public async Task FirebirdMathRoundTranslator() { var result = await _db.DataTypesSimple.Select(m => new { Id = m.Id, Round = Math.Round(m.TypeDouble), }).FirstOrDefaultAsync(m => m.Id == _simple.Id); Assert.Equal(Math.Round(_simple.TypeDouble), result.Round); } [Fact] public async Task FirebirdMathTruncateTranslator() { var result = await _db.DataTypesSimple.Select(m => new { Id = m.Id, Truncate = Math.Truncate(m.TypeDouble), }).FirstOrDefaultAsync(m => m.Id == _simple.Id); Assert.Equal(Math.Truncate(_simple.TypeDouble), result.Truncate); } [Fact] public async Task FirebirdStartsWithOptimizedTranslator() { var result = await _db.DataTypesVariable.Select(m => new { Id = m.Id, StartsWith = m.TypeString.StartsWith("Entity"), NotStartsWith = m.TypeString.StartsWith("Framework") }).FirstOrDefaultAsync(m => m.Id == _variable.Id); Assert.True(result.StartsWith); Assert.False(result.NotStartsWith); } [Fact] public async Task FirebirdStringLengthTranslator() { var result = await _db.DataTypesVariable.Select(m => new { Id = m.Id, Length = m.TypeString.Length, }).FirstOrDefaultAsync(m => m.Id == _variable.Id); Assert.Equal(_variable.TypeString.Length, result.Length); } [Fact] public async Task FirebirdStringReplaceTranslator() { var result = await _db.DataTypesVariable.Select(m => new { Id = m.Id, Replaced = m.TypeString.Replace("Entity", "Pomelo.Entity") }).FirstOrDefaultAsync(m => m.Id == _variable.Id); Assert.Equal("Pomelo.EntityFramework", result.Replaced); } [Fact] public async Task FirebirdStringSubstringTranslator() { var result = await _db.DataTypesVariable.Select(m => new { Id = m.Id, First3Chars = m.TypeString.Substring(0, 3), Last3Chars = m.TypeString.Substring(m.TypeString.Length - 4, 3), MiddleChars = m.TypeString.Substring(1, m.TypeString.Length - 2) }).FirstOrDefaultAsync(m => m.Id == _variable.Id); Assert.Equal(_variable.TypeString.Substring(0, 3), result.First3Chars); Assert.Equal(_variable.TypeString.Substring(_variable.TypeString.Length - 4, 3), result.Last3Chars); Assert.Equal(_variable.TypeString.Substring(1, _variable.TypeString.Length - 2), result.MiddleChars); } [Fact] public async Task FirebirdStringToLowerTranslator() { var result = await _db.DataTypesVariable.Select(m => new { Id = m.Id, ToLower = m.TypeString.ToLower() }).FirstOrDefaultAsync(m => m.Id == _variable.Id); Assert.Equal("entityframework", result.ToLower); } [Fact] public async Task FirebirdStringToUpperTranslator() { var result = await _db.DataTypesVariable.Select(m => new { Id = m.Id, Upper = m.TypeString.ToUpper() }).FirstOrDefaultAsync(m => m.Id == _variable.Id); Assert.Equal("ENTITYFRAMEWORK", result.Upper); } [Fact] public async Task FirebirdMathAcosTranslator() { var result = await _db.DataTypesSimple.Select(m => new { Id = m.Id, Acos = Math.Acos(m.TypeDoubleN.Value), }).FirstOrDefaultAsync(m => m.Id == _simple2.Id); Assert.Equal(Math.Acos(_simple2.TypeDoubleN.Value), result.Acos); } [Fact] public async Task FirebirdMathCosTranslator() { var result = await _db.DataTypesSimple.Select(m => new { Id = m.Id, Cos = Math.Cos(m.TypeDouble), }).FirstOrDefaultAsync(m => m.Id == _simple2.Id); Assert.Equal(Math.Cos(_simple2.TypeDouble), result.Cos); } [Fact] public async Task FirebirdMathSinTranslator() { var result = await _db.DataTypesSimple.Select(m => new { Id = m.Id, Sin = Math.Sin(m.TypeDouble), }).FirstOrDefaultAsync(m => m.Id == _simple2.Id); Assert.Equal(Math.Sin(_simple2.TypeDouble), result.Sin); } [Fact] public async Task FirebirdDateToDateTimeConvertTranslator() { var result = await _db.DataTypesSimple.CountAsync(m => m.TypeDateTimeN <= DateTime.Now.Date); Assert.NotEqual(0, result); } [Fact] public async Task FirebirdToStringConvertTranslator() { var result = await _db.DataTypesSimple.Select(m => new { ConvertedInt32 = m.Id.ToString(), ConvertedLong = m.TypeLong.ToString(), ConvertedByte = m.TypeByte.ToString(), ConvertedSByte = m.TypeSbyte.ToString(), ConvertedBool = m.TypeBool.ToString(), ConvertedNullBool = m.TypeBoolN.ToString(), ConvertedDecimal = m.TypeDecimal.ToString(), ConvertedDouble = m.TypeDouble.ToString(), ConvertedFloat = m.TypeFloat.ToString(), ConvertedGuid = m.TypeGuid.ToString(), Text = m.TypeChar } ).FirstOrDefaultAsync(); Assert.NotNull(result); } } }
//Copyright 2017 by Josip Medved <[email protected]> (www.medo64.com) MIT License //2017-11-05: Suppress exception on UnauthorizedAccessException. //2017-10-09: Support for /opt installation on Linux. //2017-04-29: Added IsAssumedInstalled property. // Added Reset and DeleteAll methods. //2017-04-26: Renamed from Properties. // Added \0 escape sequence. // Fixed alignment issues. //2017-04-17: First version. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Text; namespace Medo.Configuration { /// <summary> /// Provides cached access to reading and writing settings. /// This class is thread-safe. /// </summary> /// <remarks> /// File name is the same as name of the &lt;executable&gt;.cfg under windows or .&lt;executable&gt; under Linux. /// File format is as follows: /// * hash characters (#) denotes comment. /// * key and value are colon (:) separated although equals (=) is also supported. /// * backslash (\) is used for escaping. /// </remarks> public static class Config { /// <summary> /// Returns the value for the specified key. /// </summary> /// <param name="key">Key.</param> /// <param name="defaultValue">The value to return if the key does not exist.</param> /// <exception cref="ArgumentNullException">Key cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Key cannot be empty.</exception> public static string Read(string key, string defaultValue) { key = key?.Trim() ?? throw new ArgumentNullException(nameof(key), "Key cannot be null."); if (key.Length == 0) { throw new ArgumentOutOfRangeException(nameof(key), "Key cannot be empty."); } lock (SyncReadWrite) { if (!IsLoaded) { Load(); } if (OverridePropertiesFile != null) { return OverridePropertiesFile.ReadOne(key) ?? DefaultPropertiesFile.ReadOne(key) ?? defaultValue; } else { return DefaultPropertiesFile.ReadOne(key) ?? defaultValue; } } } /// <summary> /// Returns all the values for the specified key. /// </summary> /// <param name="key">Key.</param> /// <exception cref="ArgumentNullException">Key cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Key cannot be empty.</exception> public static IEnumerable<string> Read(string key) { key = key?.Trim() ?? throw new ArgumentNullException(nameof(key), "Key cannot be null."); if (key.Length == 0) { throw new ArgumentOutOfRangeException(nameof(key), "Key cannot be empty."); } lock (SyncReadWrite) { if (!IsLoaded) { Load(); } if (OverridePropertiesFile != null) { var list = new List<string>(OverridePropertiesFile.ReadMany(key)); if (list.Count > 0) { return list; } } return DefaultPropertiesFile.ReadMany(key); } } /// <summary> /// Returns the value for the specified key. /// </summary> /// <param name="key">Key.</param> /// <param name="defaultValue">The value to return if the key does not exist.</param> /// <exception cref="ArgumentNullException">Key cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Key cannot be empty.</exception> public static bool Read(string key, bool defaultValue) { if (Read(key, null) is string value) { if (bool.TryParse(value, out var result)) { return result; } else if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var resultInt)) { return (resultInt != 0); } } return defaultValue; } /// <summary> /// Returns the value for the specified key. /// </summary> /// <param name="key">Key.</param> /// <param name="defaultValue">The value to return if the key does not exist.</param> /// <exception cref="ArgumentNullException">Key cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Key cannot be empty.</exception> public static int Read(string key, int defaultValue) { if (Read(key, null) is string value) { if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { return result; } } return defaultValue; } /// <summary> /// Returns the value for the specified key. /// </summary> /// <param name="key">Key.</param> /// <param name="defaultValue">The value to return if the key does not exist.</param> /// <exception cref="ArgumentNullException">Key cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Key cannot be empty.</exception> public static long Read(string key, long defaultValue) { if (Read(key, null) is string value) { if (long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { return result; } } return defaultValue; } /// <summary> /// Returns the value for the specified key. /// </summary> /// <param name="key">Key.</param> /// <param name="defaultValue">The value to return if the key does not exist.</param> /// <exception cref="ArgumentNullException">Key cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Key cannot be empty.</exception> public static double Read(string key, double defaultValue) { if (Read(key, null) is string value) { if (double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result)) { return result; } } return defaultValue; } /// <summary> /// Writes the value for the specified key. /// If the specified key does not exist, it is created. /// </summary> /// <param name="key">Key.</param> /// <param name="value">The value to write.</param> /// <exception cref="ArgumentNullException">Key cannot be null. -or- Value cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Key cannot be empty.</exception> public static void Write(string key, string value) { key = key?.Trim() ?? throw new ArgumentNullException(nameof(key), "Key cannot be null."); if (key.Length == 0) { throw new ArgumentOutOfRangeException(nameof(key), "Key cannot be empty."); } if (value == null) { throw new ArgumentNullException(nameof(key), "Value cannot be null."); } lock (SyncReadWrite) { if (!IsLoaded) { Load(); } DefaultPropertiesFile.WriteOne(key, value); if (ImmediateSave) { Save(); } } } /// <summary> /// Writes the values for the specified key. /// If the specified key does not exist, it is created. /// If value is null or empty, key is deleted. /// </summary> /// <param name="key">Key.</param> /// <param name="value">The value to write.</param> /// <exception cref="ArgumentNullException">Key cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Key cannot be empty.</exception> public static void Write(string key, IEnumerable<string> value) { key = key?.Trim() ?? throw new ArgumentNullException(nameof(key), "Key cannot be null."); if (key.Length == 0) { throw new ArgumentOutOfRangeException(nameof(key), "Key cannot be empty."); } lock (SyncReadWrite) { if (!IsLoaded) { Load(); } DefaultPropertiesFile.WriteMany(key, value); if (ImmediateSave) { Save(); } } } /// <summary> /// Writes the value for the specified key. /// If the specified key does not exist, it is created. /// </summary> /// <param name="key">Key.</param> /// <param name="value">The value to write.</param>4 /// <exception cref="ArgumentNullException">Key cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Key cannot be empty.</exception> public static void Write(string key, bool value) { Write(key, value ? "true" : "false"); //not using ToString() because it would capitalize first letter } /// <summary> /// Writes the value for the specified key. /// If the specified key does not exist, it is created. /// </summary> /// <param name="key">Key.</param> /// <param name="value">The value to write.</param>4 /// <exception cref="ArgumentNullException">Key cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Key cannot be empty.</exception> public static void Write(string key, int value) { Write(key, value.ToString(CultureInfo.InvariantCulture)); } /// <summary> /// Writes the value for the specified key. /// If the specified key does not exist, it is created. /// </summary> /// <param name="key">Key.</param> /// <param name="value">The value to write.</param>4 /// <exception cref="ArgumentNullException">Key cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Key cannot be empty.</exception> public static void Write(string key, long value) { Write(key, value.ToString(CultureInfo.InvariantCulture)); } /// <summary> /// Writes the value for the specified key. /// If the specified key does not exist, it is created. /// </summary> /// <param name="key">Key.</param> /// <param name="value">The value to write.</param>4 /// <exception cref="ArgumentNullException">Key cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Key cannot be empty.</exception> public static void Write(string key, double value) { Write(key, value.ToString("r", CultureInfo.InvariantCulture)); } /// <summary> /// Deletes key. /// </summary> /// <param name="key">Key.</param> /// <exception cref="ArgumentNullException">Key cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Key cannot be empty.</exception> public static void Delete(string key) { key = key?.Trim() ?? throw new ArgumentNullException(nameof(key), "Key cannot be null."); if (key.Length == 0) { throw new ArgumentOutOfRangeException(nameof(key), "Key cannot be empty."); } lock (SyncReadWrite) { if (!IsLoaded) { Load(); } DefaultPropertiesFile.Delete(key); if (ImmediateSave) { Save(); } } } #region Loading and saving private static bool IsInitialized { get; set; } private static bool IsLoaded { get; set; } private static PropertiesFile DefaultPropertiesFile; private static PropertiesFile OverridePropertiesFile; private static readonly object SyncReadWrite = new object(); private static bool IsAssumedInstalledBacking; /// <summary> /// Gets if application is assumed to be installed. /// Application is considered installed if it is located in Program Files directory (or opt) or if file is already present in Application Data folder. /// </summary> public static bool IsAssumedInstalled { get { lock (SyncReadWrite) { if (!IsInitialized) { Initialize(); } return IsAssumedInstalledBacking; } } } private static string FileNameBacking; /// <summary> /// Gets/sets the name of the file used for settings. /// If executable is located under Program Files, properties file will be under Application Data. /// If executable is located in some other directory, a local file will be used. /// </summary> /// <exception cref="ArgumentNullException">Value cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Value is not a valid path.</exception> public static string FileName { get { lock (SyncReadWrite) { if (!IsInitialized) { Initialize(); } return FileNameBacking; } } set { lock (SyncReadWrite) { if (!IsInitialized) { Initialize(); } if (value == null) { throw new ArgumentNullException(nameof(value), "Value cannot be null."); } else if (value.IndexOfAny(Path.GetInvalidPathChars()) >= 0) { throw new ArgumentOutOfRangeException(nameof(value), "Value is not a valid path."); } else { FileNameBacking = value; IsLoaded = false; //force loading } } } } private static string OverrideFileNameBacking; /// <summary> /// Gets/sets the name of the file used for settings override. /// This file is not written to. /// If executable is located under Program Files, override properties file will be in executable's directory. /// If executable is located in some other directory, no override file will be used. /// </summary> /// <exception cref="ArgumentOutOfRangeException">Value is not a valid path.</exception> public static string OverrideFileName { get { lock (SyncReadWrite) { if (!IsInitialized) { Initialize(); } return OverrideFileNameBacking; } } set { lock (SyncReadWrite) { if (!IsInitialized) { Initialize(); } if ((value != null) && (value.IndexOfAny(Path.GetInvalidPathChars()) >= 0)) { throw new ArgumentOutOfRangeException(nameof(value), "Value is not a valid path."); } else { OverrideFileNameBacking = value; IsLoaded = false; } } } } /// <summary> /// Loads all settings from a file. /// Returns true if file was found. /// </summary> /// <param name="fileName">File name to use.</param> public static bool Load(string fileName) { lock (SyncReadWrite) { FileName = fileName; OverrideFileName = null; return Load(); } } /// <summary> /// Loads all settings from a file. /// Returns true if file was found. /// </summary> public static bool Load() { var sw = Stopwatch.StartNew(); try { lock (SyncReadWrite) { OverridePropertiesFile = (OverrideFileName != null) ? new PropertiesFile(OverrideFileName, isOverride: true) : null; DefaultPropertiesFile = new PropertiesFile(FileName); IsLoaded = true; return DefaultPropertiesFile.FileExists; } } finally { Debug.WriteLine("[Settings] Load completed in " + sw.ElapsedMilliseconds.ToString(CultureInfo.InvariantCulture) + " milliseconds."); } } /// <summary> /// Saves all settings to a file. /// Returns true if action is successful. /// </summary> public static bool Save() { var sw = Stopwatch.StartNew(); try { lock (SyncReadWrite) { if (!IsLoaded) { Load(); } return DefaultPropertiesFile.Save(); } } finally { Debug.WriteLine("[Settings] Save completed in " + sw.ElapsedMilliseconds.ToString(CultureInfo.InvariantCulture) + " milliseconds."); } } /// <summary> /// Deletes all settings. /// </summary> public static void DeleteAll() { lock (SyncReadWrite) { if (!IsLoaded) { Load(); } DefaultPropertiesFile.DeleteAll(); if (ImmediateSave) { Save(); } } Debug.WriteLine("[Settings] Settings deleted."); } /// <summary> /// Resets configuration. This includes file names and installation status. /// </summary> public static void Reset() { lock (SyncReadWrite) { IsLoaded = false; IsInitialized = false; } } /// <summary> /// Gets/sets if setting is saved immediatelly. /// </summary> public static bool ImmediateSave { get; set; } = true; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "Lower case form of application name is only used to generate properties file name which is not compared against other text.")] private static void Initialize() { var assembly = Assembly.GetEntryAssembly(); string companyValue = null; string productValue = null; string titleValue = null; #if NETSTANDARD1_6 var attributes = assembly.GetCustomAttributes(); #else var attributes = assembly.GetCustomAttributes(true); #endif foreach (var attribute in attributes) { if (attribute is AssemblyCompanyAttribute companyAttribute) { companyValue = companyAttribute.Company.Trim(); } if (attribute is AssemblyProductAttribute productAttribute) { productValue = productAttribute.Product.Trim(); } if (attribute is AssemblyTitleAttribute titleAttribute) { titleValue = titleAttribute.Title.Trim(); } } var company = companyValue ?? ""; var application = productValue ?? titleValue ?? assembly.GetName().Name; var executablePath = assembly.Location; var baseFileName = IsOSWindows ? application + ".cfg" : "." + application.ToLowerInvariant(); var userFileLocation = IsOSWindows ? Path.Combine(Environment.GetEnvironmentVariable("AppData"), company, application, baseFileName) : Path.Combine(Environment.GetEnvironmentVariable("HOME") ?? "~", baseFileName); var priorityFileLocation = Path.Combine(Path.GetDirectoryName(executablePath), baseFileName); bool isInProgramFiles; if (IsOSWindows) { var isPF = executablePath.StartsWith(Environment.GetEnvironmentVariable("ProgramFiles") + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase); var isPF32 = executablePath.StartsWith(Environment.GetEnvironmentVariable("ProgramFiles(x86)") + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase); isInProgramFiles = isPF || isPF32; } else { var isOpt = executablePath.StartsWith(Path.DirectorySeparatorChar + "opt" + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase); var isBin = executablePath.StartsWith(Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase); var isUsrBin = executablePath.StartsWith(Path.DirectorySeparatorChar + "usr" + Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase); isInProgramFiles = isOpt || isBin || isUsrBin; if (isOpt) { //change priority file location to /etc/opt/<app>/<app>.cfg priorityFileLocation = Path.DirectorySeparatorChar + "etc" + Path.Combine(Path.GetDirectoryName(executablePath), application.ToLowerInvariant() + ".conf"); } } IsAssumedInstalledBacking = File.Exists(userFileLocation) || isInProgramFiles; FileNameBacking = IsAssumedInstalledBacking ? userFileLocation : priorityFileLocation; OverrideFileNameBacking = IsAssumedInstalledBacking ? priorityFileLocation : null; //no priority file - one in current directory is the default one IsInitialized = true; } #if NETSTANDARD2_0 || NETSTANDARD1_6 private static bool IsOSWindows => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); #else private static bool IsOSWindows => (Type.GetType("Mono.Runtime") == null); #endif #region PropertiesFile private class PropertiesFile { private static readonly Encoding Utf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); private static readonly StringComparer KeyComparer = StringComparer.OrdinalIgnoreCase; private static readonly StringComparison KeyComparison = StringComparison.OrdinalIgnoreCase; private readonly string FileName; private readonly string LineEnding; private readonly List<LineData> Lines = new List<LineData>(); public PropertiesFile(string fileName, bool isOverride = false) { this.FileName = fileName; string fileContent = null; try { fileContent = File.ReadAllText(fileName, Utf8); } catch (IOException) { } catch (UnauthorizedAccessException) { } string lineEnding = null; if (fileContent != null) { var currLine = new StringBuilder(); var lineEndingDetermined = false; char prevChar = '\0'; foreach (var ch in fileContent) { if (ch == '\n') { if (prevChar == '\r') { //CRLF pair if (!lineEndingDetermined) { lineEnding = "\r\n"; lineEndingDetermined = true; } } else { if (!lineEndingDetermined) { lineEnding = "\n"; lineEndingDetermined = true; } processLine(currLine); currLine.Clear(); } } else if (ch == '\r') { processLine(currLine); if (!lineEndingDetermined) { lineEnding = "\r"; } //do not set as determined as there is possibility of trailing LF } else { if (lineEnding != null) { lineEndingDetermined = true; } //if there was a line ending before, mark it as determined currLine.Append(ch); } prevChar = ch; } this.FileExists = true; processLine(currLine); } this.LineEnding = lineEnding ?? Environment.NewLine; void processLine(StringBuilder line) { var lineText = line.ToString(); line.Clear(); char? valueSeparator = null; var sbKey = new StringBuilder(); var sbValue = new StringBuilder(); var sbComment = new StringBuilder(); var sbWhitespace = new StringBuilder(); var sbEscapeLong = new StringBuilder(); string separatorPrefix = null; string separatorSuffix = null; string commentPrefix = null; var state = State.Default; var prevState = State.Default; foreach (var ch in lineText) { switch (state) { case State.Default: if (char.IsWhiteSpace(ch)) { } else if (ch == '#') { sbComment.Append(ch); state = State.Comment; } else if (ch == '\\') { state = State.KeyEscape; } else { sbKey.Append(ch); state = State.Key; } break; case State.Comment: sbComment.Append(ch); break; case State.Key: if (char.IsWhiteSpace(ch)) { valueSeparator = ch; state = State.SeparatorOrValue; } else if ((ch == ':') || (ch == '=')) { valueSeparator = ch; state = State.ValueOrWhitespace; } else if (ch == '#') { sbComment.Append(ch); state = State.Comment; } else if (ch == '\\') { state = State.KeyEscape; } else { sbKey.Append(ch); } break; case State.SeparatorOrValue: if (char.IsWhiteSpace(ch)) { } else if ((ch == ':') || (ch == '=')) { valueSeparator = ch; state = State.ValueOrWhitespace; } else if (ch == '#') { sbComment.Append(ch); state = State.Comment; } else if (ch == '\\') { state = State.ValueEscape; } else { sbValue.Append(ch); state = State.Value; } break; case State.ValueOrWhitespace: if (char.IsWhiteSpace(ch)) { } else if (ch == '#') { sbComment.Append(ch); state = State.Comment; } else if (ch == '\\') { state = State.ValueEscape; } else { sbValue.Append(ch); state = State.Value; } break; case State.Value: if (char.IsWhiteSpace(ch)) { state = State.ValueOrComment; } else if (ch == '#') { sbComment.Append(ch); state = State.Comment; } else if (ch == '\\') { state = State.ValueEscape; } else { sbValue.Append(ch); } break; case State.ValueOrComment: if (char.IsWhiteSpace(ch)) { } else if (ch == '#') { sbComment.Append(ch); state = State.Comment; } else if (ch == '\\') { sbValue.Append(sbWhitespace); state = State.ValueEscape; } else { sbValue.Append(sbWhitespace); sbValue.Append(ch); state = State.Value; } break; case State.KeyEscape: case State.ValueEscape: if (ch == 'u') { state = (state == State.KeyEscape) ? State.KeyEscapeLong : State.ValueEscapeLong; } else { char newCh; switch (ch) { case '0': newCh = '\0'; break; case 'b': newCh = '\b'; break; case 't': newCh = '\t'; break; case 'n': newCh = '\n'; break; case 'r': newCh = '\r'; break; case '_': newCh = ' '; break; default: newCh = ch; break; } if (state == State.KeyEscape) { sbKey.Append(newCh); } else { sbValue.Append(newCh); } state = (state == State.KeyEscape) ? State.Key : State.Value; } break; case State.KeyEscapeLong: case State.ValueEscapeLong: sbEscapeLong.Append(ch); if (sbEscapeLong.Length == 4) { if (int.TryParse(sbEscapeLong.ToString(), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var chValue)) { if (state == State.KeyEscape) { sbKey.Append((char)chValue); } else { sbValue.Append((char)chValue); } } state = (state == State.KeyEscapeLong) ? State.Key : State.Value; } break; } if (char.IsWhiteSpace(ch) && (prevState != State.KeyEscape) && (prevState != State.ValueEscape) && (prevState != State.KeyEscapeLong) && (prevState != State.ValueEscapeLong)) { sbWhitespace.Append(ch); } else if (state != prevState) { //on state change, clean comment prefix if ((state == State.ValueOrWhitespace) && (separatorPrefix == null)) { separatorPrefix = sbWhitespace.ToString(); sbWhitespace.Clear(); } else if ((state == State.Value) && (separatorSuffix == null)) { separatorSuffix = sbWhitespace.ToString(); sbWhitespace.Clear(); } else if ((state == State.Comment) && (commentPrefix == null)) { commentPrefix = sbWhitespace.ToString(); sbWhitespace.Clear(); } else if ((state == State.Key) || (state == State.ValueOrWhitespace) || (state == State.Value)) { sbWhitespace.Clear(); } } prevState = state; } this.Lines.Add(new LineData(sbKey.ToString(), separatorPrefix, valueSeparator, separatorSuffix, sbValue.ToString(), commentPrefix, sbComment.ToString())); } #if DEBUG foreach (var line in this.Lines) { if (!string.IsNullOrEmpty(line.Key)) { Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, "[Settings] {0}{2}: {1}", line.Key, line.Value, (isOverride ? "*" : ""))); } } #endif } public bool FileExists { get; } //false if there was an error during load public bool Save() { string fileContent = string.Join(this.LineEnding, this.Lines); try { var directoryPath = Path.GetDirectoryName(this.FileName); if (!Directory.Exists(directoryPath)) { var directoryStack = new Stack<string>(); do { directoryStack.Push(directoryPath); directoryPath = Path.GetDirectoryName(directoryPath); } while (!Directory.Exists(directoryPath)); while (directoryStack.Count > 0) { try { Directory.CreateDirectory(directoryStack.Pop()); } catch (IOException) { break; } catch (UnauthorizedAccessException) { break; } } } File.WriteAllText(this.FileName, fileContent, Utf8); return true; } catch (IOException) { return false; } catch (UnauthorizedAccessException) { return false; } } private enum State { Default, Comment, Key, KeyEscape, KeyEscapeLong, SeparatorOrValue, ValueOrWhitespace, Value, ValueEscape, ValueEscapeLong, ValueOrComment, } private class LineData { public LineData() : this(null, null, null, null, null, null, null) { } public LineData(LineData template, string key, string value) : this(key, template?.SeparatorPrefix ?? "", template?.Separator ?? ':', template?.SeparatorSuffix ?? " ", value, null, null) { if (template != null) { var firstKeyTotalLength = (template.Key?.Length ?? 0) + (template.SeparatorPrefix?.Length ?? 0) + 1 + (template.SeparatorSuffix?.Length ?? 0); var totalLengthWithoutSuffix = key.Length + (template.SeparatorPrefix?.Length ?? 0) + 1; var maxSuffixLength = firstKeyTotalLength - totalLengthWithoutSuffix; if (maxSuffixLength < 1) { maxSuffixLength = 1; } //leave at least one space if (this.SeparatorSuffix.Length > maxSuffixLength) { this.SeparatorSuffix = this.SeparatorSuffix.Substring(0, maxSuffixLength); } } } public LineData(string key, string separatorPrefix, char? separator, string separatorSuffix, string value, string commentPrefix, string comment) { this.Key = key; this.SeparatorPrefix = separatorPrefix; this.Separator = separator ?? ':'; this.SeparatorSuffix = separatorSuffix; this.Value = value; this.CommentPrefix = commentPrefix; this.Comment = comment; } public string Key { get; set; } public string SeparatorPrefix { get; set; } public char Separator { get; } public string SeparatorSuffix { get; set; } public string Value { get; set; } public string CommentPrefix { get; } public string Comment { get; } public override string ToString() { var sb = new StringBuilder(); if (!string.IsNullOrEmpty(this.Key)) { EscapeIntoStringBuilder(sb, this.Key, isKey: true); if (!string.IsNullOrEmpty(this.Value)) { if ((this.Separator == ':') || (this.Separator == '=')) { sb.Append(this.SeparatorPrefix); sb.Append(this.Separator); sb.Append(this.SeparatorSuffix); } else { sb.Append(string.IsNullOrEmpty(this.SeparatorSuffix) ? " " : this.SeparatorSuffix); } EscapeIntoStringBuilder(sb, this.Value ?? ""); } else { //try to preserve formatting in case of spaces (thus omitted) sb.Append(this.SeparatorPrefix); switch (this.Separator) { case ':': sb.Append(":"); break; case '=': sb.Append("="); break; } sb.Append(this.SeparatorSuffix); } } if (!string.IsNullOrEmpty(this.Comment)) { if (!string.IsNullOrEmpty(this.CommentPrefix)) { sb.Append(this.CommentPrefix); } sb.Append(this.Comment); } return sb.ToString(); } private static void EscapeIntoStringBuilder(StringBuilder sb, string text, bool isKey = false) { for (int i = 0; i < text.Length; i++) { var ch = text[i]; switch (ch) { case '\\': sb.Append(@"\\"); break; case '\0': sb.Append(@"\0"); break; case '\b': sb.Append(@"\b"); break; case '\t': sb.Append(@"\t"); break; case '\r': sb.Append(@"\r"); break; case '\n': sb.Append(@"\n"); break; case '#': sb.Append(@"\#"); break; default: if (char.IsControl(ch)) { sb.Append(((int)ch).ToString("X4", CultureInfo.InvariantCulture)); } else if (ch == ' ') { if ((i == 0) || (i == (text.Length - 1)) || isKey) { sb.Append(@"\_"); } else { sb.Append(ch); } } else if (char.IsWhiteSpace(ch)) { switch (ch) { case '\0': sb.Append(@"\0"); break; case '\b': sb.Append(@"\b"); break; case '\t': sb.Append(@"\t"); break; case '\n': sb.Append(@"\n"); break; case '\r': sb.Append(@"\r"); break; default: sb.Append(((int)ch).ToString("X4", CultureInfo.InvariantCulture)); break; } } else if (ch == '\\') { sb.Append(@"\\"); } else { sb.Append(ch); } break; } } } public bool IsEmpty => string.IsNullOrEmpty(this.Key) && string.IsNullOrEmpty(this.Value) && string.IsNullOrEmpty(this.CommentPrefix) && string.IsNullOrEmpty(this.Comment); } private Dictionary<string, int> CachedEntries; private void FillCache() { this.CachedEntries = new Dictionary<string, int>(KeyComparer); for (var i = 0; i < this.Lines.Count; i++) { var line = this.Lines[i]; if (!line.IsEmpty) { if (this.CachedEntries.ContainsKey(line.Key)) { this.CachedEntries[line.Key] = i; //last key takes precedence } else { this.CachedEntries.Add(line.Key, i); } } } } public string ReadOne(string key) { if (this.CachedEntries == null) { FillCache(); } return this.CachedEntries.TryGetValue(key, out var lineNumber) ? this.Lines[lineNumber].Value : null; } public IEnumerable<string> ReadMany(string key) { if (this.CachedEntries == null) { FillCache(); } foreach (var line in this.Lines) { if (string.Equals(key, line.Key, KeyComparison)) { yield return line.Value; } } } public void WriteOne(string key, string value) { if (this.CachedEntries == null) { FillCache(); } if (this.CachedEntries.TryGetValue(key, out var lineIndex)) { var data = this.Lines[lineIndex]; data.Key = key; data.Value = value; } else { var hasLines = (this.Lines.Count > 0); var newData = new LineData(hasLines ? this.Lines[0] : null, key, value); if (!hasLines) { this.CachedEntries.Add(key, this.Lines.Count); this.Lines.Add(newData); this.Lines.Add(new LineData()); } else if (!this.Lines[this.Lines.Count - 1].IsEmpty) { this.CachedEntries.Add(key, this.Lines.Count); this.Lines.Add(newData); } else { this.CachedEntries.Add(key, this.Lines.Count - 1); this.Lines.Insert(this.Lines.Count - 1, newData); } } } public void WriteMany(string key, IEnumerable<string> values) { if (this.CachedEntries == null) { FillCache(); } if (this.CachedEntries.TryGetValue(key, out var lineIndex)) { int lastIndex = 0; LineData lastLine = null; for (var i = this.Lines.Count - 1; i >= 0; i--) { //find insertion point var line = this.Lines[i]; if (string.Equals(key, line.Key, KeyComparison)) { if (lastLine == null) { lastLine = line; lastIndex = i; } else { lastIndex--; } this.Lines.RemoveAt(i); } } var hasLines = (this.Lines.Count > 0); foreach (var value in values) { this.Lines.Insert(lastIndex, new LineData(lastLine ?? (hasLines ? this.Lines[0] : null), key, value)); lastIndex++; } FillCache(); } else { var hasLines = (this.Lines.Count > 0); if (!hasLines) { foreach (var value in values) { this.CachedEntries[key] = this.Lines.Count; this.Lines.Add(new LineData(null, key, value)); } this.Lines.Add(new LineData()); } else if (!this.Lines[this.Lines.Count - 1].IsEmpty) { foreach (var value in values) { this.CachedEntries[key] = this.Lines.Count; this.Lines.Add(new LineData(this.Lines[0], key, value)); } } else { foreach (var value in values) { this.CachedEntries[key] = this.Lines.Count - 1; this.Lines.Insert(this.Lines.Count - 1, new LineData(this.Lines[0], key, value)); } } } } public void Delete(string key) { if (this.CachedEntries == null) { FillCache(); } this.CachedEntries.Remove(key); for (var i = this.Lines.Count - 1; i >= 0; i--) { var line = this.Lines[i]; if (string.Equals(key, line.Key, KeyComparison)) { this.Lines.RemoveAt(i); } } } public void DeleteAll() { this.Lines.Clear(); this.FillCache(); } } #endregion #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.Diagnostics; using System.Threading; using Xunit; namespace System.Data.SqlClient.ManualTesting.Tests { public static class ConnectivityParametersTest { private const string COL_PROGRAM_NAME = "ProgramName"; private const string COL_HOSTNAME = "HostName"; private static readonly string s_databaseName = "d_" + Guid.NewGuid().ToString().Replace('-', '_'); private static readonly string s_tableName = "Person"; private static readonly string s_connectionString = DataTestUtility.TcpConnStr; private static readonly string s_dbConnectionString = new SqlConnectionStringBuilder(s_connectionString) { InitialCatalog = s_databaseName }.ConnectionString; private static readonly string s_createDatabaseCmd = $"CREATE DATABASE {s_databaseName}"; private static readonly string s_createTableCmd = $"CREATE TABLE {s_tableName} (NAME NVARCHAR(40), AGE INT)"; private static readonly string s_alterDatabaseSingleCmd = $"ALTER DATABASE {s_databaseName} SET SINGLE_USER WITH ROLLBACK IMMEDIATE;"; private static readonly string s_alterDatabaseMultiCmd = $"ALTER DATABASE {s_databaseName} SET MULTI_USER WITH ROLLBACK IMMEDIATE;"; private static readonly string s_selectTableCmd = $"SELECT COUNT(*) FROM {s_tableName}"; private static readonly string s_dropDatabaseCmd = $"DROP DATABASE {s_databaseName}"; [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void EnvironmentHostNameTest() { SqlConnectionStringBuilder builder = (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { Pooling = true }); builder.ApplicationName = "HostNameTest"; using (SqlConnection sqlConnection = new SqlConnection(builder.ConnectionString)) { sqlConnection.Open(); using (SqlCommand command = new SqlCommand("sp_who2", sqlConnection)) { using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { int programNameOrdinal = reader.GetOrdinal(COL_PROGRAM_NAME); string programName = reader.GetString(programNameOrdinal); if (programName != null && programName.Trim().Equals(builder.ApplicationName)) { // Get the hostname int hostnameOrdinal = reader.GetOrdinal(COL_HOSTNAME); string hostnameFromServer = reader.GetString(hostnameOrdinal); string expectedMachineName = Environment.MachineName.ToUpper(); string hostNameFromServer = hostnameFromServer.Trim().ToUpper(); Assert.Matches(expectedMachineName, hostNameFromServer); return; } } } } } Assert.True(false, "No non-empty hostname found for the application"); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void ConnectionTimeoutTestWithThread() { const int timeoutSec = 5; const int numOfTry = 2; const int numOfThreads = 5; SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr); builder.DataSource = "invalidhost"; builder.ConnectTimeout = timeoutSec; string connStrNotAvailable = builder.ConnectionString; for (int i = 0; i < numOfThreads; ++i) { new ConnectionWorker(connStrNotAvailable, numOfTry); } ConnectionWorker.Start(); ConnectionWorker.Stop(); double timeTotal = 0; double timeElapsed = 0; foreach (ConnectionWorker w in ConnectionWorker.WorkerList) { timeTotal += w.TimeElapsed; } timeElapsed = timeTotal / Convert.ToDouble(ConnectionWorker.WorkerList.Count); int threshold = timeoutSec * numOfTry * 2 * 1000; Assert.True(timeElapsed < threshold); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void ProcessIdTest() { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr); string sqlProviderName = builder.ApplicationName; string sqlProviderProcessID = System.Diagnostics.Process.GetCurrentProcess().Id.ToString(); using (SqlConnection sqlConnection = new SqlConnection(builder.ConnectionString)) { sqlConnection.Open(); string strCommand = $"SELECT PROGRAM_NAME,HOSTPROCESS FROM SYS.SYSPROCESSES WHERE PROGRAM_NAME LIKE ('%{sqlProviderName}%')"; using (SqlCommand command = new SqlCommand(strCommand, sqlConnection)) { using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { Assert.Equal(sqlProviderName,reader.GetString(0).Trim()); Assert.Equal(sqlProviderProcessID, reader.GetString(1).Trim()); } } } } } public class ConnectionWorker { private static List<ConnectionWorker> workerList = new List<ConnectionWorker>(); private ManualResetEventSlim _doneEvent = new ManualResetEventSlim(false); private double _timeElapsed; private Thread _thread; private string _connectionString; private int _numOfTry; public ConnectionWorker(string connectionString, int numOfTry) { workerList.Add(this); _connectionString = connectionString; _numOfTry = numOfTry; _thread = new Thread(new ThreadStart(SqlConnectionOpen)); } public static List<ConnectionWorker> WorkerList => workerList; public double TimeElapsed => _timeElapsed; public static void Start() { foreach (ConnectionWorker w in workerList) { w._thread.Start(); } } public static void Stop() { foreach (ConnectionWorker w in workerList) { w._doneEvent.Wait(); } } public void SqlConnectionOpen() { Stopwatch sw = new Stopwatch(); double totalTime = 0; for (int i = 0; i < _numOfTry; ++i) { using (SqlConnection con = new SqlConnection(_connectionString)) { sw.Start(); try { con.Open(); } catch { } sw.Stop(); } totalTime += sw.Elapsed.TotalMilliseconds; sw.Reset(); } _timeElapsed = totalTime / Convert.ToDouble(_numOfTry); _doneEvent.Set(); } } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void ConnectionKilledTest() { try { // Setup Database and Table. DataTestUtility.RunNonQuery(s_connectionString, s_createDatabaseCmd); DataTestUtility.RunNonQuery(s_dbConnectionString, s_createTableCmd); // Kill all the connections and set Database to SINGLE_USER Mode. DataTestUtility.RunNonQuery(s_connectionString, s_alterDatabaseSingleCmd); // Set Database back to MULTI_USER Mode DataTestUtility.RunNonQuery(s_connectionString, s_alterDatabaseMultiCmd); // Execute SELECT statement. DataTestUtility.RunNonQuery(s_dbConnectionString, s_selectTableCmd); } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); Assert.Null(ex); } finally { // Kill all the connections, set Database to SINGLE_USER Mode and drop Database DataTestUtility.RunNonQuery(s_connectionString, s_alterDatabaseSingleCmd); DataTestUtility.RunNonQuery(s_connectionString, s_dropDatabaseCmd); } } } }
// // PasswordDeriveTest.cs - NUnit Test Cases for PasswordDerive // // Author: // Sebastien Pouliot ([email protected]) // // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com) // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using NUnit.Framework; using System; using System.Security.Cryptography; namespace MonoTests.System.Security.Cryptography { // References: // a. PKCS#5: Password-Based Cryptography Standard // http://www.rsasecurity.com/rsalabs/pkcs/pkcs-5/index.html [TestFixture] public class PasswordDeriveBytesTest { static byte[] salt = { 0xDE, 0xAD, 0xC0, 0xDE }; static string ssalt = "DE-AD-C0-DE"; // Constructors [Test] #if NET_2_0 [ExpectedException (typeof (ArgumentNullException))] #endif public void Ctor_PasswordNullSalt () { string pwd = null; PasswordDeriveBytes pdb = new PasswordDeriveBytes (pwd, salt); } [Test] public void Ctor_PasswordSaltNull () { PasswordDeriveBytes pdb = new PasswordDeriveBytes ("s3kr3t", null); Assert.AreEqual ("SHA1", pdb.HashName, "HashName"); Assert.AreEqual (100, pdb.IterationCount, "IterationCount"); Assert.IsNull (pdb.Salt, "Salt"); } [Test] public void Ctor_PasswordSalt () { PasswordDeriveBytes pdb = new PasswordDeriveBytes ("s3kr3t", salt); Assert.AreEqual ("SHA1", pdb.HashName, "HashName"); Assert.AreEqual (100, pdb.IterationCount, "IterationCount"); Assert.AreEqual (ssalt, BitConverter.ToString (pdb.Salt), "Salt"); } [Test] #if NET_2_0 [ExpectedException (typeof (ArgumentNullException))] #else [Category ("NotWorking")] // CspParameters aren't supported by Mono (requires CryptoAPI) #endif public void Ctor_PasswordNullSaltCspParameters () { string pwd = null; PasswordDeriveBytes pdb = new PasswordDeriveBytes (pwd, salt, new CspParameters ()); } [Test] [Category ("NotWorking")] // CspParameters aren't supported by Mono (requires CryptoAPI) public void Ctor_PasswordSaltNullCspParameters () { PasswordDeriveBytes pdb = new PasswordDeriveBytes ("s3kr3t", null, new CspParameters ()); Assert.AreEqual ("SHA1", pdb.HashName, "HashName"); Assert.AreEqual (100, pdb.IterationCount, "IterationCount"); Assert.IsNull (pdb.Salt, "Salt"); } [Test] public void Ctor_PasswordSaltCspParametersNull () { PasswordDeriveBytes pdb = new PasswordDeriveBytes ("s3kr3t", salt, null); Assert.AreEqual ("SHA1", pdb.HashName, "HashName"); Assert.AreEqual (100, pdb.IterationCount, "IterationCount"); Assert.AreEqual (ssalt, BitConverter.ToString (pdb.Salt), "Salt"); } [Test] [Category ("NotWorking")] // CspParameters aren't supported by Mono (requires CryptoAPI) public void Ctor_PasswordSaltCspParameters () { PasswordDeriveBytes pdb = new PasswordDeriveBytes ("s3kr3t", salt, new CspParameters ()); Assert.AreEqual ("SHA1", pdb.HashName, "HashName"); Assert.AreEqual (100, pdb.IterationCount, "IterationCount"); Assert.AreEqual (ssalt, BitConverter.ToString (pdb.Salt), "Salt"); } [Test] #if NET_2_0 [ExpectedException (typeof (ArgumentNullException))] #endif public void Ctor_PasswordNullSaltHashIteration () { string pwd = null; PasswordDeriveBytes pdb = new PasswordDeriveBytes (pwd, salt, "SHA1", 1); } [Test] public void Ctor_PasswordSaltNullHashIteration () { PasswordDeriveBytes pdb = new PasswordDeriveBytes ("s3kr3t", null, "SHA1", 1); Assert.AreEqual ("SHA1", pdb.HashName, "HashName"); Assert.AreEqual (1, pdb.IterationCount, "IterationCount"); Assert.IsNull (pdb.Salt, "Salt"); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void Ctor_PasswordSaltHashNullIteration () { PasswordDeriveBytes pdb = new PasswordDeriveBytes ("s3kr3t", salt, null, 1); } [Test] [ExpectedException (typeof (ArgumentOutOfRangeException))] public void Ctor_PasswordSaltHashIterationNegative () { PasswordDeriveBytes pdb = new PasswordDeriveBytes ("s3kr3t", salt, "SHA1", -1); } [Test] [ExpectedException (typeof (ArgumentOutOfRangeException))] public void Ctor_PasswordSaltHashIterationZero () { PasswordDeriveBytes pdb = new PasswordDeriveBytes ("s3kr3t", salt, "SHA1", 0); } [Test] public void Ctor_PasswordSaltHashIterationMaxValue () { PasswordDeriveBytes pdb = new PasswordDeriveBytes ("s3kr3t", salt, "SHA1", Int32.MaxValue); Assert.AreEqual ("SHA1", pdb.HashName, "HashName"); Assert.AreEqual (Int32.MaxValue, pdb.IterationCount, "IterationCount"); Assert.AreEqual (ssalt, BitConverter.ToString (pdb.Salt), "Salt"); } [Test] public void Ctor_PasswordSaltHashIteration () { PasswordDeriveBytes pdb = new PasswordDeriveBytes ("s3kr3t", salt, "SHA1", 1); Assert.AreEqual ("SHA1", pdb.HashName, "HashName"); Assert.AreEqual (1, pdb.IterationCount, "IterationCount"); Assert.AreEqual (ssalt, BitConverter.ToString (pdb.Salt), "Salt"); } [Test] #if NET_2_0 [ExpectedException (typeof (ArgumentNullException))] #else [Category ("NotWorking")] // CspParameters aren't supported by Mono (requires CryptoAPI) #endif public void Ctor_PasswordNullSaltHashIterationCspParameters () { string pwd = null; PasswordDeriveBytes pdb = new PasswordDeriveBytes (pwd, salt, "SHA1", 1, new CspParameters ()); } [Test] [Category ("NotWorking")] // CspParameters aren't supported by Mono (requires CryptoAPI) public void Ctor_PasswordSaltNullHashIterationCspParameters () { PasswordDeriveBytes pdb = new PasswordDeriveBytes ("s3kr3t", null, "SHA1", 1, new CspParameters ()); Assert.AreEqual ("SHA1", pdb.HashName, "HashName"); Assert.AreEqual (1, pdb.IterationCount, "IterationCount"); Assert.IsNull (pdb.Salt, "Salt"); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void Ctor_PasswordSaltHashNullIterationCspParameters () { PasswordDeriveBytes pdb = new PasswordDeriveBytes ("s3kr3t", salt, null, 1, new CspParameters ()); } [Test] [ExpectedException (typeof (ArgumentOutOfRangeException))] public void Ctor_PasswordSaltHashIterationNegativeCspParameters () { PasswordDeriveBytes pdb = new PasswordDeriveBytes ("s3kr3t", salt, "SHA1", -1, new CspParameters ()); } [Test] [ExpectedException (typeof (ArgumentOutOfRangeException))] public void Ctor_PasswordSaltHashIterationZeroCspParameters () { PasswordDeriveBytes pdb = new PasswordDeriveBytes ("s3kr3t", salt, "SHA1", 0, new CspParameters ()); } [Test] [Category ("NotWorking")] // CspParameters aren't supported by Mono (requires CryptoAPI) public void Ctor_PasswordSaltHashIterationMaxValueCspParameters () { PasswordDeriveBytes pdb = new PasswordDeriveBytes ("s3kr3t", salt, "SHA1", Int32.MaxValue, new CspParameters ()); Assert.AreEqual ("SHA1", pdb.HashName, "HashName"); Assert.AreEqual (Int32.MaxValue, pdb.IterationCount, "IterationCount"); Assert.AreEqual (ssalt, BitConverter.ToString (pdb.Salt), "Salt"); } [Test] public void Ctor_PasswordSaltHashIterationCspParametersNull () { PasswordDeriveBytes pdb = new PasswordDeriveBytes ("s3kr3t", salt, "SHA1", 1, null); Assert.AreEqual ("SHA1", pdb.HashName, "HashName"); Assert.AreEqual (1, pdb.IterationCount, "IterationCount"); Assert.AreEqual (ssalt, BitConverter.ToString (pdb.Salt), "Salt"); } [Test] [Category ("NotWorking")] // CspParameters aren't supported by Mono (requires CryptoAPI) public void Ctor_PasswordSaltHashIterationCspParameters () { PasswordDeriveBytes pdb = new PasswordDeriveBytes ("s3kr3t", salt, "SHA1", 1, new CspParameters ()); Assert.AreEqual ("SHA1", pdb.HashName, "HashName"); Assert.AreEqual (1, pdb.IterationCount, "IterationCount"); Assert.AreEqual (ssalt, BitConverter.ToString (pdb.Salt), "Salt"); } // Properties [Test] [ExpectedException (typeof (ArgumentNullException))] public void Property_HashName_Null () { PasswordDeriveBytes pdb = new PasswordDeriveBytes ("s3kr3t", salt, "SHA1", 1); Assert.AreEqual ("SHA1", pdb.HashName, "HashName"); pdb.HashName = null; } [Test] #if !NET_2_0 // Fixed in 2.0 beta 1 [ExpectedException (typeof (NullReferenceException))] #endif public void Property_Salt () { PasswordDeriveBytes pdb = new PasswordDeriveBytes ("s3kr3t", salt); Assert.AreEqual (ssalt, BitConverter.ToString (pdb.Salt), "Salt"); pdb.Salt = null; Assert.IsNull (pdb.Salt, "Salt"); } [Test] public void Property_Salt_Modify () { PasswordDeriveBytes pdb = new PasswordDeriveBytes ("s3kr3t", salt); Assert.AreEqual (ssalt, BitConverter.ToString (pdb.Salt), "Salt"); pdb.Salt [0] = 0xFF; // modification rejected (the property returned a copy of the salt) Assert.AreEqual (ssalt, BitConverter.ToString (pdb.Salt), "Salt"); } // 1.0/1.1 compatibility #if !NET_2_0 // 1.0/1.1 accepted a null password as valid - but throw the // ArgumentNullException when GetBytes is called // byte stream from the null input. Check that we can do the same... [Test] [ExpectedException (typeof (ArgumentNullException))] public void GetBytes_PasswordNull () { string pwd = null; PasswordDeriveBytes pdb = new PasswordDeriveBytes (pwd, salt); pdb.GetBytes (24); } #endif // Old tests static int ToInt32LE(byte [] bytes, int offset) { return (bytes[offset + 3] << 24) | (bytes[offset + 2] << 16) | (bytes[offset + 1] << 8) | bytes[offset]; } // generate the key up to HashSize and reset between operations public void ShortRun(string msg, PasswordDeriveBytes pd, byte[] finalKey) { for (int i=0; i < finalKey.Length; i++) { int j = 0; bool compare = true; byte[] key = pd.GetBytes (i+1); for (; j < i; j++) { if (finalKey [j] != key[j]) { compare = false; break; } } Assert.IsTrue (compare, msg + " #" + j); pd.Reset (); } } // generate a key at least 1000 bytes and don't reset between operations public void LongRun(string msg, PasswordDeriveBytes pd, byte[] finalKey) { int bloc = finalKey.Length; int iter = (int) ((1000 + bloc - 1) / bloc); byte[] pass = null; for (int i=0; i < iter; i++) { pass = pd.GetBytes (bloc); } Assert.AreEqual (pass, finalKey, msg); } public void Run (string password, byte[] salt, string hashname, int iterations, int getbytes, int lastFourBytes) { PasswordDeriveBytes pd = new PasswordDeriveBytes (password, salt, hashname, iterations); byte[] key = pd.GetBytes (getbytes); string msg = "[pwd=" + password; msg += ", salt=" + ((salt == null) ? "null" : salt.Length.ToString ()); msg += ", hash=" + hashname; msg += ", iter=" + iterations; msg += ", get=" + getbytes + "]"; Assert.AreEqual (lastFourBytes, ToInt32LE (key, key.Length - 4), msg); } [Test] [ExpectedException (typeof (IndexOutOfRangeException))] public void TooShort () { PasswordDeriveBytes pd = new PasswordDeriveBytes ("password", null, "SHA1", 1); byte[] key = pd.GetBytes (0); } public void TooLong (string hashName, int size, int lastFourBytes) { PasswordDeriveBytes pd = new PasswordDeriveBytes ("toolong", null, hashName, 1); // this should work (we check the last four devired bytes to be sure) byte[] key = pd.GetBytes (size); Assert.AreEqual (lastFourBytes, ToInt32LE (key, size - 4), "Last 4 bytes"); // but we can't get another byte from it! try { key = pd.GetBytes (1); Assert.Fail ("Expected CryptographicException but got none"); } catch (CryptographicException) { // LAMESPEC: no limit is documented } catch (Exception e) { Assert.Fail ("Expected CryptographicException but got " + e.ToString ()); } } [Test] public void TooLong () { // 1000 times hash length is the maximum TooLong ("MD5", 16000, 1135777886); TooLong ("SHA1", 20000, -1167918035); TooLong ("SHA256", 32000, -358766048); TooLong ("SHA384", 48000, 1426370534); TooLong ("SHA512", 64000, -1763233543); } [Test] public void OneIteration () { // (1) size of hash, (2) size of 2 hash Run ("password", salt, "MD5", 1, 16, 986357363); Run ("monomono", null, "MD5", 1, 32, -1092059875); Run ("password", salt, "SHA1", 1, 20, -1251929751); Run ("monomono", null, "SHA1", 1, 40, -1148594972); Run ("password", salt, "SHA256", 1, 32, -1106908309); Run ("monomono", null, "SHA256", 1, 64, 1243724695); Run ("password", salt, "SHA384", 1, 48, 1338639872); Run ("monomono", null, "SHA384", 1, 96, -1974067932); Run ("password", salt, "SHA512", 1, 64, 998927776); Run ("monomono", null, "SHA512", 1, 128, -1082987985); } [Test] public void Salt () { Run ("password", salt, "MD5", 10, 10, -1174247292); Run ("monomono", salt, "SHA1", 20, 20, 622814236); Run ("password", salt, "MD5", 30, 30, 1491759020); Run ("monomono", salt, "SHA1", 40, 40, 1186751819); Run ("password", salt, "MD5", 50, 50, -1416348895); Run ("monomono", salt, "SHA1", 60, 60, -1167799882); Run ("password", salt, "MD5", 70, 70, -695745351); Run ("monomono", salt, "SHA1", 80, 80, 598766793); Run ("password", salt, "MD5", 90, 90, -906351079); Run ("monomono", salt, "SHA1", 100, 100, 1247157997); } [Test] public void NoSalt () { Run ("password", null, "MD5", 10, 10, -385488886); Run ("password", null, "SHA1", 20, 20, -385953596); Run ("password", null, "MD5", 30, 30, -669295228); Run ("password", null, "SHA1", 40, 40, -1921654064); Run ("password", null, "MD5", 50, 50, -1664099354); Run ("monomono", null, "SHA1", 60, 60, -1988511363); Run ("monomono", null, "MD5", 70, 70, -1326415479); Run ("monomono", null, "SHA1", 80, 80, 158880373); Run ("monomono", null, "MD5", 90, 90, 532527918); Run ("monomono", null, "SHA1", 100, 100, 769250758); } [Test] public void MD5 () { const string hashName = "MD5"; // getbytes less than hash size Run ("password", null, hashName, 10, 10, -385488886); // getbytes equal to hash size Run ("password", salt, hashName, 20, 16, -470982134); // getbytes more than hash size Run ("password", null, hashName, 30, 30, -669295228); Run ("password", salt, hashName, 40, 40, 892279589); Run ("password", null, hashName, 50, 50, -1664099354); Run ("monomono", salt, hashName, 60, 60, -2050574033); Run ("monomono", null, hashName, 70, 70, -1326415479); Run ("monomono", salt, hashName, 80, 80, 2047895994); Run ("monomono", null, hashName, 90, 90, 532527918); Run ("monomono", salt, hashName, 100, 100, 1522243696); } [Test] public void SHA1 () { const string hashName = "SHA1"; // getbytes less than hash size Run ("password", null, hashName, 10, 10, -852142057); // getbytes equal to hash size Run ("password", salt, hashName, 20, 20, -1096621819); // getbytes more than hash size Run ("password", null, hashName, 30, 30, 1748347042); Run ("password", salt, hashName, 40, 40, 900690664); Run ("password", null, hashName, 50, 50, 2125027038); Run ("monomono", salt, hashName, 60, 60, -1167799882); Run ("monomono", null, hashName, 70, 70, -1967623713); Run ("monomono", salt, hashName, 80, 80, 598766793); Run ("monomono", null, hashName, 90, 90, -1754629926); Run ("monomono", salt, hashName, 100, 100, 1247157997); } [Test] public void SHA256 () { const string hashName = "SHA256"; // getbytes less than hash size Run ("password", null, hashName, 10, 10, -1636557322); Run ("password", salt, hashName, 20, 20, -1403130075); // getbytes equal to hash size Run ("password", null, hashName, 30, 32, -1013167039); // getbytes more than hash size Run ("password", salt, hashName, 40, 40, 379553148); Run ("password", null, hashName, 50, 50, 1031928292); Run ("monomono", salt, hashName, 60, 60, 1933836953); Run ("monomono", null, hashName, 70, 70, -956782587); Run ("monomono", salt, hashName, 80, 80, 1239391711); Run ("monomono", null, hashName, 90, 90, -872090432); Run ("monomono", salt, hashName, 100, 100, -591569127); } [Test] public void SHA384 () { const string hashName = "SHA384"; // getbytes less than hash size Run ("password", null, hashName, 10, 10, 323393534); Run ("password", salt, hashName, 20, 20, -2034683704); Run ("password", null, hashName, 30, 32, 167978389); Run ("password", salt, hashName, 40, 40, 2123410525); // getbytes equal to hash size Run ("password", null, hashName, 50, 48, -47538843); // getbytes more than hash size Run ("monomono", salt, hashName, 60, 60, -118610774); Run ("monomono", null, hashName, 70, 70, 772360425); Run ("monomono", salt, hashName, 80, 80, -1018881215); Run ("monomono", null, hashName, 90, 90, -1585583772); Run ("monomono", salt, hashName, 100, 100, -821501990); } [Test] public void SHA512 () { const string hashName = "SHA512"; // getbytes less than hash size Run ("password", null, hashName, 10, 10, 708870265); Run ("password", salt, hashName, 20, 20, 23889227); Run ("password", null, hashName, 30, 32, 1718904507); Run ("password", salt, hashName, 40, 40, 979228711); Run ("password", null, hashName, 50, 48, 1554003653); // getbytes equal to hash size Run ("monomono", salt, hashName, 60, 64, 1251099126); // getbytes more than hash size Run ("monomono", null, hashName, 70, 70, 1021441810); Run ("monomono", salt, hashName, 80, 80, 640059310); Run ("monomono", null, hashName, 90, 90, 1178147201); Run ("monomono", salt, hashName, 100, 100, 206423887); } // get one block after the other [Test] public void OneByOne () { byte[] key = { 0x91, 0xDA, 0xF9, 0x9D, 0x7C, 0xA9, 0xB4, 0x42, 0xB8, 0xD9, 0x45, 0xAB, 0x69, 0xEE, 0x12, 0xBC, 0x48, 0xDD, 0x38, 0x74 }; PasswordDeriveBytes pd = new PasswordDeriveBytes ("password", salt, "SHA1", 1); string msg = "PKCS#5-Long password salt SHA1 (1)"; int bloc = key.Length; int iter = (int) ((1000 + bloc - 1) / bloc); byte[] pass = null; for (int i=0; i < iter; i++) { pass = pd.GetBytes (bloc); } Assert.AreEqual (pass, key, msg); } [Test] public void SHA1SaltShortRun () { byte[] key = { 0x0B, 0x61, 0x93, 0x96, 0x3A, 0xFF, 0x0D, 0xFC, 0xF6, 0x3D, 0xA3, 0xDB, 0x34, 0xC2, 0x99, 0x71, 0x69, 0x11, 0x61, 0xB5 }; PasswordDeriveBytes pd = new PasswordDeriveBytes ("password", salt, "SHA1", 1); string msg = "PKCS#5 password salt SHA1 (1)"; ShortRun (msg, pd, key); } [Test] public void SHA1SaltLongRun () { byte[] key = { 0x91, 0xDA, 0xF9, 0x9D, 0x7C, 0xA9, 0xB4, 0x42, 0xB8, 0xD9, 0x45, 0xAB, 0x69, 0xEE, 0x12, 0xBC, 0x48, 0xDD, 0x38, 0x74 }; PasswordDeriveBytes pd = new PasswordDeriveBytes ("password", salt, "SHA1", 1); string msg = "PKCS#5-Long password salt SHA1 (1)"; LongRun (msg, pd, key); } [Test] public void SHA1NoSaltShortRun () { byte[] key = { 0x74, 0x61, 0x03, 0x6C, 0xA1, 0xFE, 0x85, 0x3E, 0xD9, 0x3F, 0x03, 0x06, 0x58, 0x45, 0xDE, 0x36, 0x52, 0xEF, 0x4B, 0x68 }; PasswordDeriveBytes pd = new PasswordDeriveBytes ("mono", null, "SHA1", 10); string msg = "PKCS#5 mono null SHA1 (10)"; ShortRun (msg, pd, key); } [Test] public void SHA1NoSaltLongRun () { byte[] key = { 0x3A, 0xF8, 0x33, 0x88, 0x39, 0x61, 0x29, 0x75, 0x5C, 0x17, 0xD2, 0x9E, 0x8A, 0x78, 0xEB, 0xBD, 0x89, 0x1E, 0x4C, 0x67 }; PasswordDeriveBytes pd = new PasswordDeriveBytes ("mono", null, "SHA1", 10); string msg = "PKCS#5-Long mono null SHA1 (10)"; LongRun (msg, pd, key); } [Test] public void MD5SaltShortRun () { byte[] key = { 0xA5, 0x4D, 0x4E, 0xDD, 0x3A, 0x59, 0xAC, 0x98, 0x08, 0xDA, 0xE7, 0xF2, 0x85, 0x2F, 0x7F, 0xF2 }; PasswordDeriveBytes pd = new PasswordDeriveBytes ("mono", salt, "MD5", 100); string msg = "PKCS#5 mono salt MD5 (100)"; ShortRun (msg, pd, key); } [Test] public void MD5SaltLongRun () { byte[] key = { 0x92, 0x51, 0x4D, 0x10, 0xE1, 0x5F, 0xA8, 0x44, 0xEF, 0xFC, 0x0F, 0x1F, 0x6F, 0x3E, 0x40, 0x36 }; PasswordDeriveBytes pd = new PasswordDeriveBytes ("mono", salt, "MD5", 100); string msg = "PKCS#5-Long mono salt MD5 (100)"; LongRun (msg, pd, key); } [Test] public void MD5NoSaltShortRun () { byte[] key = { 0x39, 0xEB, 0x82, 0x84, 0xCF, 0x1A, 0x3B, 0x3C, 0xA1, 0xF2, 0x68, 0xAF, 0xBF, 0xAC, 0x41, 0xA6 }; PasswordDeriveBytes pd = new PasswordDeriveBytes ("password", null, "MD5", 1000); string msg = "PKCS#5 password null MD5 (1000)"; ShortRun (msg, pd, key); } [Test] public void MD5NoSaltLongRun () { byte[] key = { 0x49, 0x3C, 0x00, 0x69, 0xB4, 0x55, 0x21, 0xA4, 0xC9, 0x69, 0x2E, 0xFF, 0xAA, 0xED, 0x4C, 0x72 }; PasswordDeriveBytes pd = new PasswordDeriveBytes ("password", null, "MD5", 1000); string msg = "PKCS#5-Long password null MD5 (1000)"; LongRun (msg, pd, key); } [Test] public void Properties () { // create object... PasswordDeriveBytes pd = new PasswordDeriveBytes ("password", null, "MD5", 1000); Assert.AreEqual ("MD5", pd.HashName, "HashName-MD5"); Assert.AreEqual (1000, pd.IterationCount, "IterationCount-1000"); // ...then change all its properties... pd.HashName = "SHA1"; Assert.AreEqual ("SHA1", pd.HashName, "HashName-SHA1"); pd.Salt = salt; Assert.AreEqual (ssalt, BitConverter.ToString (pd.Salt), "Salt"); pd.IterationCount = 1; Assert.AreEqual (1, pd.IterationCount, "IterationCount-1"); byte[] expectedKey = { 0x0b, 0x61, 0x93, 0x96 }; // ... before using it Assert.AreEqual (expectedKey, pd.GetBytes (4), "PKCS#5 test properties"); // it should work but if we try to set any properties after GetBytes // they should all throw an exception try { pd.HashName = "SHA256"; Assert.Fail ("PKCS#5 can't set HashName after GetBytes - expected CryptographicException but got none"); } catch (CryptographicException) { // do nothing, this is what we expect } catch (Exception e) { Assert.Fail ("PKCS#5 can't set HashName after GetBytes - expected CryptographicException but got " + e.ToString ()); } try { pd.Salt = expectedKey; Assert.Fail ("PKCS#5 can't set Salt after GetBytes - expected CryptographicException but got none"); } catch (CryptographicException) { // do nothing, this is what we expect } catch (Exception e) { Assert.Fail ("PKCS#5 can't set Salt after GetBytes - expected CryptographicException but got " + e.ToString ()); } try { pd.IterationCount = 10; Assert.Fail ("PKCS#5 can't set IterationCount after GetBytes - expected CryptographicException but got none"); } catch (CryptographicException) { // do nothing, this is what we expect } catch (Exception e) { Assert.Fail ("PKCS#5 can't set IterationCount after GetBytes - expected CryptographicException but got " + e.ToString ()); } // same thing after Reset pd.Reset (); try { pd.HashName = "SHA256"; Assert.Fail ("PKCS#5 can't set HashName after Reset - expected CryptographicException but got none"); } catch (CryptographicException) { // do nothing, this is what we expect } catch (Exception e) { Assert.Fail ("PKCS#5 can't set HashName after Reset - expected CryptographicException but got " + e.ToString ()); } try { pd.Salt = expectedKey; Assert.Fail ("PKCS#5 can't set Salt after Reset - expected CryptographicException but got none"); } catch (CryptographicException) { // do nothing, this is what we expect } catch (Exception e) { Assert.Fail ("PKCS#5 can't set Salt after Reset - expected CryptographicException but got " + e.ToString ()); } try { pd.IterationCount = 10; Assert.Fail ("PKCS#5 can't set IterationCount after Reset - expected CryptographicException but got none"); } catch (CryptographicException) { // do nothing, this is what we expect } catch (Exception e) { Assert.Fail ("PKCS#5 can't set IterationCount after Reset - expected CryptographicException but got " + e.ToString ()); } } // FIXME: should we treat this as a bug or as a feature ? [Test] #if ! NET_2_0 [ExpectedException (typeof (NullReferenceException))] #endif public void StrangeBehaviour () { // create object with a salt... PasswordDeriveBytes pd = new PasswordDeriveBytes ("password", salt, "MD5", 1000); // ...then change the salt to null pd.Salt = null; } [Test] [ExpectedException (typeof (CryptographicException))] public void CryptDeriveKey_TooLongKey () { PasswordDeriveBytes pd = new PasswordDeriveBytes ("password", null, "MD5", 1000); pd.CryptDeriveKey ("AlgName", "MD5", 256, new byte [8]); } } }
namespace java.util { [global::MonoJavaBridge.JavaClass()] public partial class LinkedList : java.util.AbstractSequentialList, List, java.lang.Cloneable, java.io.Serializable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected LinkedList(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public override bool add(java.lang.Object arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.LinkedList.staticClass, "add", "(Ljava/lang/Object;)Z", ref global::java.util.LinkedList._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m1; public override void add(int arg0, java.lang.Object arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.LinkedList.staticClass, "add", "(ILjava/lang/Object;)V", ref global::java.util.LinkedList._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m2; public override global::java.lang.Object get(int arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.util.LinkedList.staticClass, "get", "(I)Ljava/lang/Object;", ref global::java.util.LinkedList._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m3; public virtual global::java.lang.Object clone() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.util.LinkedList.staticClass, "clone", "()Ljava/lang/Object;", ref global::java.util.LinkedList._m3) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m4; public override int indexOf(java.lang.Object arg0) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.util.LinkedList.staticClass, "indexOf", "(Ljava/lang/Object;)I", ref global::java.util.LinkedList._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m5; public override void clear() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.LinkedList.staticClass, "clear", "()V", ref global::java.util.LinkedList._m5); } private static global::MonoJavaBridge.MethodId _m6; public override int lastIndexOf(java.lang.Object arg0) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.util.LinkedList.staticClass, "lastIndexOf", "(Ljava/lang/Object;)I", ref global::java.util.LinkedList._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m7; public override bool contains(java.lang.Object arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.LinkedList.staticClass, "contains", "(Ljava/lang/Object;)Z", ref global::java.util.LinkedList._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m8; public override bool addAll(java.util.Collection arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.LinkedList.staticClass, "addAll", "(Ljava/util/Collection;)Z", ref global::java.util.LinkedList._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m9; public override bool addAll(int arg0, java.util.Collection arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.LinkedList.staticClass, "addAll", "(ILjava/util/Collection;)Z", ref global::java.util.LinkedList._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m10; public override int size() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.util.LinkedList.staticClass, "size", "()I", ref global::java.util.LinkedList._m10); } private static global::MonoJavaBridge.MethodId _m11; public override global::java.lang.Object[] toArray(java.lang.Object[] arg0) { return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.Object>(this, global::java.util.LinkedList.staticClass, "toArray", "([Ljava/lang/Object;)[Ljava/lang/Object;", ref global::java.util.LinkedList._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.Object[]; } private static global::MonoJavaBridge.MethodId _m12; public override global::java.lang.Object[] toArray() { return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.Object>(this, global::java.util.LinkedList.staticClass, "toArray", "()[Ljava/lang/Object;", ref global::java.util.LinkedList._m12) as java.lang.Object[]; } private static global::MonoJavaBridge.MethodId _m13; public virtual void push(java.lang.Object arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.LinkedList.staticClass, "push", "(Ljava/lang/Object;)V", ref global::java.util.LinkedList._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m14; public virtual global::java.lang.Object pop() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.util.LinkedList.staticClass, "pop", "()Ljava/lang/Object;", ref global::java.util.LinkedList._m14) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m15; public override global::java.lang.Object remove(int arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.util.LinkedList.staticClass, "remove", "(I)Ljava/lang/Object;", ref global::java.util.LinkedList._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m16; public override bool remove(java.lang.Object arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.LinkedList.staticClass, "remove", "(Ljava/lang/Object;)Z", ref global::java.util.LinkedList._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m17; public virtual global::java.lang.Object remove() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.util.LinkedList.staticClass, "remove", "()Ljava/lang/Object;", ref global::java.util.LinkedList._m17) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m18; public override global::java.lang.Object set(int arg0, java.lang.Object arg1) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.util.LinkedList.staticClass, "set", "(ILjava/lang/Object;)Ljava/lang/Object;", ref global::java.util.LinkedList._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m19; public override global::java.util.ListIterator listIterator(int arg0) { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.ListIterator>(this, global::java.util.LinkedList.staticClass, "listIterator", "(I)Ljava/util/ListIterator;", ref global::java.util.LinkedList._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.util.ListIterator; } private static global::MonoJavaBridge.MethodId _m20; public virtual global::java.lang.Object poll() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.util.LinkedList.staticClass, "poll", "()Ljava/lang/Object;", ref global::java.util.LinkedList._m20) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m21; public virtual global::java.lang.Object peek() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.util.LinkedList.staticClass, "peek", "()Ljava/lang/Object;", ref global::java.util.LinkedList._m21) as java.lang.Object; } public new global::java.lang.Object First { get { return getFirst(); } } private static global::MonoJavaBridge.MethodId _m22; public virtual global::java.lang.Object getFirst() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.util.LinkedList.staticClass, "getFirst", "()Ljava/lang/Object;", ref global::java.util.LinkedList._m22) as java.lang.Object; } public new global::java.lang.Object Last { get { return getLast(); } } private static global::MonoJavaBridge.MethodId _m23; public virtual global::java.lang.Object getLast() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.util.LinkedList.staticClass, "getLast", "()Ljava/lang/Object;", ref global::java.util.LinkedList._m23) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m24; public virtual global::java.lang.Object removeFirst() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.util.LinkedList.staticClass, "removeFirst", "()Ljava/lang/Object;", ref global::java.util.LinkedList._m24) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m25; public virtual global::java.lang.Object removeLast() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.util.LinkedList.staticClass, "removeLast", "()Ljava/lang/Object;", ref global::java.util.LinkedList._m25) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m26; public virtual void addFirst(java.lang.Object arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.LinkedList.staticClass, "addFirst", "(Ljava/lang/Object;)V", ref global::java.util.LinkedList._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m27; public virtual void addLast(java.lang.Object arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.LinkedList.staticClass, "addLast", "(Ljava/lang/Object;)V", ref global::java.util.LinkedList._m27, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m28; public virtual global::java.lang.Object element() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.util.LinkedList.staticClass, "element", "()Ljava/lang/Object;", ref global::java.util.LinkedList._m28) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m29; public virtual bool offer(java.lang.Object arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.LinkedList.staticClass, "offer", "(Ljava/lang/Object;)Z", ref global::java.util.LinkedList._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m30; public virtual bool offerFirst(java.lang.Object arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.LinkedList.staticClass, "offerFirst", "(Ljava/lang/Object;)Z", ref global::java.util.LinkedList._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m31; public virtual bool offerLast(java.lang.Object arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.LinkedList.staticClass, "offerLast", "(Ljava/lang/Object;)Z", ref global::java.util.LinkedList._m31, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m32; public virtual global::java.lang.Object peekFirst() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.util.LinkedList.staticClass, "peekFirst", "()Ljava/lang/Object;", ref global::java.util.LinkedList._m32) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m33; public virtual global::java.lang.Object peekLast() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.util.LinkedList.staticClass, "peekLast", "()Ljava/lang/Object;", ref global::java.util.LinkedList._m33) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m34; public virtual global::java.lang.Object pollFirst() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.util.LinkedList.staticClass, "pollFirst", "()Ljava/lang/Object;", ref global::java.util.LinkedList._m34) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m35; public virtual global::java.lang.Object pollLast() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.util.LinkedList.staticClass, "pollLast", "()Ljava/lang/Object;", ref global::java.util.LinkedList._m35) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m36; public virtual bool removeFirstOccurrence(java.lang.Object arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.LinkedList.staticClass, "removeFirstOccurrence", "(Ljava/lang/Object;)Z", ref global::java.util.LinkedList._m36, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m37; public virtual bool removeLastOccurrence(java.lang.Object arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.LinkedList.staticClass, "removeLastOccurrence", "(Ljava/lang/Object;)Z", ref global::java.util.LinkedList._m37, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m38; public virtual global::java.util.Iterator descendingIterator() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.Iterator>(this, global::java.util.LinkedList.staticClass, "descendingIterator", "()Ljava/util/Iterator;", ref global::java.util.LinkedList._m38) as java.util.Iterator; } private static global::MonoJavaBridge.MethodId _m39; public LinkedList(java.util.Collection arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.LinkedList._m39.native == global::System.IntPtr.Zero) global::java.util.LinkedList._m39 = @__env.GetMethodIDNoThrow(global::java.util.LinkedList.staticClass, "<init>", "(Ljava/util/Collection;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.LinkedList.staticClass, global::java.util.LinkedList._m39, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m40; public LinkedList() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.LinkedList._m40.native == global::System.IntPtr.Zero) global::java.util.LinkedList._m40 = @__env.GetMethodIDNoThrow(global::java.util.LinkedList.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.LinkedList.staticClass, global::java.util.LinkedList._m40); Init(@__env, handle); } static LinkedList() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.util.LinkedList.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/util/LinkedList")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using Xunit; using Tests.Collections; using System.Reflection; using System.Linq; namespace System.Collections.ObjectModel.Tests { public class ReadOnlyDictionaryTests { /// <summary> /// Current key that the m_generateItemFunc is at. /// </summary> private static int s_currentKey = int.MaxValue; /// <summary> /// Function to generate a KeyValuePair. /// </summary> private static Func<KeyValuePair<int, string>> s_generateItemFunc = () => { var kvp = new KeyValuePair<int, string>(s_currentKey, s_currentKey.ToString()); s_currentKey--; return kvp; }; /// <summary> /// Tests that the ReadOnlyDictionary is constructed with the given /// Dictionary. /// </summary> [Fact] public static void CtorTests() { KeyValuePair<int, string>[] expectedArr = new KeyValuePair<int, string>[] { new KeyValuePair<int, string>(1, "one"), new KeyValuePair<int, string>(2, "two"), new KeyValuePair<int, string>(3, "three"), new KeyValuePair<int, string>(4, "four"), new KeyValuePair<int, string>(5, "five") }; DummyDictionary<int, string> dummyExpectedDict = new DummyDictionary<int, string>(expectedArr); ReadOnlyDictionary<int, string> dictionary = new ReadOnlyDictionary<int, string>(dummyExpectedDict); IReadOnlyDictionary_T_Test<int, string> helper = new IReadOnlyDictionary_T_Test<int, string>(dictionary, expectedArr, s_generateItemFunc); helper.InitialItems_Tests(); IDictionary<int, string> dictAsIDictionary = dictionary; Assert.True(dictAsIDictionary.IsReadOnly, "ReadonlyDictionary Should be readonly"); IDictionary dictAsNonGenericIDictionary = dictionary; Assert.True(dictAsNonGenericIDictionary.IsFixedSize); Assert.True(dictAsNonGenericIDictionary.IsReadOnly); } /// <summary> /// Tests that an argument null exception is returned when given /// a null dictionary to initialise ReadOnlyDictionary. /// </summary> [Fact] public static void CtorTests_Negative() { Assert.Throws<ArgumentNullException>(() => { ReadOnlyDictionary<int, string> dict = new ReadOnlyDictionary<int, string>(null); }); } /// <summary> /// Tests that true is returned when the key exists in the dictionary /// and false otherwise. /// </summary> [Fact] public static void ContainsKeyTests() { KeyValuePair<int, string>[] expectedArr = new KeyValuePair<int, string>[] { new KeyValuePair<int, string>(1, "one"), new KeyValuePair<int, string>(2, "two"), new KeyValuePair<int, string>(3, "three"), new KeyValuePair<int, string>(4, "four"), new KeyValuePair<int, string>(5, "five") }; DummyDictionary<int, string> dummyExpectedDict = new DummyDictionary<int, string>(expectedArr); ReadOnlyDictionary<int, string> dictionary = new ReadOnlyDictionary<int, string>(dummyExpectedDict); IReadOnlyDictionary_T_Test<int, string> helper = new IReadOnlyDictionary_T_Test<int, string>(dictionary, expectedArr, s_generateItemFunc); helper.ContainsKey_Tests(); } /// <summary> /// Tests that the value is retrieved from a dictionary when its /// key exists in the dictionary and false when it does not. /// </summary> [Fact] public static void TryGetValueTests() { KeyValuePair<int, string>[] expectedArr = new KeyValuePair<int, string>[] { new KeyValuePair<int, string>(1, "one"), new KeyValuePair<int, string>(2, "two"), new KeyValuePair<int, string>(3, "three"), new KeyValuePair<int, string>(4, "four"), new KeyValuePair<int, string>(5, "five") }; DummyDictionary<int, string> dummyExpectedDict = new DummyDictionary<int, string>(expectedArr); ReadOnlyDictionary<int, string> dictionary = new ReadOnlyDictionary<int, string>(dummyExpectedDict); IReadOnlyDictionary_T_Test<int, string> helper = new IReadOnlyDictionary_T_Test<int, string>(dictionary, expectedArr, s_generateItemFunc); helper.TryGetValue_Tests(); } /// <summary> /// Tests that the dictionary's keys can be retrieved. /// </summary> [Fact] public static void GetKeysTests() { KeyValuePair<int, string>[] expectedArr = new KeyValuePair<int, string>[] { new KeyValuePair<int, string>(1, "one"), new KeyValuePair<int, string>(2, "two"), new KeyValuePair<int, string>(3, "three"), new KeyValuePair<int, string>(4, "four"), new KeyValuePair<int, string>(5, "five") }; DummyDictionary<int, string> dummyExpectedDict = new DummyDictionary<int, string>(expectedArr); ReadOnlyDictionary<int, string> dictionary = new ReadOnlyDictionary<int, string>(dummyExpectedDict); IReadOnlyDictionary_T_Test<int, string> helper = new IReadOnlyDictionary_T_Test<int, string>(dictionary, expectedArr, s_generateItemFunc); helper.Keys_get_Tests(); } /// <summary> /// Tests that the dictionary's values can be retrieved. /// </summary> [Fact] public static void GetValuesTests() { KeyValuePair<int, string>[] expectedArr = new KeyValuePair<int, string>[] { new KeyValuePair<int, string>(1, "one"), new KeyValuePair<int, string>(2, "two"), new KeyValuePair<int, string>(3, "three"), new KeyValuePair<int, string>(4, "four"), new KeyValuePair<int, string>(5, "five") }; DummyDictionary<int, string> dummyExpectedDict = new DummyDictionary<int, string>(expectedArr); ReadOnlyDictionary<int, string> dictionary = new ReadOnlyDictionary<int, string>(dummyExpectedDict); IReadOnlyDictionary_T_Test<int, string> helper = new IReadOnlyDictionary_T_Test<int, string>(dictionary, expectedArr, s_generateItemFunc); helper.Values_get_Tests(); } /// <summary> /// Tests that items can be retrieved by key from the Dictionary. /// </summary> [Fact] public static void GetItemTests() { KeyValuePair<int, string>[] expectedArr = new KeyValuePair<int, string>[] { new KeyValuePair<int, string>(1, "one"), new KeyValuePair<int, string>(2, "two"), new KeyValuePair<int, string>(3, "three"), new KeyValuePair<int, string>(4, "four"), new KeyValuePair<int, string>(5, "five") }; DummyDictionary<int, string> dummyExpectedDict = new DummyDictionary<int, string>(expectedArr); ReadOnlyDictionary<int, string> dictionary = new ReadOnlyDictionary<int, string>(dummyExpectedDict); IReadOnlyDictionary_T_Test<int, string> helper = new IReadOnlyDictionary_T_Test<int, string>(dictionary, expectedArr, s_generateItemFunc); helper.Item_get_Tests(); } /// <summary> /// Tests that an KeyNotFoundException is thrown when retrieving the /// value of an item whose key is not in the dictionary. /// </summary> [Fact] public static void GetItemTests_Negative() { KeyValuePair<int, string>[] expectedArr = new KeyValuePair<int, string>[] { new KeyValuePair<int, string>(1, "one"), new KeyValuePair<int, string>(2, "two"), new KeyValuePair<int, string>(3, "three"), new KeyValuePair<int, string>(4, "four"), new KeyValuePair<int, string>(5, "five") }; DummyDictionary<int, string> dummyExpectedDict = new DummyDictionary<int, string>(expectedArr); ReadOnlyDictionary<int, string> dictionary = new ReadOnlyDictionary<int, string>(dummyExpectedDict); IReadOnlyDictionary_T_Test<int, string> helper = new IReadOnlyDictionary_T_Test<int, string>(dictionary, expectedArr, s_generateItemFunc); helper.Item_get_Tests_Negative(); } /// <summary> /// Tests that a ReadOnlyDictionary cannot be modified. That is, that /// Add, Remove, Clear does not work. /// </summary> [Fact] public static void CannotModifyDictionaryTests_Negative() { KeyValuePair<int, string>[] expectedArr = new KeyValuePair<int, string>[] { new KeyValuePair<int, string>(1, "one"), new KeyValuePair<int, string>(2, "two"), new KeyValuePair<int, string>(3, "three"), new KeyValuePair<int, string>(4, "four"), new KeyValuePair<int, string>(5, "five") }; DummyDictionary<int, string> dummyExpectedDict = new DummyDictionary<int, string>(expectedArr); ReadOnlyDictionary<int, string> dictionary = new ReadOnlyDictionary<int, string>(dummyExpectedDict); IReadOnlyDictionary_T_Test<int, string> helper = new IReadOnlyDictionary_T_Test<int, string>(); IDictionary<int, string> dictAsIDictionary = dictionary; Assert.Throws<NotSupportedException>(() => dictAsIDictionary.Add(new KeyValuePair<int, string>(7, "seven"))); Assert.Throws<NotSupportedException>(() => dictAsIDictionary.Add(7, "seven")); Assert.Throws<NotSupportedException>(() => dictAsIDictionary.Remove(new KeyValuePair<int, string>(1, "one"))); Assert.Throws<NotSupportedException>(() => dictAsIDictionary.Remove(1)); Assert.Throws<NotSupportedException>(() => dictAsIDictionary.Clear()); helper.VerifyCollection(dictionary, expectedArr); //verifying that the collection has not changed. } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")] public static void DebuggerAttributeTests() { DebuggerAttributes.ValidateDebuggerDisplayReferences(new ReadOnlyDictionary<int, int>(new Dictionary<int, int>())); DebuggerAttributes.ValidateDebuggerTypeProxyProperties(new ReadOnlyDictionary<int, int>(new Dictionary<int, int>())); DebuggerAttributes.ValidateDebuggerDisplayReferences(new ReadOnlyDictionary<int, int>(new Dictionary<int, int>()).Keys); DebuggerAttributes.ValidateDebuggerDisplayReferences(new ReadOnlyDictionary<int, int>(new Dictionary<int, int>()).Values); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")] public static void DebuggerAttribute_NullDictionary_ThrowsArgumentNullException() { TargetInvocationException ex = Assert.Throws<TargetInvocationException>(() => DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(ReadOnlyDictionary<int, int>), null)); ArgumentNullException argumentNullException = Assert.IsType<ArgumentNullException>(ex.InnerException); Assert.Equal("dictionary", argumentNullException.ParamName); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")] public static void DebuggerAttribute_NullDictionaryKeys_ThrowsArgumentNullException() { TargetInvocationException ex = Assert.Throws<TargetInvocationException>(() => DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(ReadOnlyDictionary<int, int>.KeyCollection), new Type[] { typeof(int) }, null)); ArgumentNullException argumentNullException = Assert.IsType<ArgumentNullException>(ex.InnerException); Assert.Equal("collection", argumentNullException.ParamName); } } public class TestReadOnlyDictionary<TKey, TValue> : ReadOnlyDictionary<TKey, TValue> { public TestReadOnlyDictionary(IDictionary<TKey, TValue> dict) : base(dict) { } public IDictionary<TKey, TValue> GetDictionary() { return Dictionary; } } public class DictionaryThatDoesntImplementNonGeneric<TKey, TValue> : IDictionary<TKey, TValue> { private readonly IDictionary<TKey, TValue> _inner; public DictionaryThatDoesntImplementNonGeneric(IDictionary<TKey, TValue> inner) { _inner = inner; } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return _inner.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable) _inner).GetEnumerator(); } public void Add(KeyValuePair<TKey, TValue> item) { _inner.Add(item); } public void Clear() { _inner.Clear(); } public bool Contains(KeyValuePair<TKey, TValue> item) { return _inner.Contains(item); } public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { _inner.CopyTo(array, arrayIndex); } public bool Remove(KeyValuePair<TKey, TValue> item) { return _inner.Remove(item); } public int Count { get { return _inner.Count; } } public bool IsReadOnly { get { return _inner.IsReadOnly; } } public void Add(TKey key, TValue value) { _inner.Add(key, value); } public bool ContainsKey(TKey key) { return _inner.ContainsKey(key); } public bool Remove(TKey key) { return _inner.Remove(key); } public bool TryGetValue(TKey key, out TValue value) { return _inner.TryGetValue(key, out value); } public TValue this[TKey key] { get { return _inner[key]; } set { _inner[key] = value; } } public ICollection<TKey> Keys { get { return _inner.Keys; } } public ICollection<TValue> Values { get { return _inner.Values; } } } public class ReadOnlyDictionaryOverNonGenericTests : IDictionaryTest<string, int> { public ReadOnlyDictionaryOverNonGenericTests() : base(false) { } private int m_next_item = 1; protected override bool IsResetNotSupported { get { return false; } } protected override bool IsGenericCompatibility { get { return false; } } protected override bool ItemsMustBeUnique { get { return true; } } protected override bool ItemsMustBeNonNull { get { return true; } } protected override object GenerateItem() { return new KeyValuePair<string, int>(m_next_item.ToString(), m_next_item++); } protected override IEnumerable GetEnumerable(object[] items) { var dict = new DictionaryThatDoesntImplementNonGeneric<string, int>(new Dictionary<string, int>()); foreach (KeyValuePair<string, int> p in items) dict[p.Key] = p.Value; return new TestReadOnlyDictionary<string, int>(dict); } protected override object[] InvalidateEnumerator(IEnumerable enumerable) { var roDict = (TestReadOnlyDictionary<string, int>)enumerable; var dict = roDict.GetDictionary(); var item = (KeyValuePair<string, int>)GenerateItem(); dict.Add(item.Key, item.Value); var arr = new object[dict.Count]; ((ICollection)roDict).CopyTo(arr, 0); return arr; } } public class ReadOnlyDictionaryTestsStringInt : IDictionaryTest<string, int> { public ReadOnlyDictionaryTestsStringInt() : base(false) { } private int m_next_item = 1; protected override bool IsResetNotSupported { get { return false; } } protected override bool IsGenericCompatibility { get { return false; } } protected override bool ItemsMustBeUnique { get { return true; } } protected override bool ItemsMustBeNonNull { get { return true; } } protected override object GenerateItem() { return new KeyValuePair<string, int>(m_next_item.ToString(), m_next_item++); } protected override IEnumerable GetEnumerable(object[] items) { var dict = new Dictionary<string, int>(); foreach (KeyValuePair<string, int> p in items) dict[p.Key] = p.Value; return new TestReadOnlyDictionary<string, int>(dict); } protected override object[] InvalidateEnumerator(IEnumerable enumerable) { var roDict = (TestReadOnlyDictionary<string, int>)enumerable; var dict = roDict.GetDictionary(); var item = (KeyValuePair<string, int>)GenerateItem(); dict.Add(item.Key, item.Value); var arr = new object[dict.Count]; ((ICollection)roDict).CopyTo(arr, 0); return arr; } } /// <summary> /// Helper class that performs all of the IReadOnlyDictionary /// verifications. /// </summary> public class IReadOnlyDictionary_T_Test<TKey, TValue> { private readonly IReadOnlyDictionary<TKey, TValue> _collection; private readonly KeyValuePair<TKey, TValue>[] _expectedItems; private readonly Func<KeyValuePair<TKey, TValue>> _generateItem; /// <summary> /// Initializes a new instance of the IReadOnlyDictionary_T_Test. /// </summary> public IReadOnlyDictionary_T_Test( IReadOnlyDictionary<TKey, TValue> collection, KeyValuePair<TKey, TValue>[] expectedItems, Func<KeyValuePair<TKey, TValue>> generateItem) { _collection = collection; _expectedItems = expectedItems; _generateItem = generateItem; } public IReadOnlyDictionary_T_Test() { } /// <summary> /// Tests that the initial items in the readonly collection /// are equivalent to the collection it was initialised with. /// </summary> public void InitialItems_Tests() { //[] Verify the initial items in the collection VerifyCollection(_collection, _expectedItems); //verifies the non-generic enumerator. VerifyEnumerator(_collection, _expectedItems); } /// <summary> /// Checks that the dictionary contains all keys of the expected items. /// And returns false when the dictionary does not contain a key. /// </summary> public void ContainsKey_Tests() { Assert.Equal(_expectedItems.Length, _collection.Count); for (int i = 0; i < _collection.Count; i++) { Assert.True(_collection.ContainsKey(_expectedItems[i].Key), "Err_5983muqjl Verifying ContainsKey the item in the collection and the expected existing items(" + _expectedItems[i].Key + ")"); } //Verify that the collection was not mutated VerifyCollection(_collection, _expectedItems); KeyValuePair<TKey, TValue> nonExistingItem = _generateItem(); while (!IsUniqueKey(_expectedItems, nonExistingItem)) { nonExistingItem = _generateItem(); } TKey nonExistingKey = nonExistingItem.Key; Assert.False(_collection.ContainsKey(nonExistingKey), "Err_4713ebda Verifying ContainsKey the non-existing item in the collection and the expected non-existing items key:" + nonExistingKey); //Verify that the collection was not mutated VerifyCollection(_collection, _expectedItems); } /// <summary> /// Tests that you can get values that exist in the collection /// and not when the value is not in the collection. /// </summary> public void TryGetValue_Tests() { Assert.Equal(_expectedItems.Length, _collection.Count); for (int i = 0; i < _collection.Count; i++) { TValue itemValue; Assert.True(_collection.TryGetValue(_expectedItems[i].Key, out itemValue), "Err_2621pnyan Verifying TryGetValue the item in the collection and the expected existing items(" + _expectedItems[i].Value + ")"); Assert.Equal(_expectedItems[i].Value, itemValue); } //Verify that the collection was not mutated VerifyCollection(_collection, _expectedItems); KeyValuePair<TKey, TValue> nonExistingItem = _generateItem(); while (!IsUniqueKey(_expectedItems, nonExistingItem)) { nonExistingItem = _generateItem(); } TValue nonExistingItemValue; Assert.False(_collection.TryGetValue(nonExistingItem.Key, out nonExistingItemValue), "Err_4561rtio Verifying TryGetValue returns false when looking for a non-existing item in the collection (" + nonExistingItem.Key + ")"); //Verify that the collection was not mutated VerifyCollection(_collection, _expectedItems); } /// <summary> /// Tests that you can get all the keys in the collection. /// </summary> public void Keys_get_Tests() { // Verify Key get_Values int numItemsSeen = 0; foreach (TKey key in _collection.Keys) { numItemsSeen++; TValue value; Assert.True(_collection.TryGetValue(key, out value), "Items in the Keys collection should exist in the dictionary!"); } Assert.Equal(_collection.Count, numItemsSeen); } /// <summary> /// Tests that you can get all the values in the collection. /// </summary> public void Values_get_Tests() { // Verify Values get_Values // Copy collection values to another collection, then compare them. List<TValue> knownValuesList = new List<TValue>(); foreach (KeyValuePair<TKey, TValue> pair in _collection) knownValuesList.Add(pair.Value); int numItemsSeen = 0; foreach (TValue value in _collection.Values) { numItemsSeen++; Assert.True(knownValuesList.Contains(value), "Items in the Values collection should exist in the dictionary!"); } Assert.Equal(_collection.Count, numItemsSeen); } /// <summary> /// Runs all of the tests on get Item. /// </summary> public void Item_get_Tests() { // Verify get_Item with existing item on Collection Assert.Equal(_expectedItems.Length, _collection.Count); for (int i = 0; i < _expectedItems.Length; ++i) { TKey expectedKey = _expectedItems[i].Key; TValue expectedValue = _expectedItems[i].Value; TValue actualValue = _collection[expectedKey]; Assert.Equal(expectedValue, actualValue); } //Verify that the collection was not mutated VerifyCollection(_collection, _expectedItems); } /// <summary> /// Tests that KeyNotFoundException is thrown when trying to get from /// a Dictionary whose key is not in the collection. /// </summary> public void Item_get_Tests_Negative() { // Verify get_Item with non-existing on Collection TKey nonExistingKey = _generateItem().Key; Assert.Throws<KeyNotFoundException>(() => { TValue itemValue = _collection[nonExistingKey]; }); //Verify that the collection was not mutated VerifyCollection(_collection, _expectedItems); } /// <summary> /// Verifies that the items in the given collection match the expected items. /// </summary> public void VerifyCollection(IReadOnlyDictionary<TKey, TValue> collection, KeyValuePair<TKey, TValue>[] expectedItems) { // verify that you can get all items in collection. Assert.Equal(expectedItems.Length, collection.Count); for (int i = 0; i < expectedItems.Length; ++i) { TKey expectedKey = expectedItems[i].Key; TValue expectedValue = expectedItems[i].Value; Assert.Equal(expectedValue, collection[expectedKey]); } VerifyGenericEnumerator(collection, expectedItems); } #region Helper Methods /// <summary> /// Verifies that the generic enumerator retrieves the correct items. /// </summary> private void VerifyGenericEnumerator(IReadOnlyDictionary<TKey, TValue> collection, KeyValuePair<TKey, TValue>[] expectedItems) { IEnumerator<KeyValuePair<TKey, TValue>> enumerator = collection.GetEnumerator(); int iterations = 0; int expectedCount = expectedItems.Length; // There is no sequential order to the collection, so we're testing that all the items // in the readonlydictionary exist in the array. bool[] itemsVisited = new bool[expectedCount]; bool itemFound; while ((iterations < expectedCount) && enumerator.MoveNext()) { KeyValuePair<TKey, TValue> currentItem = enumerator.Current; KeyValuePair<TKey, TValue> tempItem; // Verify we have not gotten more items then we expected Assert.True(iterations < expectedCount, "Err_9844awpa More items have been returned from the enumerator(" + iterations + " items) then are in the expectedElements(" + expectedCount + " items)"); // Verify Current returned the correct value itemFound = false; for (int i = 0; i < itemsVisited.Length; ++i) { if (!itemsVisited[i] && currentItem.Equals(expectedItems[i])) { itemsVisited[i] = true; itemFound = true; break; } } Assert.True(itemFound, "Err_1432pauy Current returned unexpected value=" + currentItem); // Verify Current always returns the same value every time it is called for (int i = 0; i < 3; i++) { tempItem = enumerator.Current; Assert.Equal(currentItem, tempItem); } iterations++; } for (int i = 0; i < expectedCount; ++i) { Assert.True(itemsVisited[i], "Err_052848ahiedoi Expected Current to return true for item: " + expectedItems[i] + "index: " + i); } Assert.Equal(expectedCount, iterations); for (int i = 0; i < 3; i++) { Assert.False(enumerator.MoveNext(), "Err_2929ahiea Expected MoveNext to return false after" + iterations + " iterations"); } enumerator.Dispose(); } /// <summary> /// Verifies that the non-generic enumerator retrieves the correct items. /// </summary> private void VerifyEnumerator(IReadOnlyDictionary<TKey, TValue> collection, KeyValuePair<TKey, TValue>[] expectedItems) { IEnumerator enumerator = collection.GetEnumerator(); int iterations = 0; int expectedCount = expectedItems.Length; // There is no sequential order to the collection, so we're testing that all the items // in the readonlydictionary exist in the array. bool[] itemsVisited = new bool[expectedCount]; bool itemFound; while ((iterations < expectedCount) && enumerator.MoveNext()) { object currentItem = enumerator.Current; object tempItem; // Verify we have not gotten more items then we expected Assert.True(iterations < expectedCount, "Err_9844awpa More items have been returned from the enumerator(" + iterations + " items) then are in the expectedElements(" + expectedCount + " items)"); // Verify Current returned the correct value itemFound = false; for (int i = 0; i < itemsVisited.Length; ++i) { if (!itemsVisited[i] && expectedItems[i].Equals(currentItem)) { itemsVisited[i] = true; itemFound = true; break; } } Assert.True(itemFound, "Err_1432pauy Current returned unexpected value=" + currentItem); // Verify Current always returns the same value every time it is called for (int i = 0; i < 3; i++) { tempItem = enumerator.Current; Assert.Equal(currentItem, tempItem); } iterations++; } for (int i = 0; i < expectedCount; ++i) { Assert.True(itemsVisited[i], "Err_052848ahiedoi Expected Current to return true for item: " + expectedItems[i] + "index: " + i); } Assert.Equal(expectedCount, iterations); for (int i = 0; i < 3; i++) { Assert.False(enumerator.MoveNext(), "Err_2929ahiea Expected MoveNext to return false after" + iterations + " iterations"); } } /// <summary> /// tests whether the given item's key is unique in a collection. /// returns true if it is and false otherwise. /// </summary> private bool IsUniqueKey(KeyValuePair<TKey, TValue>[] items, KeyValuePair<TKey, TValue> item) { for (int i = 0; i < items.Length; ++i) { if (items[i].Key != null && items[i].Key.Equals(item.Key)) { return false; } } return true; } #endregion } /// <summary> /// Helper Dictionary class that implements basic IDictionary /// functionality but none of the modifier methods. /// </summary> public class DummyDictionary<TKey, TValue> : IDictionary<TKey, TValue> { private readonly List<KeyValuePair<TKey, TValue>> _items; private readonly TKey[] _keys; private readonly TValue[] _values; public DummyDictionary(KeyValuePair<TKey, TValue>[] items) { _keys = new TKey[items.Length]; _values = new TValue[items.Length]; _items = new List<KeyValuePair<TKey, TValue>>(items); for (int i = 0; i < items.Length; i++) { _keys[i] = items[i].Key; _values[i] = items[i].Value; } } #region IDictionary<TKey, TValue> methods public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return _items.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _items.GetEnumerator(); } public int Count { get { return _items.Count; } } public bool ContainsKey(TKey key) { foreach (var item in _items) { if (item.Key.Equals(key)) return true; } return false; } public bool Contains(KeyValuePair<TKey, TValue> item) { foreach (var i in _items) { if (i.Equals(item)) return true; } return false; } public ICollection<TKey> Keys { get { return _keys; } } public ICollection<TValue> Values { get { return _values; } } public TValue this[TKey key] { get { foreach (var item in _items) { if (item.Key.Equals(key)) return item.Value; } throw new KeyNotFoundException("key does not exist"); } set { throw new NotImplementedException(); } } public bool TryGetValue(TKey key, out TValue value) { value = default(TValue); if (!ContainsKey(key)) return false; value = this[key]; return true; } public bool IsReadOnly { get { return false; } } #endregion #region Not Implemented Methods public void Add(TKey key, TValue value) { throw new NotImplementedException("Should not have been able to add to the collection."); } public void Add(KeyValuePair<TKey, TValue> item) { throw new NotImplementedException("Should not have been able to add to the collection."); } public bool Remove(TKey key) { throw new NotImplementedException("Should not have been able remove items from the collection."); } public bool Remove(KeyValuePair<TKey, TValue> item) { throw new NotImplementedException("Should not have been able remove items from the collection."); } public void Clear() { throw new NotImplementedException("Should not have been able clear the collection."); } public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { throw new NotImplementedException(); } #endregion } }
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using System.Xml; namespace Braintree.Tests { //NOTE: good [TestFixture] public class CreditCardVerificationTest { private BraintreeGateway gateway; [SetUp] public void Setup() { gateway = new BraintreeGateway(); } [Test] public void ConstructFromResponse() { StringBuilder builder = new StringBuilder(); builder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); builder.Append("<api-error-response>"); builder.Append(" <verification>"); builder.Append(" <avs-error-response-code nil=\"true\"></avs-error-response-code>"); builder.Append(" <avs-postal-code-response-code>I</avs-postal-code-response-code>"); builder.Append(" <status>processor_declined</status>"); builder.Append(" <processor-response-code>2000</processor-response-code>"); builder.Append(" <avs-street-address-response-code>I</avs-street-address-response-code>"); builder.Append(" <processor-response-text>Do Not Honor</processor-response-text>"); builder.Append(" <cvv-response-code>M</cvv-response-code>"); builder.Append(" </verification>"); builder.Append(" <errors>"); builder.Append(" <errors type=\"array\"/>"); builder.Append(" </errors>"); builder.Append("</api-error-response>"); XmlDocument doc = new XmlDocument(); doc.LoadXml(builder.ToString()); CreditCardVerification verification = new CreditCardVerification(new NodeWrapper(doc).GetNode("//verification"), gateway); Assert.AreEqual(null, verification.AvsErrorResponseCode); Assert.AreEqual("I", verification.AvsPostalCodeResponseCode); Assert.AreEqual(VerificationStatus.PROCESSOR_DECLINED, verification.Status); Assert.AreEqual("2000", verification.ProcessorResponseCode); Assert.AreEqual("I", verification.AvsStreetAddressResponseCode); Assert.AreEqual("Do Not Honor", verification.ProcessorResponseText); Assert.AreEqual("M", verification.CvvResponseCode); } [Test] public void ConstructFromResponseWithNoVerification() { StringBuilder builder = new StringBuilder(); builder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); builder.Append("<api-error-response>"); builder.Append(" <errors>"); builder.Append(" <errors type=\"array\"/>"); builder.Append(" </errors>"); builder.Append("</api-error-response>"); XmlDocument doc = new XmlDocument(); doc.LoadXml(builder.ToString()); CreditCardVerification verification = new CreditCardVerification(new NodeWrapper(doc).GetNode("//verification"), gateway); Assert.AreEqual(null, verification.AvsErrorResponseCode); Assert.AreEqual(null, verification.AvsPostalCodeResponseCode); Assert.AreEqual(null, verification.Status); Assert.AreEqual(null, verification.ProcessorResponseCode); Assert.AreEqual(null, verification.AvsStreetAddressResponseCode); Assert.AreEqual(null, verification.ProcessorResponseText); Assert.AreEqual(null, verification.CvvResponseCode); } [Test] public void Search_OnMultipleValueFields() { var createRequest = new CustomerRequest { CreditCard = new CreditCardRequest { Number = CreditCardNumbers.FailsSandboxVerification.Visa, ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { VerifyCard = true } } }; Result<Customer> result = gateway.Customer.Create(createRequest); CreditCardVerification verification1 = gateway.CreditCardVerification.Find(result.CreditCardVerification.Id); createRequest = new CustomerRequest { CreditCard = new CreditCardRequest { Number = CreditCardNumbers.FailsSandboxVerification.MasterCard, ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { VerifyCard = true } } }; result = gateway.Customer.Create(createRequest); CreditCardVerification verification2 = gateway.CreditCardVerification.Find(result.CreditCardVerification.Id); CreditCardVerificationSearchRequest searchRequest = new CreditCardVerificationSearchRequest(). CreditCardCardType.IncludedIn(CreditCardCardType.VISA, CreditCardCardType.MASTER_CARD). Ids.IncludedIn(verification1.Id, verification2.Id). Status.IncludedIn(verification1.Status); ResourceCollection<CreditCardVerification> collection = gateway.CreditCardVerification.Search(searchRequest); Assert.AreEqual(2, collection.MaximumCount); } [Test] public void CardTypeIndicators() { string name = Guid.NewGuid().ToString("n"); var createRequest = new CustomerRequest { CreditCard = new CreditCardRequest { CardholderName = name, Number = CreditCardNumbers.CardTypeIndicators.Unknown, ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { VerifyCard = true } } }; gateway.Customer.Create(createRequest); CreditCardVerificationSearchRequest searchRequest = new CreditCardVerificationSearchRequest(). CreditCardCardholderName.Is(name); ResourceCollection<CreditCardVerification> collection = gateway.CreditCardVerification.Search(searchRequest); CreditCardVerification verification = collection.FirstItem; Assert.AreEqual(verification.CreditCard.Prepaid, Braintree.CreditCardPrepaid.UNKNOWN); Assert.AreEqual(verification.CreditCard.Debit, Braintree.CreditCardDebit.UNKNOWN); Assert.AreEqual(verification.CreditCard.DurbinRegulated, Braintree.CreditCardDurbinRegulated.UNKNOWN); Assert.AreEqual(verification.CreditCard.Commercial, Braintree.CreditCardCommercial.UNKNOWN); Assert.AreEqual(verification.CreditCard.Healthcare, Braintree.CreditCardHealthcare.UNKNOWN); Assert.AreEqual(verification.CreditCard.Payroll, Braintree.CreditCardPayroll.UNKNOWN); } [Test] public void Search_OnTextFields() { var createRequest = new CustomerRequest { Email = "[email protected]", CreditCard = new CreditCardRequest { Number = "4111111111111111", ExpirationDate = "05/12", BillingAddress = new CreditCardAddressRequest { PostalCode = "44444" }, Options = new CreditCardOptionsRequest { VerifyCard = true } } }; Result<Customer> result = gateway.Customer.Create(createRequest); string token = result.Target.CreditCards[0].Token; string postalCode = result.Target.CreditCards[0].BillingAddress.PostalCode; string customerId = result.Target.Id; string customerEmail = result.Target.Email; CreditCardVerificationSearchRequest searchRequest = new CreditCardVerificationSearchRequest(). PaymentMethodToken.Is(token). BillingAddressDetailsPostalCode.Is(postalCode). CustomerId.Is(customerId). CustomerEmail.Is(customerEmail); ResourceCollection<CreditCardVerification> collection = gateway.CreditCardVerification.Search(searchRequest); CreditCardVerification verification = collection.FirstItem; Assert.AreEqual(1, collection.MaximumCount); Assert.AreEqual(token, verification.CreditCard.Token); Assert.AreEqual(postalCode, verification.BillingAddress.PostalCode); } } }
using UnityEngine; using System.Collections; using UnityEngine.Events; using System.Collections.Generic; using UnityEngine.UI; using UnityEngine.EventSystems; public delegate void HapticPulseEventHandler(ushort strength); [ExecuteInEditMode] //Lets us set up buttons from inspector option public class RadialMenu : MonoBehaviour { #region Variables public List<RadialMenuButton> buttons; public GameObject buttonPrefab; [Range(0f, 1f)] public float buttonThickness = 0.5f; public Color buttonColor = Color.white; public float offsetDistance = 1; [Range(0, 359)] public float offsetRotation; public bool rotateIcons; public float iconMargin; public bool isShown; public bool hideOnRelease; public bool executeOnUnclick; [Range(0, 1599)] public ushort baseHapticStrength; public event HapticPulseEventHandler FireHapticPulse; //Has to be public to keep state from editor -> play mode? public List<GameObject> menuButtons; private int currentHover = -1; private int currentPress = -1; #endregion #region Unity Methods private void Awake() { if (Application.isPlaying) { if (!isShown) { transform.localScale = Vector3.zero; } RegenerateButtons(); } } private void Update() { //Keep track of pressed button and constantly invoke Hold event if (currentPress != -1) { buttons[currentPress].OnHold.Invoke(); } } #endregion #region Interaction //Turns and Angle and Event type into a button action private void InteractButton(float angle, ButtonEvent evt) //Can't pass ExecuteEvents as parameter? Unity gives error { //Get button ID from angle float buttonAngle = 360f / buttons.Count; //Each button is an arc with this angle angle = mod((angle + offsetRotation), 360); //Offset the touch coordinate with our offset int buttonID = (int)mod(((angle + (buttonAngle / 2f)) / buttonAngle), buttons.Count); //Convert angle into ButtonID (This is the magic) var pointer = new PointerEventData(EventSystem.current); //Create a new EventSystem (UI) Event //If we changed buttons while moving, un-hover and un-click the last button we were on if (currentHover != buttonID && currentHover != -1) { ExecuteEvents.Execute(menuButtons[currentHover], pointer, ExecuteEvents.pointerUpHandler); ExecuteEvents.Execute(menuButtons[currentHover], pointer, ExecuteEvents.pointerExitHandler); buttons[currentHover].OnHoverExit.Invoke(); if (executeOnUnclick && currentPress != -1) { ExecuteEvents.Execute(menuButtons[buttonID], pointer, ExecuteEvents.pointerDownHandler); AttempHapticPulse ((ushort)(baseHapticStrength * 1.666f)); } } if (evt == ButtonEvent.click) //Click button if click, and keep track of current press (executes button action) { ExecuteEvents.Execute(menuButtons[buttonID], pointer, ExecuteEvents.pointerDownHandler); currentPress = buttonID; if (!executeOnUnclick) { buttons[buttonID].OnClick.Invoke (); AttempHapticPulse ((ushort)(baseHapticStrength * 2.5f)); } } else if (evt == ButtonEvent.unclick) //Clear press id to stop invoking OnHold method (hide menu) { ExecuteEvents.Execute(menuButtons[buttonID], pointer, ExecuteEvents.pointerUpHandler); currentPress = -1; if (executeOnUnclick) { AttempHapticPulse ((ushort)(baseHapticStrength * 2.5f)); buttons[buttonID].OnClick.Invoke (); } } else if (evt == ButtonEvent.hoverOn && currentHover != buttonID) // Show hover UI event (darken button etc). Show menu { ExecuteEvents.Execute(menuButtons[buttonID], pointer, ExecuteEvents.pointerEnterHandler); buttons[buttonID].OnHoverEnter.Invoke(); AttempHapticPulse (baseHapticStrength); } currentHover = buttonID; //Set current hover ID, need this to un-hover if selected button changes } /* * Public methods to call Interact */ public void HoverButton(float angle) { InteractButton(angle, ButtonEvent.hoverOn); } public void ClickButton(float angle) { InteractButton(angle, ButtonEvent.click); } public void UnClickButton(float angle) { InteractButton(angle, ButtonEvent.unclick); } public void ToggleMenu() { if (isShown) { HideMenu(true); } else { ShowMenu(); } } public void StopTouching() { if (currentHover != -1) { var pointer = new PointerEventData(EventSystem.current); ExecuteEvents.Execute(menuButtons[currentHover], pointer, ExecuteEvents.pointerExitHandler); buttons[currentHover].OnHoverExit.Invoke(); currentHover = -1; } } /* * Public methods to Show/Hide menu */ public void ShowMenu() { if (!isShown) { isShown = true; StopCoroutine("TweenMenuScale"); StartCoroutine("TweenMenuScale", isShown); } } public RadialMenuButton GetButton(int id) { if (id < buttons.Count) { return buttons[id]; } return null; } public void HideMenu(bool force) { if (isShown && (hideOnRelease || force)) { isShown = false; StopCoroutine("TweenMenuScale"); StartCoroutine("TweenMenuScale", isShown); } } //Simple tweening for menu, scales linearly from 0 to 1 and 1 to 0 private IEnumerator TweenMenuScale(bool show) { float targetScale = 0; Vector3 Dir = -1 * Vector3.one; if (show) { targetScale = 1; Dir = Vector3.one; } int i = 0; //Sanity check for infinite loops while (i < 250 && ((show && transform.localScale.x < targetScale) || (!show && transform.localScale.x > targetScale))) { transform.localScale += Dir * Time.deltaTime * 4f; //Tweening function - currently 0.25 second linear yield return true; i++; } transform.localScale = Dir * targetScale; StopCoroutine("TweenMenuScale"); } private void AttempHapticPulse(ushort strength) { if (strength > 0 && FireHapticPulse != null) { FireHapticPulse (strength); } } #endregion #region Generation //Creates all the button Arcs and populates them with desired icons public void RegenerateButtons() { RemoveAllButtons(); for (int i = 0; i < buttons.Count; i++) { // Initial placement/instantiation GameObject newButton = Instantiate(buttonPrefab); newButton.transform.SetParent(transform); newButton.transform.localScale = Vector3.one; newButton.GetComponent<RectTransform>().offsetMax = Vector2.zero; newButton.GetComponent<RectTransform>().offsetMin = Vector2.zero; //Setup button arc UICircle circle = newButton.GetComponent<UICircle>(); if (buttonThickness == 1) { circle.fill = true; } else { circle.thickness = (int)(buttonThickness * (GetComponent<RectTransform>().rect.width / 2f)); } int fillPerc = (int)(100f / buttons.Count); circle.fillPercent = fillPerc; circle.color = buttonColor; //Final placement/rotation float angle = ((360 / buttons.Count) * i) + offsetRotation; newButton.transform.localEulerAngles = new Vector3(0, 0, angle); newButton.layer = 4; //UI Layer newButton.transform.localPosition = Vector3.zero; if (circle.fillPercent < 55) { float angleRad = (angle * Mathf.PI) / 180f; Vector2 angleVector = new Vector2(-Mathf.Cos(angleRad), -Mathf.Sin(angleRad)); newButton.transform.localPosition += (Vector3)angleVector * offsetDistance; } //Place and populate Button Icon GameObject buttonIcon = newButton.GetComponentInChildren<RadialButtonIcon>().gameObject; if (buttons[i].ButtonIcon == null) { buttonIcon.SetActive(false); } else { buttonIcon.GetComponent<Image>().sprite = buttons[i].ButtonIcon; buttonIcon.transform.localPosition = new Vector2(-1 * ((newButton.GetComponent<RectTransform>().rect.width / 2f) - (circle.thickness / 2f)), 0); //Min icon size from thickness and arc float scale1 = Mathf.Abs(circle.thickness); float R = Mathf.Abs(buttonIcon.transform.localPosition.x); float bAngle = (359f * circle.fillPercent * 0.01f * Mathf.PI) / 180f; float scale2 = (R * 2 * Mathf.Sin(bAngle / 2f)); if (circle.fillPercent > 24) //Scale calc doesn't work for > 90 degrees { scale2 = float.MaxValue; } float iconScale = Mathf.Min(scale1, scale2) - iconMargin; buttonIcon.GetComponent<RectTransform>().sizeDelta = new Vector2(iconScale, iconScale); //Rotate icons all vertically if desired if (!rotateIcons) { buttonIcon.transform.eulerAngles = GetComponentInParent<Canvas>().transform.eulerAngles; } } menuButtons.Add(newButton); } } public void AddButton(RadialMenuButton newButton) { buttons.Add(newButton); RegenerateButtons(); } private void RemoveAllButtons() { if (menuButtons == null) { menuButtons = new List<GameObject>(); } for (int i = 0; i < menuButtons.Count; i++) { DestroyImmediate(menuButtons[i]); } menuButtons = new List<GameObject>(); } #endregion #region Utility private float mod(float a, float b) { return a - b * Mathf.Floor(a / b); } #endregion } [System.Serializable] public class RadialMenuButton { public Sprite ButtonIcon; public UnityEvent OnClick; public UnityEvent OnHold; public UnityEvent OnHoverEnter; public UnityEvent OnHoverExit; } public enum ButtonEvent { hoverOn, hoverOff, click, unclick }
/* transpiled with BefunCompile v1.3.0 (c) 2017 */ public static class Program { private static readonly string _g = "AR+LCAAAAAAABADtmk2PozgQhv+KQ3ouQUxjlwPpqIVW2sveZo9zGKUvK3H1Kafe/z4FzoexjTHd4Am0LUWNoZqXx1UUL1HO5CcOQsg2wEAZ0oqFk7uMUHJ/B5X7gWO9"+ "iynpfkS5BcqFvu+iXJSLclEuykW5KBdK7rqPGEM9GuW85dwjyk0o56GpRXxJOXVfNyDKfVhuxFio3NhriHIWuU50J8pT13JiT7lu1Brk9H2jEhjlPnXSKBflliS37Y4o"+ "tzq5ySSj3B+VM2P1SMuRKPfV5MxYQ8oaatnzteXmGFEuykW5LyCXh5VjYeVoWDkRVi4JK/dPWDnHdyhzyAVezN2q7ztY9X0XuGcGXsx198zAo0r+/zfZVTQ7JiT5dUz+"+ "S87zi74fxTMq/UpfvpHXOYValieUqHj9neEH8MPx89cschVluahYXtMU8rZuKmgm/DLhzWR/mZDkZ0Iwdr9PdxiF+9tNno9LwHtWipwdU1rn7PU9O4gc2gng5EXkvJ1w"+ "nOyzvcj37XQvKOBfCiKt/RPQXlcTfa3Sk/qv/ZMPjooAXmK22Z7eGG6kjCIaFaPW2La8dVrjymdjVvlDa9xdgjdN7+SQ81vW7hpXrhPKcRZFmYuC72pgTQ0UILe4KJjc"+ "AlFQucV6z1LJ7J+6rcqSb88FfvWKc0VJ7aos6iNNy0K4T1iVZRtXOuOq8tBGHcyoE1Ym2eLu7bGZbgdLHWMx1BEnU3duT2eLOmf07SnHK6ZFzYo6paUA3CoFL2ooRedU"+ "l9iDoCVGYOxBAG4dLFH0gPsx4qVz7Eyqo2/uiGesM0qlA0nHfOhA0jEnXfZIdFylAwcdokkyxEytdIhGH4kO0SQZYqYDdPRKB310Mnc7BvWzQvhHcyfpQNK5KpO1dODO"+ "3WZ7fmsgASEPEnJeuko7crLRcd/cgewtBh15anPX0DFJR2ejOymt0kV3q0xJ1tTnQM/M7D2T2Juz/xWPjn1PN5tvzeP4hW42WU3Zs5y86rnjVzo2QAeSztIzifIaF4aO"+ "9h4xK1PScRed2jMzC139+SseE+tBBwodH67MW8+00aWfv+Ixsf2louXu5lOclan2TBtd/2LOQid6j1grk8vnglfPtNE5vPYcdHnvEc1nZiN8pnxW633zMe876TOzET7z"+ "SscMOv75Kx4T61eZXKXz9Zkto0YX+IngUZmqz8xG+EwbXeDK7L/NrT4zG+EzbXQBKlP0bHeH1Wf65Q7uvSU83Ynz5lsSTqDO+42fw2dmVjoEavzxtXU2bwCl2jrd3+N8"+ "jE73x8o1uU/h8Jm+dFCqrfOR6VSfOUh3a53tW04pC/Qx6Uyf6ZO7Ox08NJ3pMwfpbq3z8XNn+kyTrnnrNnIH994yJZ3rrVuNcg7NZ0p3Zfeaw99qD48xuZtgaD7zSmfz"+ "mgun4zodrIZO9ZnSf6yJTvWZV7pVVebNZ64vd6bPbBlXQmf6zPXRqT5zTXSmz1wTnekz10en+sy10CGTdMbSbjaeuDDt5rR0/c5YjinUJB0YdFCYdnOpdNyg44VpN5dK"+ "R+9094d680ZaqJZlqXTdyrzTQaHazaXS8R46vorcWStTdsxLfS6Zjum54yodWzidtTJvdHzhdEplanZzlZUJKt2SK7P5jtL6RLjRwXR0yikq7Rf1+q8wJ6GrEpLYf2ks"+ "Jjl/d/wGS+iz/X1bAAA="; private static readonly long[] g = System.Array.ConvertAll(zd(System.Convert.FromBase64String(_g)),b=>(long)b); private static byte[]zd(byte[]o){byte[]d=System.Linq.Enumerable.ToArray(System.Linq.Enumerable.Skip(o, 1));for(int i=0;i<o[0];i++)d=zs(d);return d;} private static byte[]zs(byte[]o){using(var c=new System.IO.MemoryStream(o)) using(var z=new System.IO.Compression.GZipStream(c,System.IO.Compression.CompressionMode.Decompress)) using(var r=new System.IO.MemoryStream()){z.CopyTo(r);return r.ToArray();}} private static long gr(long x,long y){return(x>=0&&y>=0&&x<111&&y<211)?g[y*111+x]:0;} private static void gw(long x,long y,long v){if(x>=0&&y>=0&&x<111&&y<211)g[y*111+x]=v;} private static long td(long a,long b){ return (b==0)?0:(a/b); } private static long tm(long a,long b){ return (b==0)?0:(a%b); } private static System.Collections.Generic.Stack<long> s=new System.Collections.Generic.Stack<long>(); private static long sp(){ return (s.Count==0)?0:s.Pop(); } private static void sa(long v){ s.Push(v); } private static long sr(){ return (s.Count==0)?0:s.Peek(); } static void Main(string[]args) { long t0; gw(2,1,0); gw(2,3,2520); gw(3,1,0); gw(108,99,32); sa(9999); sa(9999); _1: if(sp()!=0)goto _205;else goto _2; _2: gw(2,0,1); sp(); _3: gw(3,0,gr(2,0)+1); _4: gw(4,0,gr(3,0)+1); _5: gw(5,0,gr(4,0)+1); _6: gw((gr(2,0)*10)+gr(3,0),(gr(5,0)*10)+gr(4,0),88); gw(3,1,gr(3,1)+1); t0=gr(5,0)-9; gw(5,0,gr(5,0)+1); if((t0)!=0)goto _6;else goto _8; _8: t0=gr(4,0)-8; gw(4,0,gr(4,0)+1); if((t0)!=0)goto _5;else goto _9; _9: t0=gr(3,0)-7; gw(3,0,gr(3,0)+1); if((t0)!=0)goto _4;else goto _10; _10: t0=gr(2,0)-6; gw(2,0,gr(2,0)+1); if((t0)!=0)goto _3;else goto _11; _11: if(gr(3,1)!=1)goto _13;else goto _12; _12: System.Console.Out.Write(gr(1,4)+" "); System.Console.Out.Write(gr(2,4)+" "); System.Console.Out.Write(gr(3,4)+" "); System.Console.Out.Write(gr(4,4)+" "); return; _13: gw(2,1,gr(2,1)+1); gw(3,1,0); gw(2,0,1); _14: gw(3,0,gr(2,0)+1); _15: gw(4,0,gr(3,0)+1); _16: gw(5,0,gr(4,0)+1); _17: if(gr((gr(2,0)*10)+gr(3,0),(gr(5,0)*10)+gr(4,0))!=88)goto _18;else goto _22; _18: t0=gr(5,0)-9; gw(5,0,gr(5,0)+1); if((t0)!=0)goto _17;else goto _19; _19: t0=gr(4,0)-8; gw(4,0,gr(4,0)+1); if((t0)!=0)goto _16;else goto _20; _20: t0=gr(3,0)-7; gw(3,0,gr(3,0)+1); if((t0)!=0)goto _15;else goto _21; _21: t0=gr(2,0)-6; gw(2,0,gr(2,0)+1); if((t0)!=0)goto _14;else goto _11; _22: gw(1,6,gr(2,0)*gr(2,3)); gw(2,6,gr(3,0)*gr(2,3)); gw(3,6,gr(4,0)*gr(2,3)); gw(4,6,gr(5,0)*gr(2,3)); gw(7,6,0); _23: t0=gr(7,6); sa(gr(7,6)); gw(7,6,gr(7,6)+1); if((t0)!=0)goto _24;else goto _204; _24: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _25;else goto _203; _25: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _26;else goto _202; _26: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _27;else goto _201; _27: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _28;else goto _200; _28: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _29;else goto _199; _29: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _30;else goto _198; _30: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _31;else goto _197; _31: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _32;else goto _196; _32: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _33;else goto _195; _33: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _34;else goto _194; _34: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _35;else goto _193; _35: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _36;else goto _192; _36: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _37;else goto _191; _37: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _38;else goto _190; _38: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _39;else goto _189; _39: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _40;else goto _188; _40: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _41;else goto _187; _41: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _42;else goto _186; _42: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _43;else goto _185; _43: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _44;else goto _184; _44: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _45;else goto _183; _45: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _46;else goto _182; _46: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _47;else goto _181; _47: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _48;else goto _180; _48: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _49;else goto _179; _49: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _50;else goto _178; _50: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _51;else goto _177; _51: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _52;else goto _176; _52: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _53;else goto _175; _53: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _54;else goto _174; _54: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _55;else goto _173; _55: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _56;else goto _172; _56: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _57;else goto _171; _57: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _58;else goto _170; _58: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _59;else goto _169; _59: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _60;else goto _167; _60: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _61;else goto _165; _61: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _62;else goto _163; _62: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _63;else goto _161; _63: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _64;else goto _159; _64: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _65;else goto _157; _65: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _66;else goto _155; _66: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _67;else goto _153; _67: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _68;else goto _151; _68: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _69;else goto _149; _69: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _70;else goto _147; _70: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _146;else goto _71; _71: sp(); if((gr(3,6))!=0)goto _72;else goto _23; _72: gw(7,7,0); gw(1,7,gr(1,6)); gw(2,7,gr(2,6)); gw(3,7,td(gr(4,6)*gr(2,3),gr(3,6))); _73: t0=gr(7,7); sa(gr(7,7)); gw(7,7,gr(7,7)+1); if((t0)!=0)goto _74;else goto _145; _74: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _75;else goto _144; _75: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _76;else goto _143; _76: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _77;else goto _142; _77: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _78;else goto _141; _78: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _79;else goto _140; _79: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _80;else goto _139; _80: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _81;else goto _138; _81: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _82;else goto _137; _82: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _83;else goto _136; _83: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _84;else goto _135; _84: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _85;else goto _134; _85: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _86;else goto _133; _86: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _87;else goto _132; _87: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _88;else goto _131; _88: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _89;else goto _130; _89: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _90;else goto _129; _90: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _91;else goto _128; _91: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _92;else goto _126; _92: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _93;else goto _124; _93: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _94;else goto _122; _94: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _95;else goto _120; _95: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _96;else goto _118; _96: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _117;else goto _97; _97: sp(); if((gr(2,7))!=0)goto _99;else goto _98; _98: sa(4); goto _73; _99: gw(7,8,0); gw(1,8,gr(1,7)); gw(2,8,td(gr(3,7)*gr(2,3),gr(2,7))); _100: t0=gr(7,8); sa(gr(7,8)); gw(7,8,gr(7,8)+1); if((t0)!=0)goto _101;else goto _116; _101: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _102;else goto _115; _102: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _103;else goto _114; _103: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _104;else goto _113; _104: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _109;else goto _105; _105: sp(); if((gr(2,8))!=0)goto _106;else goto _100; _106: gw(1,9,td(gr(1,8)*gr(2,3),gr(2,8))); _107: if(((((td(gr(1,9),gr(2,3)))-gr(2,1)!=0)?1:0)+((tm(gr(1,9),gr(2,3))!=0)?1L:0L))!=0)goto _100;else goto _108; _108: gw(3,1,gr(3,1)+1); gw(1,4,gr(2,0)); gw(2,4,gr(3,0)); gw(3,4,gr(4,0)); gw(4,4,gr(5,0)); goto _18; _109: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _112;else goto _110; _110: sp(); if((gr(1,8))!=0)goto _111;else goto _100; _111: gw(1,9,td(gr(2,8)*gr(2,3),gr(1,8))); goto _107; _112: sp(); goto _73; _113: gw(1,9,td(gr(1,8)*gr(2,8),gr(2,3))); sp(); goto _107; _114: gw(1,9,gr(2,8)-gr(1,8)); sp(); goto _107; _115: gw(1,9,gr(1,8)-gr(2,8)); sp(); goto _107; _116: gw(1,9,gr(1,8)+gr(2,8)); sp(); goto _107; _117: sp(); goto _23; _118: sp(); if((gr(2,7))!=0)goto _119;else goto _98; _119: gw(7,8,0); gw(1,8,gr(2,7)); gw(2,8,td(gr(3,7)*gr(2,3),gr(1,7))); goto _100; _120: sp(); if((gr(2,7))!=0)goto _121;else goto _98; _121: gw(7,8,0); gw(1,8,gr(1,7)); gw(2,8,td(gr(2,7)*gr(2,3),gr(3,7))); goto _100; _122: sp(); if((gr(2,7))!=0)goto _123;else goto _98; _123: gw(7,8,0); gw(1,8,gr(3,7)); gw(2,8,td(gr(2,7)*gr(2,3),gr(1,7))); goto _100; _124: sp(); if((gr(2,7))!=0)goto _125;else goto _98; _125: gw(7,8,0); gw(1,8,td(gr(1,7)*gr(2,3),gr(3,7))); gw(2,8,gr(2,7)); goto _100; _126: sp(); if((gr(2,7))!=0)goto _127;else goto _98; _127: gw(7,8,0); gw(1,8,td(gr(1,7)*gr(2,3),gr(2,7))); gw(2,8,gr(3,7)); goto _100; _128: gw(7,8,0); gw(1,8,gr(1,7)); gw(2,8,td(gr(3,7)*gr(2,7),gr(2,3))); sp(); goto _100; _129: gw(7,8,0); gw(1,8,gr(2,7)); gw(2,8,td(gr(3,7)*gr(1,7),gr(2,3))); sp(); goto _100; _130: gw(7,8,0); gw(1,8,gr(1,7)); gw(2,8,td(gr(2,7)*gr(3,7),gr(2,3))); sp(); goto _100; _131: gw(7,8,0); gw(1,8,gr(3,7)); gw(2,8,td(gr(2,7)*gr(1,7),gr(2,3))); sp(); goto _100; _132: gw(7,8,0); gw(1,8,td(gr(1,7)*gr(3,7),gr(2,3))); gw(2,8,gr(2,7)); sp(); goto _100; _133: gw(7,8,0); gw(1,8,td(gr(1,7)*gr(2,7),gr(2,3))); gw(2,8,gr(3,7)); sp(); goto _100; _134: gw(7,8,0); gw(1,8,gr(1,7)); gw(2,8,gr(3,7)-gr(2,7)); sp(); goto _100; _135: gw(7,8,0); gw(1,8,gr(2,7)); gw(2,8,gr(3,7)-gr(1,7)); sp(); goto _100; _136: gw(7,8,0); gw(1,8,gr(1,7)); gw(2,8,gr(2,7)-gr(3,7)); sp(); goto _100; _137: gw(7,8,0); gw(1,8,gr(3,7)); gw(2,8,gr(2,7)-gr(1,7)); sp(); goto _100; _138: gw(7,8,0); gw(1,8,gr(1,7)-gr(3,7)); gw(2,8,gr(2,7)); sp(); goto _100; _139: gw(7,8,0); gw(1,8,gr(1,7)-gr(2,7)); gw(2,8,gr(3,7)); sp(); goto _100; _140: gw(7,8,0); gw(1,8,gr(1,7)); gw(2,8,gr(3,7)+gr(2,7)); sp(); goto _100; _141: gw(7,8,0); gw(1,8,gr(2,7)); gw(2,8,gr(3,7)+gr(1,7)); sp(); goto _100; _142: gw(7,8,0); gw(1,8,gr(1,7)); gw(2,8,gr(2,7)+gr(3,7)); sp(); goto _100; _143: gw(7,8,0); gw(1,8,gr(3,7)); gw(2,8,gr(2,7)+gr(1,7)); sp(); goto _100; _144: gw(7,8,0); gw(1,8,gr(1,7)+gr(3,7)); gw(2,8,gr(2,7)); sp(); goto _100; _145: gw(7,8,0); gw(1,8,gr(1,7)+gr(2,7)); gw(2,8,gr(3,7)); sp(); goto _100; _146: gw((gr(2,0)*10)+gr(3,0),(gr(5,0)*10)+gr(4,0),32); sp(); goto _18; _147: sp(); if((gr(2,6))!=0)goto _148;else goto _23; _148: gw(7,7,0); gw(1,7,gr(1,6)); gw(2,7,gr(3,6)); gw(3,7,td(gr(4,6)*gr(2,3),gr(2,6))); goto _73; _149: sp(); if((gr(1,6))!=0)goto _150;else goto _23; _150: gw(7,7,0); gw(1,7,gr(3,6)); gw(2,7,gr(2,6)); gw(3,7,td(gr(4,6)*gr(2,3),gr(1,6))); goto _73; _151: sp(); if((gr(4,6))!=0)goto _152;else goto _23; _152: gw(7,7,0); gw(1,7,gr(1,6)); gw(2,7,gr(2,6)); gw(3,7,td(gr(3,6)*gr(2,3),gr(4,6))); goto _73; _153: sp(); if((gr(2,6))!=0)goto _154;else goto _23; _154: gw(7,7,0); gw(1,7,gr(1,6)); gw(2,7,gr(4,6)); gw(3,7,td(gr(3,6)*gr(2,3),gr(2,6))); goto _73; _155: sp(); if((gr(1,6))!=0)goto _156;else goto _23; _156: gw(7,7,0); gw(1,7,gr(4,6)); gw(2,7,gr(2,6)); gw(3,7,td(gr(3,6)*gr(2,3),gr(1,6))); goto _73; _157: sp(); if((gr(4,6))!=0)goto _158;else goto _23; _158: gw(7,7,0); gw(1,7,gr(1,6)); gw(2,7,td(gr(2,6)*gr(2,3),gr(4,6))); gw(3,7,gr(3,6)); goto _73; _159: sp(); if((gr(3,6))!=0)goto _160;else goto _23; _160: gw(7,7,0); gw(1,7,gr(1,6)); gw(2,7,td(gr(2,6)*gr(2,3),gr(3,6))); gw(3,7,gr(4,6)); goto _73; _161: sp(); if((gr(1,6))!=0)goto _162;else goto _23; _162: gw(7,7,0); gw(1,7,gr(4,6)); gw(2,7,td(gr(2,6)*gr(2,3),gr(1,6))); gw(3,7,gr(3,6)); goto _73; _163: sp(); if((gr(4,6))!=0)goto _164;else goto _23; _164: gw(7,7,0); gw(1,7,td(gr(1,6)*gr(2,3),gr(4,6))); gw(2,7,gr(2,6)); gw(3,7,gr(3,6)); goto _73; _165: sp(); if((gr(3,6))!=0)goto _166;else goto _23; _166: gw(7,7,0); gw(1,7,td(gr(1,6)*gr(2,3),gr(3,6))); gw(2,7,gr(2,6)); gw(3,7,gr(4,6)); goto _73; _167: sp(); if((gr(2,6))!=0)goto _168;else goto _23; _168: gw(7,7,0); gw(1,7,td(gr(1,6)*gr(2,3),gr(2,6))); gw(2,7,gr(3,6)); gw(3,7,gr(4,6)); goto _73; _169: gw(7,7,0); gw(1,7,gr(1,6)); gw(2,7,gr(2,6)); gw(3,7,td(gr(4,6)*gr(3,6),gr(2,3))); sp(); goto _73; _170: gw(7,7,0); gw(1,7,gr(1,6)); gw(2,7,gr(3,6)); gw(3,7,td(gr(4,6)*gr(2,6),gr(2,3))); sp(); goto _73; _171: gw(7,7,0); gw(1,7,gr(3,6)); gw(2,7,gr(2,6)); gw(3,7,td(gr(4,6)*gr(1,6),gr(2,3))); sp(); goto _73; _172: gw(7,7,0); gw(1,7,gr(1,6)); gw(2,7,gr(2,6)); gw(3,7,td(gr(3,6)*gr(4,6),gr(2,3))); sp(); goto _73; _173: gw(7,7,0); gw(1,7,gr(1,6)); gw(2,7,gr(4,6)); gw(3,7,td(gr(3,6)*gr(2,6),gr(2,3))); sp(); goto _73; _174: gw(7,7,0); gw(1,7,gr(4,6)); gw(2,7,gr(2,6)); gw(3,7,td(gr(3,6)*gr(1,6),gr(2,3))); sp(); goto _73; _175: gw(7,7,0); gw(1,7,gr(1,6)); gw(2,7,td(gr(2,6)*gr(4,6),gr(2,3))); gw(3,7,gr(3,6)); sp(); goto _73; _176: gw(7,7,0); gw(1,7,gr(1,6)); gw(2,7,td(gr(2,6)*gr(3,6),gr(2,3))); gw(3,7,gr(4,6)); sp(); goto _73; _177: gw(7,7,0); gw(1,7,gr(4,6)); gw(2,7,td(gr(2,6)*gr(1,6),gr(2,3))); gw(3,7,gr(3,6)); sp(); goto _73; _178: gw(7,7,0); gw(1,7,td(gr(1,6)*gr(4,6),gr(2,3))); gw(2,7,gr(2,6)); gw(3,7,gr(3,6)); sp(); goto _73; _179: gw(7,7,0); gw(1,7,td(gr(1,6)*gr(3,6),gr(2,3))); gw(2,7,gr(2,6)); gw(3,7,gr(4,6)); sp(); goto _73; _180: gw(7,7,0); gw(1,7,td(gr(1,6)*gr(2,6),gr(2,3))); gw(2,7,gr(3,6)); gw(3,7,gr(4,6)); sp(); goto _73; _181: gw(7,7,0); gw(1,7,gr(1,6)); gw(2,7,gr(2,6)); gw(3,7,gr(4,6)-gr(3,6)); sp(); goto _73; _182: gw(7,7,0); gw(1,7,gr(1,6)); gw(2,7,gr(3,6)); gw(3,7,gr(4,6)-gr(2,6)); sp(); goto _73; _183: gw(7,7,0); gw(1,7,gr(3,6)); gw(2,7,gr(2,6)); gw(3,7,gr(4,6)-gr(1,6)); sp(); goto _73; _184: gw(7,7,0); gw(1,7,gr(1,6)); gw(2,7,gr(2,6)); gw(3,7,gr(3,6)-gr(4,6)); sp(); goto _73; _185: gw(7,7,0); gw(1,7,gr(1,6)); gw(2,7,gr(4,6)); gw(3,7,gr(3,6)-gr(2,6)); sp(); goto _73; _186: gw(7,7,0); gw(1,7,gr(4,6)); gw(2,7,gr(2,6)); gw(3,7,gr(3,6)-gr(1,6)); sp(); goto _73; _187: gw(7,7,0); gw(1,7,gr(1,6)); gw(2,7,gr(2,6)-gr(4,6)); gw(3,7,gr(3,6)); sp(); goto _73; _188: gw(7,7,0); gw(1,7,gr(1,6)); gw(2,7,gr(2,6)-gr(3,6)); gw(3,7,gr(4,6)); sp(); goto _73; _189: gw(7,7,0); gw(1,7,gr(4,6)); gw(2,7,gr(2,6)-gr(1,6)); gw(3,7,gr(3,6)); sp(); goto _73; _190: gw(7,7,0); gw(1,7,gr(1,6)-gr(4,6)); gw(2,7,gr(2,6)); gw(3,7,gr(3,6)); sp(); goto _73; _191: gw(7,7,0); gw(1,7,gr(1,6)-gr(3,6)); gw(2,7,gr(2,6)); gw(3,7,gr(4,6)); sp(); goto _73; _192: gw(7,7,0); gw(1,7,gr(1,6)-gr(2,6)); gw(2,7,gr(3,6)); gw(3,7,gr(4,6)); sp(); goto _73; _193: gw(7,7,0); gw(1,7,gr(1,6)); gw(2,7,gr(2,6)); gw(3,7,gr(4,6)+gr(3,6)); sp(); goto _73; _194: gw(7,7,0); gw(1,7,gr(1,6)); gw(2,7,gr(3,6)); gw(3,7,gr(4,6)+gr(2,6)); sp(); goto _73; _195: gw(7,7,0); gw(1,7,gr(3,6)); gw(2,7,gr(2,6)); gw(3,7,gr(4,6)+gr(1,6)); sp(); goto _73; _196: gw(7,7,0); gw(1,7,gr(1,6)); gw(2,7,gr(2,6)); gw(3,7,gr(3,6)+gr(4,6)); sp(); goto _73; _197: gw(7,7,0); gw(1,7,gr(1,6)); gw(2,7,gr(4,6)); gw(3,7,gr(3,6)+gr(2,6)); sp(); goto _73; _198: gw(7,7,0); gw(1,7,gr(4,6)); gw(2,7,gr(2,6)); gw(3,7,gr(3,6)+gr(1,6)); sp(); goto _73; _199: gw(7,7,0); gw(1,7,gr(1,6)); gw(2,7,gr(2,6)+gr(4,6)); gw(3,7,gr(3,6)); sp(); goto _73; _200: gw(7,7,0); gw(1,7,gr(1,6)); gw(2,7,gr(2,6)+gr(3,6)); gw(3,7,gr(4,6)); sp(); goto _73; _201: gw(7,7,0); gw(1,7,gr(4,6)); gw(2,7,gr(2,6)+gr(1,6)); gw(3,7,gr(3,6)); sp(); goto _73; _202: gw(7,7,0); gw(1,7,gr(1,6)+gr(4,6)); gw(2,7,gr(2,6)); gw(3,7,gr(3,6)); sp(); goto _73; _203: gw(7,7,0); gw(1,7,gr(1,6)+gr(3,6)); gw(2,7,gr(2,6)); gw(3,7,gr(4,6)); sp(); goto _73; _204: gw(7,7,0); gw(1,7,gr(1,6)+gr(2,6)); gw(2,7,gr(3,6)); gw(3,7,gr(4,6)); sp(); goto _73; _205: sa(sp()-1L); sa(sr()); sa(32); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa((sr()%100)+9); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(sp()/100L); {long v0=sp();long v1=sp();gw(v1,v0,sp());} sa(sr()); goto _1; } }
using System; using System.Collections.Generic; using System.Diagnostics; namespace YAF.Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using ByteRunAutomaton = YAF.Lucene.Net.Util.Automaton.ByteRunAutomaton; using BytesRef = YAF.Lucene.Net.Util.BytesRef; using CompiledAutomaton = YAF.Lucene.Net.Util.Automaton.CompiledAutomaton; using Int32sRef = YAF.Lucene.Net.Util.Int32sRef; using StringHelper = YAF.Lucene.Net.Util.StringHelper; using Transition = YAF.Lucene.Net.Util.Automaton.Transition; /// <summary> /// A <see cref="FilteredTermsEnum"/> that enumerates terms based upon what is accepted by a /// DFA. /// <para/> /// The algorithm is such: /// <list type="number"> /// <item><description>As long as matches are successful, keep reading sequentially.</description></item> /// <item><description>When a match fails, skip to the next string in lexicographic order that /// does not enter a reject state.</description></item> /// </list> /// <para> /// The algorithm does not attempt to actually skip to the next string that is /// completely accepted. this is not possible when the language accepted by the /// FSM is not finite (i.e. * operator). /// </para> /// @lucene.experimental /// </summary> internal class AutomatonTermsEnum : FilteredTermsEnum { // a tableized array-based form of the DFA private readonly ByteRunAutomaton runAutomaton; // common suffix of the automaton private readonly BytesRef commonSuffixRef; // true if the automaton accepts a finite language private readonly bool? finite; // array of sorted transitions for each state, indexed by state number private readonly Transition[][] allTransitions; // for path tracking: each long records gen when we last // visited the state; we use gens to avoid having to clear private readonly long[] visited; private long curGen; // the reference used for seeking forwards through the term dictionary private readonly BytesRef seekBytesRef = new BytesRef(10); // true if we are enumerating an infinite portion of the DFA. // in this case it is faster to drive the query based on the terms dictionary. // when this is true, linearUpperBound indicate the end of range // of terms where we should simply do sequential reads instead. private bool linear = false; private readonly BytesRef linearUpperBound = new BytesRef(10); private readonly IComparer<BytesRef> termComp; /// <summary> /// Construct an enumerator based upon an automaton, enumerating the specified /// field, working on a supplied <see cref="TermsEnum"/> /// <para/> /// @lucene.experimental /// </summary> /// <param name="tenum"> TermsEnum </param> /// <param name="compiled"> CompiledAutomaton </param> public AutomatonTermsEnum(TermsEnum tenum, CompiledAutomaton compiled) : base(tenum) { this.finite = compiled.Finite; this.runAutomaton = compiled.RunAutomaton; Debug.Assert(this.runAutomaton != null); this.commonSuffixRef = compiled.CommonSuffixRef; this.allTransitions = compiled.SortedTransitions; // used for path tracking, where each bit is a numbered state. visited = new long[runAutomaton.Count]; termComp = Comparer; } /// <summary> /// Returns <c>true</c> if the term matches the automaton. Also stashes away the term /// to assist with smart enumeration. /// </summary> protected override AcceptStatus Accept(BytesRef term) { if (commonSuffixRef == null || StringHelper.EndsWith(term, commonSuffixRef)) { if (runAutomaton.Run(term.Bytes, term.Offset, term.Length)) { return linear ? AcceptStatus.YES : AcceptStatus.YES_AND_SEEK; } else { return (linear && termComp.Compare(term, linearUpperBound) < 0) ? AcceptStatus.NO : AcceptStatus.NO_AND_SEEK; } } else { return (linear && termComp.Compare(term, linearUpperBound) < 0) ? AcceptStatus.NO : AcceptStatus.NO_AND_SEEK; } } protected override BytesRef NextSeekTerm(BytesRef term) { //System.out.println("ATE.nextSeekTerm term=" + term); if (term == null) { Debug.Assert(seekBytesRef.Length == 0); // return the empty term, as its valid if (runAutomaton.IsAccept(runAutomaton.InitialState)) { return seekBytesRef; } } else { seekBytesRef.CopyBytes(term); } // seek to the next possible string; if (NextString()) { return seekBytesRef; // reposition } else { return null; // no more possible strings can match } } /// <summary> /// Sets the enum to operate in linear fashion, as we have found /// a looping transition at position: we set an upper bound and /// act like a <see cref="Search.TermRangeQuery"/> for this portion of the term space. /// </summary> private void SetLinear(int position) { Debug.Assert(linear == false); int state = runAutomaton.InitialState; int maxInterval = 0xff; for (int i = 0; i < position; i++) { state = runAutomaton.Step(state, seekBytesRef.Bytes[i] & 0xff); Debug.Assert(state >= 0, "state=" + state); } for (int i = 0; i < allTransitions[state].Length; i++) { Transition t = allTransitions[state][i]; if (t.Min <= (seekBytesRef.Bytes[position] & 0xff) && (seekBytesRef.Bytes[position] & 0xff) <= t.Max) { maxInterval = t.Max; break; } } // 0xff terms don't get the optimization... not worth the trouble. if (maxInterval != 0xff) { maxInterval++; } int length = position + 1; // value + maxTransition if (linearUpperBound.Bytes.Length < length) { linearUpperBound.Bytes = new byte[length]; } Array.Copy(seekBytesRef.Bytes, 0, linearUpperBound.Bytes, 0, position); linearUpperBound.Bytes[position] = (byte)maxInterval; linearUpperBound.Length = length; linear = true; } private readonly Int32sRef savedStates = new Int32sRef(10); /// <summary> /// Increments the byte buffer to the next string in binary order after s that will not put /// the machine into a reject state. If such a string does not exist, returns /// <c>false</c>. /// <para/> /// The correctness of this method depends upon the automaton being deterministic, /// and having no transitions to dead states. /// </summary> /// <returns> <c>true</c> if more possible solutions exist for the DFA </returns> private bool NextString() { int state; int pos = 0; savedStates.Grow(seekBytesRef.Length + 1); int[] states = savedStates.Int32s; states[0] = runAutomaton.InitialState; while (true) { curGen++; linear = false; // walk the automaton until a character is rejected. for (state = states[pos]; pos < seekBytesRef.Length; pos++) { visited[state] = curGen; int nextState = runAutomaton.Step(state, seekBytesRef.Bytes[pos] & 0xff); if (nextState == -1) { break; } states[pos + 1] = nextState; // we found a loop, record it for faster enumeration if ((finite == false) && !linear && visited[nextState] == curGen) { SetLinear(pos); } state = nextState; } // take the useful portion, and the last non-reject state, and attempt to // append characters that will match. if (NextString(state, pos)) { return true; } // no more solutions exist from this useful portion, backtrack else { if ((pos = Backtrack(pos)) < 0) // no more solutions at all { return false; } int newState = runAutomaton.Step(states[pos], seekBytesRef.Bytes[pos] & 0xff); if (newState >= 0 && runAutomaton.IsAccept(newState)) /* String is good to go as-is */ { return true; } /* else advance further */ // TODO: paranoia? if we backtrack thru an infinite DFA, the loop detection is important! // for now, restart from scratch for all infinite DFAs if (finite == false) { pos = 0; } } } } /// <summary> /// Returns the next string in lexicographic order that will not put /// the machine into a reject state. /// <para/> /// This method traverses the DFA from the given position in the string, /// starting at the given state. /// <para/> /// If this cannot satisfy the machine, returns <c>false</c>. This method will /// walk the minimal path, in lexicographic order, as long as possible. /// <para/> /// If this method returns <c>false</c>, then there might still be more solutions, /// it is necessary to backtrack to find out. /// </summary> /// <param name="state"> current non-reject state </param> /// <param name="position"> useful portion of the string </param> /// <returns> <c>true</c> if more possible solutions exist for the DFA from this /// position </returns> private bool NextString(int state, int position) { /* * the next lexicographic character must be greater than the existing * character, if it exists. */ int c = 0; if (position < seekBytesRef.Length) { c = seekBytesRef.Bytes[position] & 0xff; // if the next byte is 0xff and is not part of the useful portion, // then by definition it puts us in a reject state, and therefore this // path is dead. there cannot be any higher transitions. backtrack. if (c++ == 0xff) { return false; } } seekBytesRef.Length = position; visited[state] = curGen; Transition[] transitions = allTransitions[state]; // find the minimal path (lexicographic order) that is >= c for (int i = 0; i < transitions.Length; i++) { Transition transition = transitions[i]; if (transition.Max >= c) { int nextChar = Math.Max(c, transition.Min); // append either the next sequential char, or the minimum transition seekBytesRef.Grow(seekBytesRef.Length + 1); seekBytesRef.Length++; seekBytesRef.Bytes[seekBytesRef.Length - 1] = (byte)nextChar; state = transition.Dest.Number; /* * as long as is possible, continue down the minimal path in * lexicographic order. if a loop or accept state is encountered, stop. */ while (visited[state] != curGen && !runAutomaton.IsAccept(state)) { visited[state] = curGen; /* * Note: we work with a DFA with no transitions to dead states. * so the below is ok, if it is not an accept state, * then there MUST be at least one transition. */ transition = allTransitions[state][0]; state = transition.Dest.Number; // append the minimum transition seekBytesRef.Grow(seekBytesRef.Length + 1); seekBytesRef.Length++; seekBytesRef.Bytes[seekBytesRef.Length - 1] = (byte)transition.Min; // we found a loop, record it for faster enumeration if ((finite == false) && !linear && visited[state] == curGen) { SetLinear(seekBytesRef.Length - 1); } } return true; } } return false; } /// <summary> /// Attempts to backtrack thru the string after encountering a dead end /// at some given position. Returns <c>false</c> if no more possible strings /// can match. /// </summary> /// <param name="position"> current position in the input string </param> /// <returns> position &gt;=0 if more possible solutions exist for the DFA </returns> private int Backtrack(int position) { while (position-- > 0) { int nextChar = seekBytesRef.Bytes[position] & 0xff; // if a character is 0xff its a dead-end too, // because there is no higher character in binary sort order. if (nextChar++ != 0xff) { seekBytesRef.Bytes[position] = (byte)nextChar; seekBytesRef.Length = position + 1; return position; } } return -1; // all solutions exhausted } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** Purpose: Unsafe code that uses pointers should use ** SafePointer to fix subtle lifetime problems with the ** underlying resource. ** ===========================================================*/ // Design points: // *) Avoid handle-recycling problems (including ones triggered via // resurrection attacks) for all accesses via pointers. This requires tying // together the lifetime of the unmanaged resource with the code that reads // from that resource, in a package that uses synchronization to enforce // the correct semantics during finalization. We're using SafeHandle's // ref count as a gate on whether the pointer can be dereferenced because that // controls the lifetime of the resource. // // *) Keep the penalties for using this class small, both in terms of space // and time. Having multiple threads reading from a memory mapped file // will already require 2 additional interlocked operations. If we add in // a "current position" concept, that requires additional space in memory and // synchronization. Since the position in memory is often (but not always) // something that can be stored on the stack, we can save some memory by // excluding it from this object. However, avoiding the need for // synchronization is a more significant win. This design allows multiple // threads to read and write memory simultaneously without locks (as long as // you don't write to a region of memory that overlaps with what another // thread is accessing). // // *) Space-wise, we use the following memory, including SafeHandle's fields: // Object Header MT* handle int bool bool <2 pad bytes> length // On 32 bit platforms: 24 bytes. On 64 bit platforms: 40 bytes. // (We can safe 4 bytes on x86 only by shrinking SafeHandle) // // *) Wrapping a SafeHandle would have been a nice solution, but without an // ordering between critical finalizable objects, it would have required // changes to each SafeHandle subclass to opt in to being usable from a // SafeBuffer (or some clever exposure of SafeHandle's state fields and a // way of forcing ReleaseHandle to run even after the SafeHandle has been // finalized with a ref count > 1). We can use less memory and create fewer // objects by simply inserting a SafeBuffer into the class hierarchy. // // *) In an ideal world, we could get marshaling support for SafeBuffer that // would allow us to annotate a P/Invoke declaration, saying this parameter // specifies the length of the buffer, and the units of that length are X. // P/Invoke would then pass that size parameter to SafeBuffer. // [DllImport(...)] // static extern SafeMemoryHandle AllocCharBuffer(int numChars); // If we could put an attribute on the SafeMemoryHandle saying numChars is // the element length, and it must be multiplied by 2 to get to the byte // length, we can simplify the usage model for SafeBuffer. // // *) This class could benefit from a constraint saying T is a value type // containing no GC references. // Implementation notes: // *) The Initialize method must be called before you use any instance of // a SafeBuffer. To avoid races when storing SafeBuffers in statics, // you either need to take a lock when publishing the SafeBuffer, or you // need to create a local, initialize the SafeBuffer, then assign to the // static variable (perhaps using Interlocked.CompareExchange). Of course, // assignments in a static class constructor are under a lock implicitly. using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using Microsoft.Win32.SafeHandles; namespace System.Runtime.InteropServices { public abstract unsafe class SafeBuffer : SafeHandleZeroOrMinusOneIsInvalid { // Steal UIntPtr.MaxValue as our uninitialized value. private static readonly UIntPtr Uninitialized = (UIntPtr.Size == 4) ? ((UIntPtr)UInt32.MaxValue) : ((UIntPtr)UInt64.MaxValue); private UIntPtr _numBytes; protected SafeBuffer(bool ownsHandle) : base(ownsHandle) { _numBytes = Uninitialized; } // On the desktop CLR, SafeBuffer has access to the internal handle field since they're both in // mscorlib. For this refactoring, we'll keep the name the same to minimize deltas, but shim // through to DangerousGetHandle private new IntPtr handle { get { return DangerousGetHandle(); } } public override bool IsInvalid { get { return DangerousGetHandle() == IntPtr.Zero || DangerousGetHandle() == new IntPtr(-1); } } /// <summary> /// Specifies the size of the region of memory, in bytes. Must be /// called before using the SafeBuffer. /// </summary> /// <param name="numBytes">Number of valid bytes in memory.</param> [CLSCompliant(false)] public void Initialize(ulong numBytes) { if (numBytes < 0) throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_NeedNonNegNum); if (IntPtr.Size == 4 && numBytes > UInt32.MaxValue) throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_AddressSpace); if (numBytes >= (ulong)Uninitialized) throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_UIntPtrMaxMinusOne); _numBytes = (UIntPtr)numBytes; } /// <summary> /// Specifies the the size of the region in memory, as the number of /// elements in an array. Must be called before using the SafeBuffer. /// </summary> [CLSCompliant(false)] public void Initialize(uint numElements, uint sizeOfEachElement) { if (numElements < 0) throw new ArgumentOutOfRangeException(nameof(numElements), SR.ArgumentOutOfRange_NeedNonNegNum); if (sizeOfEachElement < 0) throw new ArgumentOutOfRangeException(nameof(sizeOfEachElement), SR.ArgumentOutOfRange_NeedNonNegNum); if (IntPtr.Size == 4 && numElements * sizeOfEachElement > UInt32.MaxValue) throw new ArgumentOutOfRangeException("numBytes", SR.ArgumentOutOfRange_AddressSpace); if (numElements * sizeOfEachElement >= (ulong)Uninitialized) throw new ArgumentOutOfRangeException(nameof(numElements), SR.ArgumentOutOfRange_UIntPtrMaxMinusOne); _numBytes = checked((UIntPtr)(numElements * sizeOfEachElement)); } /// <summary> /// Specifies the the size of the region in memory, as the number of /// elements in an array. Must be called before using the SafeBuffer. /// </summary> [CLSCompliant(false)] public void Initialize<T>(uint numElements) where T : struct { Initialize(numElements, AlignedSizeOf<T>()); } // Callers should ensure that they check whether the pointer ref param // is null when AcquirePointer returns. If it is not null, they must // call ReleasePointer in a CER. This method calls DangerousAddRef // & exposes the pointer. Unlike Read, it does not alter the "current // position" of the pointer. Here's how to use it: // // byte* pointer = null; // RuntimeHelpers.PrepareConstrainedRegions(); // try { // safeBuffer.AcquirePointer(ref pointer); // // Use pointer here, with your own bounds checking // } // finally { // if (pointer != null) // safeBuffer.ReleasePointer(); // } // // Note: If you cast this byte* to a T*, you have to worry about // whether your pointer is aligned. Additionally, you must take // responsibility for all bounds checking with this pointer. /// <summary> /// Obtain the pointer from a SafeBuffer for a block of code, /// with the express responsibility for bounds checking and calling /// ReleasePointer later within a CER to ensure the pointer can be /// freed later. This method either completes successfully or /// throws an exception and returns with pointer set to null. /// </summary> /// <param name="pointer">A byte*, passed by reference, to receive /// the pointer from within the SafeBuffer. You must set /// pointer to null before calling this method.</param> [CLSCompliant(false)] public void AcquirePointer(ref byte* pointer) { if (_numBytes == Uninitialized) throw NotInitialized(); pointer = null; try { } finally { bool junk = false; DangerousAddRef(ref junk); pointer = (byte*)handle; } } public void ReleasePointer() { if (_numBytes == Uninitialized) throw NotInitialized(); DangerousRelease(); } /// <summary> /// Read a value type from memory at the given offset. This is /// equivalent to: return *(T*)(bytePtr + byteOffset); /// </summary> /// <typeparam name="T">The value type to read</typeparam> /// <param name="byteOffset">Where to start reading from memory. You /// may have to consider alignment.</param> /// <returns>An instance of T read from memory.</returns> [CLSCompliant(false)] public T Read<T>(ulong byteOffset) where T : struct { if (_numBytes == Uninitialized) throw NotInitialized(); uint sizeofT = SizeOf<T>(); byte* ptr = (byte*)handle + byteOffset; SpaceCheck(ptr, sizeofT); // return *(T*) (_ptr + byteOffset); T value = default(T); bool mustCallRelease = false; try { DangerousAddRef(ref mustCallRelease); fixed (byte* pStructure = &Unsafe.As<T, byte>(ref value)) Buffer.Memmove(pStructure, ptr, sizeofT); } finally { if (mustCallRelease) DangerousRelease(); } return value; } [CLSCompliant(false)] public void ReadArray<T>(ulong byteOffset, T[] array, int index, int count) where T : struct { if (array == null) throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Buffer); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); if (_numBytes == Uninitialized) throw NotInitialized(); uint sizeofT = SizeOf<T>(); uint alignedSizeofT = AlignedSizeOf<T>(); byte* ptr = (byte*)handle + byteOffset; SpaceCheck(ptr, checked((ulong)(alignedSizeofT * count))); bool mustCallRelease = false; try { DangerousAddRef(ref mustCallRelease); if (count > 0) { unsafe { fixed (byte* pStructure = &Unsafe.As<T, byte>(ref array[index])) { for (int i = 0; i < count; i++) Buffer.Memmove(pStructure + sizeofT * i, ptr + alignedSizeofT * i, sizeofT); } } } } finally { if (mustCallRelease) DangerousRelease(); } } /// <summary> /// Write a value type to memory at the given offset. This is /// equivalent to: *(T*)(bytePtr + byteOffset) = value; /// </summary> /// <typeparam name="T">The type of the value type to write to memory.</typeparam> /// <param name="byteOffset">The location in memory to write to. You /// may have to consider alignment.</param> /// <param name="value">The value type to write to memory.</param> [CLSCompliant(false)] public void Write<T>(ulong byteOffset, T value) where T : struct { if (_numBytes == Uninitialized) throw NotInitialized(); uint sizeofT = SizeOf<T>(); byte* ptr = (byte*)handle + byteOffset; SpaceCheck(ptr, sizeofT); // *((T*) (_ptr + byteOffset)) = value; bool mustCallRelease = false; try { DangerousAddRef(ref mustCallRelease); fixed (byte* pStructure = &Unsafe.As<T, byte>(ref value)) Buffer.Memmove(ptr, pStructure, sizeofT); } finally { if (mustCallRelease) DangerousRelease(); } } [CLSCompliant(false)] public void WriteArray<T>(ulong byteOffset, T[] array, int index, int count) where T : struct { if (array == null) throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Buffer); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); if (_numBytes == Uninitialized) throw NotInitialized(); uint sizeofT = SizeOf<T>(); uint alignedSizeofT = AlignedSizeOf<T>(); byte* ptr = (byte*)handle + byteOffset; SpaceCheck(ptr, checked((ulong)(alignedSizeofT * count))); bool mustCallRelease = false; try { DangerousAddRef(ref mustCallRelease); if (count > 0) { unsafe { fixed (byte* pStructure = &Unsafe.As<T, byte>(ref array[index])) { for (int i = 0; i < count; i++) Buffer.Memmove(ptr + alignedSizeofT * i, pStructure + sizeofT * i, sizeofT); } } } } finally { if (mustCallRelease) DangerousRelease(); } } /// <summary> /// Returns the number of bytes in the memory region. /// </summary> [CLSCompliant(false)] public ulong ByteLength { get { if (_numBytes == Uninitialized) throw NotInitialized(); return (ulong)_numBytes; } } /* No indexer. The perf would be misleadingly bad. People should use * AcquirePointer and ReleasePointer instead. */ private void SpaceCheck(byte* ptr, ulong sizeInBytes) { if ((ulong)_numBytes < sizeInBytes) NotEnoughRoom(); if ((ulong)(ptr - (byte*)handle) > ((ulong)_numBytes) - sizeInBytes) NotEnoughRoom(); } private static void NotEnoughRoom() { throw new ArgumentException(SR.Arg_BufferTooSmall); } private static InvalidOperationException NotInitialized() { Debug.Assert(false, "Uninitialized SafeBuffer! Someone needs to call Initialize before using this instance!"); return new InvalidOperationException(SR.InvalidOperation_MustCallInitialize); } #region "SizeOf Helpers" /// <summary> /// Returns the size that SafeBuffer (and hence, UnmanagedMemoryAccessor) reserves in the unmanaged buffer for each element of an array of T. This is not the same /// value that sizeof(T) returns! Since the primary use case is to parse memory mapped files, we cannot change this algorithm as this defines a de-facto serialization format. /// Throws if T is not blittable. /// </summary> internal static uint AlignedSizeOf<T>() where T : struct { uint size = SizeOf<T>(); if (size == 1 || size == 2) { return size; } return (uint)(((size + 3) & (~3))); } /// <summary> /// Returns same value as sizeof(T) but throws if T is not blittable. /// </summary> internal static uint SizeOf<T>() where T : struct { RuntimeTypeHandle structureTypeHandle = typeof(T).TypeHandle; if (!structureTypeHandle.IsBlittable()) throw new ArgumentException(SR.Argument_NeedStructWithNoRefs); return (uint)Unsafe.SizeOf<T>(); } #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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // AsyncWork.cs // // Helper class that is used to test the FromAsync method. These classes hold the APM patterns // and is used by the TaskFromAsyncTest.cs file // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; using System.Threading.Tasks; namespace System.Threading.Tasks.Tests { #region AsyncWork (base) /// <summary> /// The abstract that defines the work done by the Async method /// </summary> public abstract class AsyncWork { /// <summary> /// Defines the amount of time the thread should sleep (to simulate workload) /// </summary> private const int DEFAULT_TIME = 1000; // 1s private List<object> _inputs; public AsyncWork() { _inputs = new List<object>(); } protected void AddInput(object o) { _inputs.Add(o); } protected void InvokeAction(bool throwing) { // // simulate some dummy workload // var task = Task.Delay(DEFAULT_TIME); task.Wait(); if (throwing) //simulates error condition during the execution of user delegate { throw new TPLTestException(); } } protected ReadOnlyCollection<object> InvokeFunc(bool throwing) { // // simulate some dummy workload // var task = Task.Delay(DEFAULT_TIME); task.Wait(); if (throwing) { throw new TPLTestException(); } return Inputs; } protected void CheckState(object o) { ObservedState = o; ObservedTaskScheduler = TaskScheduler.Current; } public ReadOnlyCollection<object> Inputs { get { return new ReadOnlyCollection<object>(_inputs); } } public object ObservedState { get; private set; } public object ObservedTaskScheduler { get; private set; } } #endregion #region AsyncAction /// <summary> /// Extends the base class to implement that action form of APM /// </summary> public class AsyncAction : AsyncWork { private Action _action; // a general action to take-in inputs upfront rather than delayed until BeginInvoke // for testing the overload taking IAsyncResult public AsyncAction(object[] inputs, bool throwing) : base() { _action = () => { foreach (object o in inputs) { AddInput(o); } InvokeAction(throwing); }; } public AsyncAction(bool throwing) : base() { _action = () => { InvokeAction(throwing); }; } #region APM public IAsyncResult BeginInvoke(AsyncCallback cb, object state) { return _action.BeginInvoke(cb, state); } public void EndInvoke(IAsyncResult iar) { CheckState(iar.AsyncState); _action.EndInvoke(iar); } #endregion } /// <summary> /// Extends the base class to implement that action form of APM with one parameter /// </summary> public class AsyncAction<T> : AsyncWork { public delegate void Action<TArg>(TArg obj); private Action<T> _action; public AsyncAction(bool throwing) : base() { _action = (o) => { AddInput(o); InvokeAction(throwing); }; } #region APM public IAsyncResult BeginInvoke(T t, AsyncCallback cb, object state) { return _action.BeginInvoke(t, cb, state); } public void EndInvoke(IAsyncResult iar) { CheckState(iar.AsyncState); _action.EndInvoke(iar); } #endregion } /// <summary> /// Extends the base class to implement that action form of APM with two parameters /// </summary> public class AsyncAction<T1, T2> : AsyncWork { private Action<T1, T2> _action; public AsyncAction(bool throwing) : base() { _action = (o1, o2) => { AddInput(o1); AddInput(o2); InvokeAction(throwing); }; } #region APM public IAsyncResult BeginInvoke(T1 t1, T2 t2, AsyncCallback cb, object state) { return _action.BeginInvoke(t1, t2, cb, state); } public void EndInvoke(IAsyncResult iar) { CheckState(iar.AsyncState); _action.EndInvoke(iar); } #endregion } /// <summary> /// Extends the base class to implement that action form of APM with three parameters /// </summary> public class AsyncAction<T1, T2, T3> : AsyncWork { private Action<T1, T2, T3> _action; public AsyncAction(bool throwing) : base() { _action = (o1, o2, o3) => { AddInput(o1); AddInput(o2); AddInput(o3); InvokeAction(throwing); }; } #region APM public IAsyncResult BeginInvoke(T1 t1, T2 t2, T3 t3, AsyncCallback cb, object state) { return _action.BeginInvoke(t1, t2, t3, cb, state); } public void EndInvoke(IAsyncResult iar) { CheckState(iar.AsyncState); _action.EndInvoke(iar); } #endregion } #endregion #region AsyncFunc /// <summary> /// Extends the base class to implement that function form of APM /// </summary> public class AsyncFunc : AsyncWork { private Func<ReadOnlyCollection<object>> _func; // a general func to take-in inputs upfront rather than delayed until BeginInvoke // for testing the overload taking IAsyncResult public AsyncFunc(object[] inputs, bool throwing) : base() { _func = () => { foreach (object o in inputs) { AddInput(o); } return InvokeFunc(throwing); }; } public AsyncFunc(bool throwing) : base() { _func = () => { return InvokeFunc(throwing); }; } #region APM public IAsyncResult BeginInvoke(AsyncCallback cb, object state) { return _func.BeginInvoke(cb, state); } public ReadOnlyCollection<object> EndInvoke(IAsyncResult iar) { CheckState(iar.AsyncState); return _func.EndInvoke(iar); } #endregion } /// <summary> /// Extends the base class to implement that function form of APM with one parameter /// </summary> public class AsyncFunc<T> : AsyncWork { private Func<T, ReadOnlyCollection<object>> _func; public AsyncFunc(bool throwing) : base() { _func = (o) => { AddInput(o); return InvokeFunc(throwing); }; } #region APM public IAsyncResult BeginInvoke(T t, AsyncCallback cb, object state) { return _func.BeginInvoke(t, cb, state); } public ReadOnlyCollection<object> EndInvoke(IAsyncResult iar) { CheckState(iar.AsyncState); return _func.EndInvoke(iar); } #endregion } /// <summary> /// Extends the base class to implement that function form of APM with two parameters /// </summary> public class AsyncFunc<T1, T2> : AsyncWork { private Func<T1, T2, ReadOnlyCollection<object>> _func; public AsyncFunc(bool throwing) : base() { _func = (o1, o2) => { AddInput(o1); AddInput(o2); return InvokeFunc(throwing); }; } #region APM public IAsyncResult BeginInvoke(T1 t1, T2 t2, AsyncCallback cb, object state) { return _func.BeginInvoke(t1, t2, cb, state); } public ReadOnlyCollection<object> EndInvoke(IAsyncResult iar) { CheckState(iar.AsyncState); return _func.EndInvoke(iar); } #endregion } /// <summary> /// Extends the base class to implement that function form of APM with three parameters /// </summary> public class AsyncFunc<T1, T2, T3> : AsyncWork { private Func<T1, T2, T3, ReadOnlyCollection<object>> _func; public AsyncFunc(bool throwing) : base() { _func = (o1, o2, o3) => { AddInput(o1); AddInput(o2); AddInput(o3); return InvokeFunc(throwing); }; } #region APM public IAsyncResult BeginInvoke(T1 t1, T2 t2, T3 t3, AsyncCallback cb, object state) { return _func.BeginInvoke(t1, t2, t3, cb, state); } public ReadOnlyCollection<object> EndInvoke(IAsyncResult iar) { CheckState(iar.AsyncState); return _func.EndInvoke(iar); } #endregion } #endregion }
using System; using System.Collections; using System.ComponentModel; using System.Security; using System.Security.Permissions; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Umbraco.Core.Models; using umbraco.BusinessLogic.Actions; using umbraco.presentation.LiveEditing.Modules.ItemEditing; namespace umbraco.presentation.templateControls { /// <summary> /// Control that renders an Umbraco item on a page. /// </summary> [DefaultProperty("Field")] [ToolboxData("<{0}:Item runat=\"server\"></{0}:Item>")] [Designer("umbraco.presentation.templateControls.ItemDesigner, umbraco")] public class Item : CompositeControl { #region Private Fields /// <summary>The item's unique ID on the page.</summary> private readonly int m_ItemId; public AttributeCollectionAdapter LegacyAttributes; #endregion /// <summary> /// Used by the UmbracoHelper to assign an IPublishedContent to the Item which allows us to pass this in /// to the 'item' ctor so that it renders with the new API instead of the old one. /// </summary> internal IPublishedContent ContentItem { get; private set; } #region Public Control Properties /// <summary> /// Gets or sets the field name. /// </summary> /// <value>The field name.</value> [Bindable(true)] [Category("Umbraco")] [DefaultValue("")] [Localizable(true)] public string Field { get { return (string)ViewState["Field"] ?? String.Empty; } set { ViewState["Field"] = value; } } /// <summary> /// Gets or sets the node id expression. /// </summary> /// <value>The node id expression.</value> [Bindable(true)] [Category("Umbraco")] [DefaultValue("")] [Localizable(true)] public string NodeId { get { return (string)ViewState["NodeId"] ?? String.Empty; } set { ViewState["NodeId"] = value; } } /// <summary> /// Gets or sets the text to display if the control is empty. /// </summary> /// <value>The text to display if the control is empty.</value> [Bindable(true)] [Category("Umbraco")] [DefaultValue("")] [Localizable(true)] public string TextIfEmpty { get { return (string)ViewState["TextIfEmpty"] ?? String.Empty; } set { ViewState["TextIfEmpty"] = value; } } /// <summary> /// Gets or sets the XPath expression used for the inline XSLT transformation. /// </summary> /// <value> /// The XPath expression, or an empty string to disable XSLT transformation. /// The code <c>{0}</c> is used as a placeholder for the rendered field contents. /// </value> [Bindable(true)] [Category("Umbraco")] [DefaultValue("")] [Localizable(true)] public string Xslt { get { return (string)ViewState["Xslt"] ?? String.Empty; } set { ViewState["Xslt"] = value; } } /// <summary> /// Gets or sets a value indicating whether XML entity escaping of the XSLT transformation output is disabled. /// </summary> /// <value><c>true</c> HTML escaping is disabled; otherwise, <c>false</c> (default).</value> /// <remarks> /// This corresponds value to the <c>disable-output-escaping</c> parameter /// of the XSLT <c>value-of</c> element. /// </remarks> [Bindable(true)] [Category("Umbraco")] [DefaultValue(false)] [Localizable(true)] public bool XsltDisableEscaping { get { return ViewState["XsltEscape"] == null ? false : (bool)ViewState["XsltEscape"]; } set { ViewState["XsltEscape"] = value; } } [Bindable(true)] [Category("Umbraco")] [DefaultValue("")] [Localizable(true)] public bool DebugMode { get { return ((ViewState["DebugMode"] == null) ? false : (bool)ViewState["DebugMode"]); } set { ViewState["DebugMode"] = value; } } /// <summary> /// Gets or sets a value indicating whether Live Editing is disabled for this field. /// </summary> /// <value><c>true</c> if you manually wish to disable Live Editing for this field; otherwise, <c>false</c> (default is false).</value> [Bindable(true)] [Category("Umbraco")] [DefaultValue("")] [Localizable(true)] public bool LiveEditingDisabled { get { return ((ViewState["LiveEditingDisabled"] == null) ? false : (bool)ViewState["LiveEditingDisabled"]); } set { ViewState["LiveEditingDisabled"] = value; } } public ItemRenderer Renderer { get; set; } #endregion #region Public Readonly Properties /// <summary> /// Gets the item's unique ID on the page. /// </summary> /// <value>The item id.</value> public int ItemId { get { return m_ItemId; } } /// <summary> /// Gets a value indicating whether this control can be used in Live Editing mode. /// Checks whether live editing has not been disabled, /// the control is inside a form tag, /// the field is editable /// and the user has sufficient permissions. /// </summary> /// <value><c>true</c> if live editing is useLiveEditing; otherwise, <c>false</c>.</value> public bool CanUseLiveEditing { get { return !LiveEditingDisabled && IsInsideFormTag() && FieldSupportsLiveEditing() && FieldEditableWithUserPermissions(); } } /// <summary> /// Gets the Umbraco page elements. /// </summary> /// <value>The Umbraco page elements.</value> public Hashtable PageElements { get { return Context.Items["pageElements"] as Hashtable; } } #endregion #region Public Constructors /// <summary> /// Initializes a new instance of the <see cref="Item"/> class. /// </summary> public Item() { // create page unique ID for this item object lastItemId = HttpContext.Current.Items["LiveEditing_LastItemId"]; m_ItemId = (lastItemId != null ? (int)lastItemId + 1 : 1); HttpContext.Current.Items["LiveEditing_LastItemId"] = m_ItemId; Renderer = !UmbracoContext.Current.LiveEditingContext.Enabled ? ItemRenderer.Instance : LiveEditingItemRenderer.Instance; } /// <summary> /// Internal ctor used to assign an IPublishedContent object. /// </summary> /// <param name="contentItem"></param> internal Item(IPublishedContent contentItem) :this() { ContentItem = contentItem; } #endregion #region Overriden Control Methods /// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Init"/> event. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param> protected override void OnInit(EventArgs e) { Attributes.Add("field", Field); LegacyAttributes = new AttributeCollectionAdapter(Attributes); Renderer.Init(this); base.OnInit(e); } /// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load"/> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs"/> object that contains the event data.</param> protected override void OnLoad(EventArgs e) { Renderer.Load(this); base.OnLoad(e); } /// <summary> /// Writes the <see cref="T:System.Web.UI.WebControls.CompositeControl"/> content /// to the specified <see cref="T:System.Web.UI.HtmlTextWriter"/> object, for display on the client. /// </summary> /// <param name="writer"> /// An <see cref="T:System.Web.UI.HtmlTextWriter"/> that represents /// the output stream to render HTML content on the client. /// </param> protected override void Render(HtmlTextWriter writer) { Renderer.Render(this, writer); } #endregion #region Helper Functions /// <summary> /// Gets the parsed node id. As a nodeid on a item element can be null, an integer or even a squarebracket syntax, this helper method /// is handy for getting the exact parsed nodeid back. /// </summary> /// <returns>The parsed nodeid, the id of the current page OR null if it's not specified</returns> public int? GetParsedNodeId() { if (!String.IsNullOrEmpty(NodeId)) { string tempNodeId = helper.parseAttribute(PageElements, NodeId); int nodeIdInt = 0; if (int.TryParse(tempNodeId, out nodeIdInt)) { return nodeIdInt; } } else if (PageElements["pageID"] != null) { return int.Parse(PageElements["pageID"].ToString()); } return null; } /// <summary> /// Gets a value indicating whether this control is inside the form tag. /// </summary> /// <returns><c>true</c> if this control is inside the form tag; otherwise, <c>false</c>.</returns> protected virtual bool IsInsideFormTag() { // check if this control has an ancestor that is the page form for (Control parent = this.Parent; parent != null; parent = parent.Parent) if (parent == Page.Form) return true; return false; } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override string ToString() { return String.Format("Item {0} (NodeId '{1}' : {2})", ItemId, NodeId, Field); } #endregion #region Field Information Functions // 27/08/2008 Ruben Verborgh: This functionality should really be inside some kind of super Field class, // which could be anything from a property to a dictionary item. // However, I don't think we should do this in the current Umbraco generation. /// <summary> /// Gets a value indicating whether Live Editing is useLiveEditing on this field. /// Certain functionalities of the item field makes it hard to /// support Live Editing, like dictionary items and recursive values. /// </summary> /// <value> /// <c>true</c> if Live Editing is useLiveEditing; otherwise, <c>false</c>. /// </value> protected virtual bool FieldSupportsLiveEditing() { return !(FieldIsRercursive() || FieldIsDictionaryItem()); } /// <summary> /// Determines whether the field is a dictionary item. /// </summary> /// <returns><c>true</c> if the field is a dictionary item; otherwise, <c>false</c>.</returns> protected virtual bool FieldIsDictionaryItem() { return helper.FindAttribute(new AttributeCollectionAdapter(Attributes), "field").StartsWith("#"); } /// <summary> /// Determines whether the field is recursive. /// </summary> /// <returns><c>true</c> if the field is recursive; otherwise, <c>false</c>.</returns> protected virtual bool FieldIsRercursive() { return helper.FindAttribute(new AttributeCollectionAdapter(Attributes), "recursive") == "true"; } /// <summary> /// Determines whether field uses the API to lookup the value /// (if a NodeId attribute is specified and is different from the current page id). /// </summary> /// <returns><c>true</c> if API lookup is used; otherwise, <c>false</c>.</returns> [Obsolete("Method never implemented", true)] protected virtual bool FieldIsApiLookup() { // TODO: remove false and add security return false; } /// <summary> /// Gets a value indicating whether the current item is editable by the current user. /// </summary> /// <value><c>true</c> if the current item is editable by the current user; otherwise, <c>false</c>.</value> protected virtual bool FieldEditableWithUserPermissions() { BusinessLogic.User u = helper.GetCurrentUmbracoUser(); return u != null && u.GetPermissions(PageElements["path"].ToString()).Contains(ActionUpdate.Instance.Letter.ToString()); } #endregion } public class ItemDesigner : System.Web.UI.Design.ControlDesigner { private Item m_control; public override string GetDesignTimeHtml() { m_control = this.Component as Item; return returnMarkup(String.Format("Getting '{0}'", m_control.Field)); } private string returnMarkup(string message) { return "<span style=\"background-color: #DDD; padding: 2px;\">" + message + "</span>"; } protected override string GetErrorDesignTimeHtml(Exception e) { if (this.Component != null) { m_control = this.Component as Item; } if (m_control != null && !String.IsNullOrEmpty(m_control.Field)) { return returnMarkup(String.Format("Getting '{0}'", m_control.Field)); } else { return returnMarkup("<em>Please add a Field property</em>"); } } } }
// ---------------------------------------------------------------------------- // XmlEquivalencyAssertionTestFixture.cs // // Contains the definition of the XmlEquivalencyAssertionTestFixture class. // Copyright 2009 Steve Guidi. // // File created: 6/19/2009 18:50:22 // ---------------------------------------------------------------------------- using System; using System.Xml; using System.Xml.Linq; using Jolt.Testing.Assertions; using Jolt.Testing.Properties; using NUnit.Framework; namespace Jolt.Testing.Test.Assertions { [TestFixture] public sealed class XmlEquivalencyAssertionTestFixture { #region constructors ---------------------------------------------------------------------- /// <summary> /// Initializes the static fields of the test fixture. /// </summary> static XmlEquivalencyAssertionTestFixture() { DefaultElementName = XName.Get("ElementName", "urn:document-namespace"); DefaultAttributes = new XAttribute[] { new XAttribute("attribute_3", 300), new XAttribute("attribute_1", 100), new XAttribute("attribute_2", 200) }; } #endregion #region public methods -------------------------------------------------------------------- /// <summary> /// Verifies the construction of the class; only the storage of a /// given XML comparison flags enumeration. /// </summary> [Test] public void Construction() { AssertionConstructionTests.XmlEquivalencyAssertion(flags => new XmlEquivalencyAssertion(flags)); } /// <summary> /// Verifies the behavior of the AreEquivalent() method, when given /// two XML elements that contain a different number of child elements, /// and the element order of a sequence is ignored. /// </summary> [Test] public void AreEquivalent_IgnoreSequenceOrder_ExcessElement() { XmlComparisonResult comparisonResult = new XmlEquivalencyAssertion(XmlComparisonFlags.IgnoreSequenceOrder) .AreEquivalent(GetEmbeddedXml("AssertionInput.xml"), GetEmbeddedXml("AssertionInput-AdditionalElement.xml")); Assert.That(!comparisonResult.Result); ValidateComparisonResultElement( comparisonResult.ExpectedElement, XName.Get("anotherElement", DefaultElementName.NamespaceName), XName.Get("root", DefaultElementName.NamespaceName)); ValidateComparisonResultElement( comparisonResult.ActualElement, XName.Get("element", DefaultElementName.NamespaceName), XName.Get("root", DefaultElementName.NamespaceName)); Assert.That(comparisonResult.Message, Is.EqualTo( String.Format(Resources.AssertionFailure_UnexpectedElement, "anotherElement", "element"))); Assert.That(comparisonResult.XPathHint, Is.EqualTo( String.Format("/{0}root/{0}element", "urn:document-namespace:"))); } /// <summary> /// Verifies the behavior of the AreEquivalent() method, when given /// two XML elements that contain a different number of descendant elements, /// and the element order of a sequence is ignored. /// </summary> [Test] public void AreEquivalent_IgnoreSequenceOrder_ExcessElementInDescendant() { XmlComparisonResult comparisonResult = new XmlEquivalencyAssertion(XmlComparisonFlags.IgnoreSequenceOrder) .AreEquivalent(GetEmbeddedXml("AssertionInput.xml"), GetEmbeddedXml("AssertionInput-AdditionalElementInDescendant.xml")); Assert.That(!comparisonResult.Result); ValidateComparisonResultElement( comparisonResult.ExpectedElement, XName.Get("yetAnotherElement", DefaultElementName.NamespaceName), XName.Get("grandChildElement", DefaultElementName.NamespaceName)); ValidateComparisonResultElement( comparisonResult.ActualElement, XName.Get("anotherElementAgain", DefaultElementName.NamespaceName), XName.Get("grandChildElement", DefaultElementName.NamespaceName)); Assert.That(comparisonResult.Message, Is.EqualTo( String.Format(Resources.AssertionFailure_UnexpectedElement, "yetAnotherElement", "anotherElementAgain"))); Assert.That(comparisonResult.XPathHint, Is.EqualTo( String.Format("/{0}root/{0}anotherElement/{0}childElement/{0}grandChildElement/{0}anotherElementAgain", "urn:document-namespace:"))); } /// <summary> /// Verifies the behavior of the AreEquivalent() method, when given /// two XML elements that contain a different number of child elements, /// and the element order of a sequence is ignored. /// </summary> [Test] public void AreEquivalent_IgnoreSequenceOrder_MismatchingNumberOfChildren() { XmlComparisonResult comparisonResult = new XmlEquivalencyAssertion(XmlComparisonFlags.IgnoreSequenceOrder) .AreEquivalent(GetEmbeddedXml("AssertionInput.xml"), GetEmbeddedXml("AssertionInput-MismatchingNumberOfChildren.xml")); Assert.That(!comparisonResult.Result); ValidateComparisonResultElement(comparisonResult.ExpectedElement, XName.Get("root", DefaultElementName.NamespaceName), null); ValidateComparisonResultElement(comparisonResult.ActualElement, XName.Get("root", DefaultElementName.NamespaceName), null); Assert.That(comparisonResult.Message, Is.EqualTo( String.Format(Resources.AssertionFailure_ChildElementQuantityMismatch, "root"))); Assert.That(comparisonResult.XPathHint, Is.EqualTo( String.Format("/{0}root", "urn:document-namespace:"))); } /// <summary> /// Verifies the behavior of the AreEquivalent() method, when given /// two XML elements that contain a different number of descendant elements, /// and the element order of a sequence is ignored. /// </summary> [Test] public void AreEquivalent_IgnoreSequenceOrder_MismatchingNumberOfChildrenInDescendant() { XmlComparisonResult comparisonResult = new XmlEquivalencyAssertion(XmlComparisonFlags.IgnoreSequenceOrder) .AreEquivalent(GetEmbeddedXml("AssertionInput.xml"), GetEmbeddedXml("AssertionInput-MismatchingNumberOfChildrenInDescendant.xml")); Assert.That(!comparisonResult.Result); ValidateComparisonResultElement( comparisonResult.ExpectedElement, XName.Get("anotherGrandChildElement", DefaultElementName.NamespaceName), XName.Get("childElement", DefaultElementName.NamespaceName)); ValidateComparisonResultElement( comparisonResult.ActualElement, XName.Get("anotherGrandChildElement", DefaultElementName.NamespaceName), XName.Get("childElement", DefaultElementName.NamespaceName)); Assert.That(comparisonResult.Message, Is.EqualTo( String.Format(Resources.AssertionFailure_ChildElementQuantityMismatch, "anotherGrandChildElement"))); Assert.That(comparisonResult.XPathHint, Is.EqualTo( String.Format("/{0}root/{0}anotherElement/{0}childElement/{0}anotherGrandChildElement", "urn:document-namespace:"))); } /// <summary> /// Verifies the behavior of the AreEquivalent() method, when given /// two XML elements that contain a different number of descendant elements, /// and the element order of a sequence is ignored. /// </summary> [Test] public void AreEquivalent_IgnoreSequenceOrder() { Assert.That(new XmlEquivalencyAssertion(XmlComparisonFlags.IgnoreSequenceOrder) .AreEquivalent(GetEmbeddedXml("AssertionInput.xml"), GetEmbeddedXml("AssertionInput-ElementSequenceTransformed.xml")) .Result); } /// <summary> /// Verifies the behavior of the AreEquivalent() method, when given /// two XML elements that contain similar elements in different namespaces, /// and the element namespaces are ignored. /// </summary> [Test] public void AreEquivalent_IgnoreElementNamespace() { Assert.That(new XmlEquivalencyAssertion(XmlComparisonFlags.IgnoreElementNamespaces) .AreEquivalent(GetEmbeddedXml("AssertionInput.xml"), GetEmbeddedXml("AssertionInput-ElementNamespaceTransformed.xml")) .Result); } /// <summary> /// Verifies the behavior of the AreEquivalent() method, when given /// two XML elements that contain similar attributes in different namespaces, /// and the attribute namespaces are ignored. /// </summary> [Test] public void AreEquivalent_IgnoreAttributeNamespace() { Assert.That(new XmlEquivalencyAssertion(XmlComparisonFlags.IgnoreAttributeNamespaces) .AreEquivalent(GetEmbeddedXml("AssertionInput.xml"), GetEmbeddedXml("AssertionInput-AttributeNamespaceTransformed.xml")) .Result); } /// <summary> /// Verifies the behavior of the AreEquivalent() method, when given /// two XML elements that contain the same set of attributes, but /// in different order. /// </summary> [Test] public void AreEquivalent_AttributeOrdering() { Assert.That(new XmlEquivalencyAssertion(XmlComparisonFlags.Strict) .AreEquivalent(GetEmbeddedXml("AssertionInput.xml"), GetEmbeddedXml("AssertionInput-AttributeOrderTransformed.xml")) .Result); } /// <summary> /// Verifies the behavior of the AreEquivalent() method, when given /// two XML elements that contain different attributes, and the /// attributes are ignored. /// </summary> [Test] public void AreEquivalent_IgnoreAttributes() { Assert.That(new XmlEquivalencyAssertion(XmlComparisonFlags.IgnoreAttributes) .AreEquivalent(GetEmbeddedXml("AssertionInput.xml"), GetEmbeddedXml("AssertionInput-AttributeTransformed.xml")) .Result); } /// <summary> /// Verifies the behavior of the AreEquivalent() method, when given /// two XML elements that contain element differing in values, /// and element values are ingored. /// </summary> [Test] public void AreEquivalent_IgnoreElementValues() { Assert.That(new XmlEquivalencyAssertion(XmlComparisonFlags.IgnoreElementValues) .AreEquivalent(GetEmbeddedXml("AssertionInput.xml"), GetEmbeddedXml("AssertionInput-ElementValueTransformed.xml")) .Result); } /// <summary> /// Verifies the strict behavior mode of the AreEquivalent() method, when given /// two XML elements that are equal to one another. /// </summary> [Test] public void AreEquivalent_Strict() { XElement expectedElement = new XElement(DefaultElementName, DefaultAttributes, new XElement(DefaultElementName), new XElement(DefaultElementName, 100, 200, DefaultAttributes, new XElement(DefaultElementName), 300)); Assert.That(new XmlEquivalencyAssertion(XmlComparisonFlags.Strict) .AreEquivalent(expectedElement.CreateReader(), expectedElement.CreateReader()) .Result); } /// <summary> /// Verifies the strict behavior mode of the AreEquivalent() method, when given /// two XML elements that differ in local name. /// </summary> [Test] public void AreEquivalent_Strict_LocalNameMismatch() { XElement expectedElement = new XElement(DefaultElementName); XElement actualElement = new XElement(XName.Get("DifferentElementName", DefaultElementName.NamespaceName)); XmlComparisonResult comparisonResult = new XmlEquivalencyAssertion(XmlComparisonFlags.Strict).AreEquivalent( expectedElement.CreateReader(), actualElement.CreateReader()); Assert.That(!comparisonResult.Result); ValidateComparisonResultElement(comparisonResult.ExpectedElement, DefaultElementName, null); ValidateComparisonResultElement( comparisonResult.ActualElement, XName.Get("DifferentElementName", DefaultElementName.NamespaceName), null); Assert.That(comparisonResult.Message, Is.EqualTo( String.Format(Resources.AssertionFailure_UnexpectedElement, DefaultElementName.LocalName, "DifferentElementName"))); Assert.That(comparisonResult.XPathHint, Is.EqualTo( String.Format("/{0}:{1}", DefaultElementName.NamespaceName, "DifferentElementName"))); } /// <summary> /// Verifies the strict behavior mode of the AreEquivalent() method, when given /// two XML elements that differ in namespace. /// </summary> [Test] public void AreEquivalent_Strict_NamespaceMismatch() { XName unexpectedElement = XName.Get(DefaultElementName.LocalName, "urn:different-namespace"); XmlComparisonResult comparisonResult = new XmlEquivalencyAssertion(XmlComparisonFlags.Strict).AreEquivalent( new XElement(DefaultElementName).CreateReader(), new XElement(unexpectedElement).CreateReader()); Assert.That(!comparisonResult.Result); ValidateComparisonResultElement(comparisonResult.ExpectedElement, DefaultElementName, null); ValidateComparisonResultElement(comparisonResult.ActualElement, unexpectedElement, null); Assert.That(comparisonResult.Message, Is.EqualTo(String.Format( Resources.AssertionFailure_ElementNamespaceMismatch, DefaultElementName.LocalName, DefaultElementName.NamespaceName, unexpectedElement.NamespaceName))); Assert.That(comparisonResult.XPathHint, Is.EqualTo( String.Format("/{0}:{1}", unexpectedElement.NamespaceName, unexpectedElement.LocalName))); } /// <summary> /// Verifies the strict behavior mode of the AreEquivalent() method, when given /// two XML elements that differ in value. /// </summary> [Test] public void AreEquivalent_Strict_ValueMismatch() { XElement expectedElement = new XElement(DefaultElementName, 100, 200, new XElement(DefaultElementName), 300); XElement actualElement = new XElement(DefaultElementName, 100, new XElement(DefaultElementName), 200, 400); XmlComparisonResult comparisonResult = new XmlEquivalencyAssertion(XmlComparisonFlags.Strict) .AreEquivalent(expectedElement.CreateReader(), actualElement.CreateReader()); Assert.That(!comparisonResult.Result); ValidateComparisonResultElement(comparisonResult.ExpectedElement, DefaultElementName, null); ValidateComparisonResultElement(comparisonResult.ActualElement, DefaultElementName, null); Assert.That(comparisonResult.ExpectedElement, Is.Not.SameAs(comparisonResult.ActualElement)); Assert.That(comparisonResult.Message, Is.EqualTo( String.Format(Resources.AssertionFailure_ElementValueMismatch, DefaultElementName.LocalName, "100200300", "100200400"))); Assert.That(comparisonResult.XPathHint, Is.EqualTo( String.Format("/{0}:{1}", DefaultElementName.NamespaceName, DefaultElementName.LocalName))); } /// <summary> /// Verifies the strict behavior mode of the AreEquivalent() method, when given /// two XML elements that differ in number of attributes. /// </summary> [Test] public void AreEquivalent_Strict_FewerAttributes() { XmlComparisonResult comparisonResult = new XmlEquivalencyAssertion(XmlComparisonFlags.Strict).AreEquivalent( new XElement(DefaultElementName, new XAttribute("attribute_1", 100)).CreateReader(), new XElement(DefaultElementName).CreateReader()); Assert.That(!comparisonResult.Result); ValidateComparisonResultElement(comparisonResult.ExpectedElement, DefaultElementName, null); ValidateComparisonResultElement(comparisonResult.ActualElement, DefaultElementName, null); Assert.That(comparisonResult.ExpectedElement, Is.Not.SameAs(comparisonResult.ActualElement)); Assert.That(comparisonResult.Message, Is.EqualTo( String.Format(Resources.AssertionFailure_AttributeQuantityMismatch, DefaultElementName.LocalName))); Assert.That(comparisonResult.XPathHint, Is.EqualTo( String.Format("/{0}:{1}", DefaultElementName.NamespaceName, DefaultElementName.LocalName))); } /// <summary> /// Verifies the strict behavior mode of the AreEquivalent() method, when given /// two XML elements that differ in number of attributes. /// </summary> [Test] public void AreEquivalent_Strict_FewerAttributesInDescendant() { XElement expectedElement = new XElement(DefaultElementName, new XElement(DefaultElementName, new XAttribute("attribute_1", 100))); XElement actualElement = new XElement(DefaultElementName, new XElement(DefaultElementName)); XmlComparisonResult comparisonResult = new XmlEquivalencyAssertion(XmlComparisonFlags.Strict) .AreEquivalent(expectedElement.CreateReader(), actualElement.CreateReader()); Assert.That(!comparisonResult.Result); ValidateComparisonResultElement(comparisonResult.ExpectedElement, DefaultElementName, DefaultElementName); ValidateComparisonResultElement(comparisonResult.ActualElement, DefaultElementName, DefaultElementName); Assert.That(comparisonResult.ExpectedElement, Is.Not.SameAs(comparisonResult.ActualElement)); Assert.That(comparisonResult.Message, Is.EqualTo( String.Format(Resources.AssertionFailure_AttributeQuantityMismatch, DefaultElementName.LocalName))); Assert.That(comparisonResult.XPathHint, Is.EqualTo( String.Format("/{0}:{1}/{0}:{1}", DefaultElementName.NamespaceName, DefaultElementName.LocalName))); } /// <summary> /// Verifies the strict behavior mode of the AreEquivalent() method, when given /// two XML elements that differ in number of attributes. /// </summary> [Test] public void AreEquivalent_Strict_ExcessAttributes() { XElement expectedElement = new XElement(DefaultElementName, new XAttribute("attribute_1", 100)); XElement actualElement = new XElement(DefaultElementName, new XAttribute("attribute_1", 100), new XAttribute("attribute_2", 200)); XmlComparisonResult comparisonResult = new XmlEquivalencyAssertion(XmlComparisonFlags.Strict) .AreEquivalent(expectedElement.CreateReader(), actualElement.CreateReader()); Assert.That(!comparisonResult.Result); ValidateComparisonResultElement(comparisonResult.ExpectedElement, DefaultElementName, null); ValidateComparisonResultElement(comparisonResult.ActualElement, DefaultElementName, null); Assert.That(comparisonResult.ExpectedElement, Is.Not.SameAs(comparisonResult.ActualElement)); Assert.That(comparisonResult.Message, Is.EqualTo( String.Format(Resources.AssertionFailure_AttributeQuantityMismatch, DefaultElementName.LocalName))); Assert.That(comparisonResult.XPathHint, Is.EqualTo( String.Format("/{0}:{1}", DefaultElementName.NamespaceName, DefaultElementName.LocalName))); } /// <summary> /// Verifies the strict behavior mode of the AreEquivalent() method, when given /// two XML elements that differ in number of attributes. /// </summary> [Test] public void AreEquivalent_Strict_ExcessAttributesInDescendant() { XElement expectedElement = new XElement(DefaultElementName, new XElement(DefaultElementName, new XAttribute("attribute_1", 100))); XElement actualElement = new XElement(DefaultElementName, new XElement(DefaultElementName, new XAttribute("attribute_1", 100), new XAttribute("attribute_2", 200))); XmlComparisonResult comparisonResult = new XmlEquivalencyAssertion(XmlComparisonFlags.Strict) .AreEquivalent(expectedElement.CreateReader(), actualElement.CreateReader()); Assert.That(!comparisonResult.Result); ValidateComparisonResultElement(comparisonResult.ExpectedElement, DefaultElementName, DefaultElementName); ValidateComparisonResultElement(comparisonResult.ActualElement, DefaultElementName, DefaultElementName); Assert.That(comparisonResult.ExpectedElement, Is.Not.SameAs(comparisonResult.ActualElement)); Assert.That(comparisonResult.Message, Is.EqualTo( String.Format(Resources.AssertionFailure_AttributeQuantityMismatch, DefaultElementName.LocalName))); Assert.That(comparisonResult.XPathHint, Is.EqualTo( String.Format("/{0}:{1}/{0}:{1}", DefaultElementName.NamespaceName, DefaultElementName.LocalName))); } /// <summary> /// Verifies the strict behavior mode of the AreEquivalent() method, when given /// two XML elements that differ in their attributes. /// </summary> [Test] public void AreEquivalent_Strict_AttributeNameMismatch() { XAttribute[] actualAttributes = { new XAttribute("attribute_6", 300), DefaultAttributes[1], DefaultAttributes[2] }; XmlComparisonResult comparisonResult = new XmlEquivalencyAssertion(XmlComparisonFlags.Strict).AreEquivalent( new XElement(DefaultElementName, DefaultAttributes).CreateReader(), new XElement(DefaultElementName, actualAttributes).CreateReader()); Assert.That(!comparisonResult.Result); ValidateComparisonResultElement(comparisonResult.ExpectedElement, DefaultElementName, null); ValidateComparisonResultElement(comparisonResult.ActualElement, DefaultElementName, null); Assert.That(comparisonResult.ExpectedElement, Is.Not.SameAs(comparisonResult.ActualElement)); Assert.That(comparisonResult.Message, Is.EqualTo( String.Format(Resources.AssertionFailure_UnexpectedAttribute, actualAttributes[0].Name.LocalName, DefaultElementName.LocalName))); Assert.That(comparisonResult.XPathHint, Is.EqualTo( String.Format("/{0}:{1}", DefaultElementName.NamespaceName, DefaultElementName.LocalName))); } /// <summary> /// Verifies the strict behavior mode of the AreEquivalent() method, when given /// two XML elements that differ in their attribute values. /// </summary> [Test] public void AreEquivalent_Strict_AttributeValueMismatch() { XAttribute[] actualAttributes = { new XAttribute(DefaultAttributes[0].Name, 600), DefaultAttributes[1], DefaultAttributes[2] }; XmlComparisonResult comparisonResult = new XmlEquivalencyAssertion(XmlComparisonFlags.Strict).AreEquivalent( new XElement(DefaultElementName, DefaultAttributes).CreateReader(), new XElement(DefaultElementName, actualAttributes).CreateReader()); Assert.That(!comparisonResult.Result); ValidateComparisonResultElement(comparisonResult.ExpectedElement, DefaultElementName, null); ValidateComparisonResultElement(comparisonResult.ActualElement, DefaultElementName, null); Assert.That(comparisonResult.ExpectedElement, Is.Not.SameAs(comparisonResult.ActualElement)); Assert.That(comparisonResult.Message, Is.EqualTo(String.Format( Resources.AssertionFailure_AttributeValueMismatch, DefaultAttributes[0].Name, DefaultElementName.LocalName, DefaultAttributes[0].Value, actualAttributes[0].Value))); Assert.That(comparisonResult.XPathHint, Is.EqualTo( String.Format("/{0}:{1}", DefaultElementName.NamespaceName, DefaultElementName.LocalName))); } /// <summary> /// Verifies the strict behavior mode of the AreEquivalent() method, when given /// two XML elements that differ in number of a child elements. /// </summary> [Test] public void AreEquivalent_Strict_ExcessElement() { XName excessElementName = XName.Get("excessElement", DefaultElementName.NamespaceName); XmlComparisonResult comparisonResult = new XmlEquivalencyAssertion(XmlComparisonFlags.Strict).AreEquivalent( new XElement(DefaultElementName, new XElement(DefaultElementName)).CreateReader(), new XElement(DefaultElementName, new XElement(excessElementName), new XElement(DefaultElementName)).CreateReader()); Assert.That(!comparisonResult.Result); ValidateComparisonResultElement(comparisonResult.ExpectedElement, DefaultElementName, DefaultElementName); ValidateComparisonResultElement(comparisonResult.ActualElement, excessElementName, DefaultElementName); Assert.That(comparisonResult.Message, Is.EqualTo( String.Format(Resources.AssertionFailure_UnexpectedElement, DefaultElementName.LocalName, excessElementName.LocalName))); Assert.That(comparisonResult.XPathHint, Is.EqualTo( String.Format("/{0}:{1}/{0}:{2}", DefaultElementName.NamespaceName, DefaultElementName.LocalName, excessElementName.LocalName))); } /// <summary> /// Verifies the strict behavior mode of the AreEquivalent() method, when given /// two XML elements that differ in number of a decendant elements. /// </summary> [Test] public void AreEquivalent_Strict_ExcessElementInDescendant() { XName excessElementName = XName.Get("excessElement", DefaultElementName.NamespaceName); XmlComparisonResult comparisonResult = new XmlEquivalencyAssertion(XmlComparisonFlags.Strict).AreEquivalent( new XElement(DefaultElementName, new XElement(DefaultElementName, new XElement(DefaultElementName), new XElement(DefaultElementName))).CreateReader(), new XElement(DefaultElementName, new XElement(DefaultElementName, new XElement(DefaultElementName), new XElement(excessElementName), new XElement(DefaultElementName))).CreateReader()); Assert.That(!comparisonResult.Result); ValidateComparisonResultElement(comparisonResult.ExpectedElement, DefaultElementName, DefaultElementName); ValidateComparisonResultElement(comparisonResult.ActualElement, excessElementName, DefaultElementName); Assert.That(comparisonResult.Message, Is.EqualTo( String.Format(Resources.AssertionFailure_UnexpectedElement, DefaultElementName.LocalName, excessElementName.LocalName))); Assert.That(comparisonResult.XPathHint, Is.EqualTo( String.Format("/{0}:{1}/{0}:{1}/{0}:{2}", DefaultElementName.NamespaceName, DefaultElementName.LocalName, excessElementName.LocalName))); } /// <summary> /// Verifies the strict behavior mode of the AreEquivalent() method, when given /// two XML elements that differ in number of a child elements. /// </summary> [Test] public void AreEquivalent_Strict_MismatchingNumberOfChildren() { XmlComparisonResult comparisonResult = new XmlEquivalencyAssertion(XmlComparisonFlags.Strict).AreEquivalent( new XElement(DefaultElementName).CreateReader(), new XElement(DefaultElementName, new XElement(DefaultElementName)).CreateReader()); Assert.That(!comparisonResult.Result); ValidateComparisonResultElement(comparisonResult.ExpectedElement, DefaultElementName, null); ValidateComparisonResultElement(comparisonResult.ActualElement, DefaultElementName, null); Assert.That(comparisonResult.Message, Is.EqualTo( String.Format(Resources.AssertionFailure_ChildElementQuantityMismatch, DefaultElementName.LocalName))); Assert.That(comparisonResult.XPathHint, Is.EqualTo( String.Format("/{0}:{1}", DefaultElementName.NamespaceName, DefaultElementName.LocalName))); } /// <summary> /// Verifies the strict behavior mode of the AreEquivalent() method, when given /// two XML elements that differ in number of a descendant elements. /// </summary> [Test] public void AreEquivalent_Strict_MismatchingNumberOfChildrenInDescendant() { XmlComparisonResult comparisonResult = new XmlEquivalencyAssertion(XmlComparisonFlags.Strict).AreEquivalent( new XElement(DefaultElementName, new XElement(DefaultElementName)).CreateReader(), new XElement(DefaultElementName, new XElement(DefaultElementName, new XElement(DefaultElementName))).CreateReader()); Assert.That(!comparisonResult.Result); ValidateComparisonResultElement(comparisonResult.ExpectedElement, DefaultElementName, DefaultElementName); ValidateComparisonResultElement(comparisonResult.ActualElement, DefaultElementName, DefaultElementName); Assert.That(comparisonResult.Message, Is.EqualTo( String.Format(Resources.AssertionFailure_ChildElementQuantityMismatch, DefaultElementName.LocalName))); Assert.That(comparisonResult.XPathHint, Is.EqualTo( String.Format("/{0}:{1}/{0}:{1}", DefaultElementName.NamespaceName, DefaultElementName.LocalName))); } /// <summary> /// Verifies the strict behavior mode of the AreEquivalent() method, when given /// two XML elements that differ in a child element local name. /// </summary> [Test] public void AreEquivalent_Strict_ChildLocalNameMismatch() { XName differentElementName = XName.Get("DifferentElementName", DefaultElementName.NamespaceName); XElement expectedElement = new XElement(DefaultElementName, new XElement(DefaultElementName), new XElement(DefaultElementName)); XElement actualElement = new XElement(DefaultElementName, new XElement(DefaultElementName), new XElement(differentElementName)); XmlComparisonResult comparisonResult = new XmlEquivalencyAssertion(XmlComparisonFlags.Strict) .AreEquivalent(expectedElement.CreateReader(), actualElement.CreateReader()); Assert.That(!comparisonResult.Result); ValidateComparisonResultElement(comparisonResult.ExpectedElement, DefaultElementName, DefaultElementName); ValidateComparisonResultElement(comparisonResult.ActualElement, differentElementName, DefaultElementName); Assert.That(comparisonResult.Message, Is.EqualTo( String.Format(Resources.AssertionFailure_UnexpectedElement, DefaultElementName.LocalName, differentElementName.LocalName))); Assert.That(comparisonResult.XPathHint, Is.EqualTo( String.Format("/{0}:{1}/{0}:{2}", DefaultElementName.NamespaceName, DefaultElementName.LocalName, differentElementName.LocalName))); } /// <summary> /// Verifies the strict behavior mode of the AreEquivalent() method, when given /// two XML elements that differ in child element namespace. /// </summary> [Test] public void AreEquivalent_Strict_ChildNamespaceMismatch() { XName differentElementName = XName.Get(DefaultElementName.LocalName, "urn:different-namespace"); XElement expectedElement = new XElement(DefaultElementName, new XElement(DefaultElementName), new XElement(DefaultElementName)); XElement actualElement = new XElement(DefaultElementName, new XElement(DefaultElementName), new XElement(differentElementName)); XmlComparisonResult comparisonResult = new XmlEquivalencyAssertion(XmlComparisonFlags.Strict) .AreEquivalent(expectedElement.CreateReader(), actualElement.CreateReader()); Assert.That(!comparisonResult.Result); ValidateComparisonResultElement(comparisonResult.ExpectedElement, DefaultElementName, DefaultElementName); ValidateComparisonResultElement(comparisonResult.ActualElement, differentElementName, DefaultElementName); Assert.That(comparisonResult.Message, Is.EqualTo(String.Format( Resources.AssertionFailure_ElementNamespaceMismatch, DefaultElementName.LocalName, DefaultElementName.NamespaceName, differentElementName.NamespaceName))); Assert.That(comparisonResult.XPathHint, Is.EqualTo( String.Format("/{0}:{1}/{2}:{1}", DefaultElementName.NamespaceName, DefaultElementName.LocalName, differentElementName.NamespaceName))); } /// <summary> /// Verifies the strict behavior mode of the AreEquivalent() method, when given /// two XML elements that differ in child element value. /// </summary> [Test] public void AreEquivalent_Strict_ChildValueMismatch() { XElement expectedElement = new XElement(DefaultElementName, new XElement(DefaultElementName), new XElement(DefaultElementName, 100, 200, new XElement(DefaultElementName), 300)); XElement actualElement = new XElement(DefaultElementName, new XElement(DefaultElementName), new XElement(DefaultElementName, 100, new XElement(DefaultElementName), 200, 400)); XmlComparisonResult comparisonResult = new XmlEquivalencyAssertion(XmlComparisonFlags.Strict) .AreEquivalent(expectedElement.CreateReader(), actualElement.CreateReader()); Assert.That(!comparisonResult.Result); ValidateComparisonResultElement(comparisonResult.ExpectedElement, DefaultElementName, DefaultElementName); ValidateComparisonResultElement(comparisonResult.ActualElement, DefaultElementName, DefaultElementName); Assert.That(comparisonResult.ExpectedElement, Is.Not.SameAs(comparisonResult.ActualElement)); Assert.That(comparisonResult.Message, Is.EqualTo( String.Format(Resources.AssertionFailure_ElementValueMismatch, DefaultElementName.LocalName, "100200300", "100200400"))); Assert.That(comparisonResult.XPathHint, Is.EqualTo( String.Format("/{0}:{1}/{0}:{1}", DefaultElementName.NamespaceName, DefaultElementName.LocalName))); } /// <summary> /// Verifies the strict behavior mode of the AreEquivalent() method, when given /// two XML elements that differ in a child element's attributes. /// </summary> [Test] public void AreEquivalent_Strict_ChildAttributeNameMismatch() { XAttribute[] actualAttributes = { new XAttribute("attribute_6", 300), DefaultAttributes[1], DefaultAttributes[2] }; XElement expectedElement = new XElement(DefaultElementName, new XElement(DefaultElementName), new XElement(DefaultElementName, DefaultAttributes)); XElement actualElement = new XElement(DefaultElementName, new XElement(DefaultElementName), new XElement(DefaultElementName, actualAttributes)); XmlComparisonResult comparisonResult = new XmlEquivalencyAssertion(XmlComparisonFlags.Strict) .AreEquivalent(expectedElement.CreateReader(), actualElement.CreateReader()); Assert.That(!comparisonResult.Result); ValidateComparisonResultElement(comparisonResult.ExpectedElement, DefaultElementName, DefaultElementName); ValidateComparisonResultElement(comparisonResult.ActualElement, DefaultElementName, DefaultElementName); Assert.That(comparisonResult.ExpectedElement, Is.Not.SameAs(comparisonResult.ActualElement)); Assert.That(comparisonResult.Message, Is.EqualTo( String.Format(Resources.AssertionFailure_UnexpectedAttribute, actualAttributes[0].Name.LocalName, DefaultElementName.LocalName))); Assert.That(comparisonResult.XPathHint, Is.EqualTo( String.Format("/{0}:{1}/{0}:{1}", DefaultElementName.NamespaceName, DefaultElementName.LocalName))); } /// <summary> /// Verifies the strict behavior mode of the AreEquivalent() method, when given /// two XML elements that differ in a child element's attribute values. /// </summary> [Test] public void AreEquivalent_Strict_ChildAttributeValueMismatch() { XAttribute[] actualAttributes = { new XAttribute(DefaultAttributes[0].Name, 600), DefaultAttributes[1], DefaultAttributes[2] }; XElement expectedElement = new XElement(DefaultElementName, new XElement(DefaultElementName), new XElement(DefaultElementName, DefaultAttributes)); XElement actualElement = new XElement(DefaultElementName, new XElement(DefaultElementName), new XElement(DefaultElementName, actualAttributes)); XmlComparisonResult comparisonResult = new XmlEquivalencyAssertion(XmlComparisonFlags.Strict) .AreEquivalent(expectedElement.CreateReader(), actualElement.CreateReader()); Assert.That(!comparisonResult.Result); ValidateComparisonResultElement(comparisonResult.ExpectedElement, DefaultElementName, DefaultElementName); ValidateComparisonResultElement(comparisonResult.ActualElement, DefaultElementName, DefaultElementName); Assert.That(comparisonResult.ExpectedElement, Is.Not.SameAs(comparisonResult.ActualElement)); Assert.That(comparisonResult.Message, Is.EqualTo(String.Format( Resources.AssertionFailure_AttributeValueMismatch, actualAttributes[0].Name.LocalName, DefaultElementName.LocalName, DefaultAttributes[0].Value, actualAttributes[0].Value))); Assert.That(comparisonResult.XPathHint, Is.EqualTo( String.Format("/{0}:{1}/{0}:{1}", DefaultElementName.NamespaceName, DefaultElementName.LocalName))); } #endregion #region private methods ------------------------------------------------------------------- /// <summary> /// Loads an embedded resource from the XML folder, with the given name. /// </summary> /// /// <param name="resourceName"> /// The name of the resource to load. /// </param> private static XmlReader GetEmbeddedXml(string resourceName) { Type thisType = typeof(XmlEquivalencyAssertionTestFixture); return XmlReader.Create(thisType.Assembly.GetManifestResourceStream(thisType, "Xml." + resourceName)); } /// <summary> /// Validates the contents of a given XElement, stored in an /// <seealso cref="XmlComparisonResult"/>. /// </summary> /// /// <param name="element"> /// The element to validate. /// </param> /// /// <param name="expectedElementName"> /// The expected element name. /// </param> /// /// <param name="expectedParentElementName"> /// The name of the expected element's parent. /// </param> private static void ValidateComparisonResultElement(XElement element, XName expectedElementName, XName expectedParentElementName) { Assert.That(element.Name, Is.EqualTo(expectedElementName)); if (expectedParentElementName == null) { Assert.That(element.Parent, Is.Null); } else { Assert.That(element.Parent.Name, Is.EqualTo(expectedParentElementName)); } } #endregion #region private fields -------------------------------------------------------------------- private static readonly XName DefaultElementName; private static readonly XAttribute[] DefaultAttributes; #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.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Testing; using Templates.Test.Helpers; using Xunit; using Xunit.Abstractions; namespace Templates.Test { public class RazorPagesTemplateTest : LoggedTest { public RazorPagesTemplateTest(ProjectFactoryFixture projectFactory) { ProjectFactory = projectFactory; } public ProjectFactoryFixture ProjectFactory { get; set; } private ITestOutputHelper _output; public ITestOutputHelper Output { get { if (_output == null) { _output = new TestOutputLogger(Logger); } return _output; } } [ConditionalFact] [SkipOnHelix("Cert failure, https://github.com/dotnet/aspnetcore/issues/28090", Queues = "All.OSX;" + HelixConstants.Windows10Arm64 + HelixConstants.DebianArm64)] public async Task RazorPagesTemplate_NoAuth() { var project = await ProjectFactory.GetOrCreateProject("razorpagesnoauth", Output); var createResult = await project.RunDotNetNewAsync("razor"); Assert.True(0 == createResult.ExitCode, ErrorMessages.GetFailedProcessMessage("razor", project, createResult)); var projectFileContents = ReadFile(project.TemplateOutputDir, $"{project.ProjectName}.csproj"); Assert.DoesNotContain(".db", projectFileContents); Assert.DoesNotContain("Microsoft.EntityFrameworkCore.Tools", projectFileContents); Assert.DoesNotContain("Microsoft.VisualStudio.Web.CodeGeneration.Design", projectFileContents); Assert.DoesNotContain("Microsoft.EntityFrameworkCore.Tools.DotNet", projectFileContents); Assert.DoesNotContain("Microsoft.Extensions.SecretManager.Tools", projectFileContents); var publishResult = await project.RunDotNetPublishAsync(); Assert.True(0 == publishResult.ExitCode, ErrorMessages.GetFailedProcessMessage("publish", project, createResult)); // Run dotnet build after publish. The reason is that one uses Config = Debug and the other uses Config = Release // The output from publish will go into bin/Release/netcoreappX.Y/publish and won't be affected by calling build // later, while the opposite is not true. var buildResult = await project.RunDotNetBuildAsync(); Assert.True(0 == buildResult.ExitCode, ErrorMessages.GetFailedProcessMessage("build", project, createResult)); var pages = new List<Page> { new Page { Url = PageUrls.HomeUrl, Links = new string[] { PageUrls.HomeUrl, PageUrls.HomeUrl, PageUrls.PrivacyUrl, PageUrls.DocsUrl, PageUrls.PrivacyUrl } }, new Page { Url = PageUrls.PrivacyUrl, Links = new string[] { PageUrls.HomeUrl, PageUrls.HomeUrl, PageUrls.PrivacyUrl, PageUrls.PrivacyUrl } } }; using (var aspNetProcess = project.StartBuiltProjectAsync()) { Assert.False( aspNetProcess.Process.HasExited, ErrorMessages.GetFailedProcessMessageOrEmpty("Run built project", project, aspNetProcess.Process)); await aspNetProcess.AssertPagesOk(pages); } using (var aspNetProcess = project.StartPublishedProjectAsync()) { Assert.False( aspNetProcess.Process.HasExited, ErrorMessages.GetFailedProcessMessageOrEmpty("Run published project", project, aspNetProcess.Process)); await aspNetProcess.AssertPagesOk(pages); } } [ConditionalTheory] [InlineData(false)] [InlineData(true)] [SkipOnHelix("Cert failure, https://github.com/dotnet/aspnetcore/issues/28090", Queues = "All.OSX;" + HelixConstants.Windows10Arm64 + HelixConstants.DebianArm64)] public async Task RazorPagesTemplate_IndividualAuth(bool useLocalDB) { var project = await ProjectFactory.GetOrCreateProject("razorpagesindividual" + (useLocalDB ? "uld" : ""), Output); var createResult = await project.RunDotNetNewAsync("razor", auth: "Individual", useLocalDB: useLocalDB); Assert.True(0 == createResult.ExitCode, ErrorMessages.GetFailedProcessMessage("create/restore", project, createResult)); var projectFileContents = ReadFile(project.TemplateOutputDir, $"{project.ProjectName}.csproj"); if (!useLocalDB) { Assert.Contains(".db", projectFileContents); } var publishResult = await project.RunDotNetPublishAsync(); Assert.True(0 == publishResult.ExitCode, ErrorMessages.GetFailedProcessMessage("publish", project, publishResult)); // Run dotnet build after publish. The reason is that one uses Config = Debug and the other uses Config = Release // The output from publish will go into bin/Release/netcoreappX.Y/publish and won't be affected by calling build // later, while the opposite is not true. var buildResult = await project.RunDotNetBuildAsync(); Assert.True(0 == buildResult.ExitCode, ErrorMessages.GetFailedProcessMessage("build", project, buildResult)); var migrationsResult = await project.RunDotNetEfCreateMigrationAsync("razorpages"); Assert.True(0 == migrationsResult.ExitCode, ErrorMessages.GetFailedProcessMessage("run EF migrations", project, migrationsResult)); project.AssertEmptyMigration("razorpages"); // Note: if any links are updated here, MvcTemplateTest.cs should be updated as well var pages = new List<Page> { new Page { Url = PageUrls.ForgotPassword, Links = new string [] { PageUrls.HomeUrl, PageUrls.HomeUrl, PageUrls.PrivacyUrl, PageUrls.RegisterUrl, PageUrls.LoginUrl, PageUrls.PrivacyUrl } }, new Page { Url = PageUrls.HomeUrl, Links = new string[] { PageUrls.HomeUrl, PageUrls.HomeUrl, PageUrls.PrivacyUrl, PageUrls.RegisterUrl, PageUrls.LoginUrl, PageUrls.DocsUrl, PageUrls.PrivacyUrl } }, new Page { Url = PageUrls.PrivacyUrl, Links = new string[] { PageUrls.HomeUrl, PageUrls.HomeUrl, PageUrls.PrivacyUrl, PageUrls.RegisterUrl, PageUrls.LoginUrl, PageUrls.PrivacyUrl } }, new Page { Url = PageUrls.LoginUrl, Links = new string[] { PageUrls.HomeUrl, PageUrls.HomeUrl, PageUrls.PrivacyUrl, PageUrls.RegisterUrl, PageUrls.LoginUrl, PageUrls.ForgotPassword, PageUrls.RegisterUrl, PageUrls.ResendEmailConfirmation, PageUrls.ExternalArticle, PageUrls.PrivacyUrl } }, new Page { Url = PageUrls.RegisterUrl, Links = new string [] { PageUrls.HomeUrl, PageUrls.HomeUrl, PageUrls.PrivacyUrl, PageUrls.RegisterUrl, PageUrls.LoginUrl, PageUrls.ExternalArticle, PageUrls.PrivacyUrl } } }; using (var aspNetProcess = project.StartBuiltProjectAsync()) { Assert.False( aspNetProcess.Process.HasExited, ErrorMessages.GetFailedProcessMessageOrEmpty("Run built project", project, aspNetProcess.Process)); await aspNetProcess.AssertPagesOk(pages); } using (var aspNetProcess = project.StartPublishedProjectAsync()) { Assert.False( aspNetProcess.Process.HasExited, ErrorMessages.GetFailedProcessMessageOrEmpty("Run built project", project, aspNetProcess.Process)); await aspNetProcess.AssertPagesOk(pages); } } [ConditionalTheory] [SkipOnHelix("https://github.com/dotnet/aspnetcore/issues/28090", Queues = HelixConstants.Windows10Arm64 + HelixConstants.DebianArm64)] [InlineData("IndividualB2C", null)] [InlineData("IndividualB2C", new string[] { "--called-api-url \"https://graph.microsoft.com\"", "--called-api-scopes user.readwrite" })] [InlineData("SingleOrg", null)] [InlineData("SingleOrg", new string[] { "--called-api-url \"https://graph.microsoft.com\"", "--called-api-scopes user.readwrite" })] public Task RazorPagesTemplate_IdentityWeb_BuildsAndPublishes(string auth, string[] args) => BuildAndPublishRazorPagesTemplate(auth: auth, args: args); [ConditionalTheory] [InlineData("SingleOrg", new string[] { "--calls-graph" })] [QuarantinedTest("https://github.com/dotnet/aspnetcore/issues/31729")] public Task RazorPagesTemplate_IdentityWeb_BuildsAndPublishes_WithSingleOrg(string auth, string[] args) => BuildAndPublishRazorPagesTemplate(auth: auth, args: args); private async Task<Project> BuildAndPublishRazorPagesTemplate(string auth, string[] args) { var project = await ProjectFactory.GetOrCreateProject("razorpages" + Guid.NewGuid().ToString().Substring(0, 10).ToLowerInvariant(), Output); var createResult = await project.RunDotNetNewAsync("razor", auth: auth, args: args); Assert.True(0 == createResult.ExitCode, ErrorMessages.GetFailedProcessMessage("create/restore", project, createResult)); // Verify building in debug works var buildResult = await project.RunDotNetBuildAsync(); Assert.True(0 == buildResult.ExitCode, ErrorMessages.GetFailedProcessMessage("build", project, buildResult)); // Publish builds in "release" configuration. Running publish should ensure we can compile in release and that we can publish without issues. buildResult = await project.RunDotNetPublishAsync(); Assert.True(0 == buildResult.ExitCode, ErrorMessages.GetFailedProcessMessage("publish", project, buildResult)); return project; } private string ReadFile(string basePath, string path) { var fullPath = Path.Combine(basePath, path); var doesExist = File.Exists(fullPath); Assert.True(doesExist, $"Expected file to exist, but it doesn't: {path}"); return File.ReadAllText(Path.Combine(basePath, path)); } } }
using System; using System.Collections.Generic; using System.Text; using System.IO; using OctoTorrent.Common; using OctoTorrent.Client; using System.Net; using System.Diagnostics; using System.Threading; using OctoTorrent.BEncoding; using OctoTorrent.Client.Encryption; using OctoTorrent.Dht; using OctoTorrent.Dht.Listeners; namespace OctoTorrent { using System.Linq; using SampleClient; class main { static string _dhtNodeFile; static string _basePath; static string _downloadsPath; static string _fastResumeFile; static string _torrentsPath; static ClientEngine _engine; // The engine used for downloading static List<TorrentManager> _torrents; // The list where all the torrentManagers will be stored that the engine gives us static Top10Listener _listener; // This is a subclass of TraceListener which remembers the last 20 statements sent to it static void Main(string[] args) { /* Generate the paths to the folder we will save .torrent files to and where we download files to */ _basePath = Environment.CurrentDirectory; // This is the directory we are currently in _torrentsPath = Path.Combine(_basePath, "Torrents"); // This is the directory we will save .torrents to _downloadsPath = Path.Combine(_basePath, "Downloads"); // This is the directory we will save downloads to _fastResumeFile = Path.Combine(_torrentsPath, "fastresume.data"); _dhtNodeFile = Path.Combine(_basePath, "DhtNodes"); _torrents = new List<TorrentManager>(); // This is where we will store the torrentmanagers _listener = new Top10Listener(10); // We need to cleanup correctly when the user closes the window by using ctrl-c // or an unhandled exception happens Console.CancelKeyPress += delegate { Shutdown(); }; AppDomain.CurrentDomain.ProcessExit += delegate { Shutdown(); }; AppDomain.CurrentDomain.UnhandledException += delegate(object sender, UnhandledExceptionEventArgs e) { Console.WriteLine(e.ExceptionObject); Shutdown(); }; Thread.GetDomain().UnhandledException += delegate(object sender, UnhandledExceptionEventArgs e) { Console.WriteLine(e.ExceptionObject); Shutdown(); }; StartEngine(); } private static void StartEngine() { int port; Torrent torrent; // Ask the user what port they want to use for incoming connections Console.Write(Environment.NewLine + "Choose a listen port: "); while (!Int32.TryParse(Console.ReadLine(), out port)) { } // Create the settings which the engine will use // downloadsPath - this is the path where we will save all the files to // port - this is the port we listen for connections on var engineSettings = new EngineSettings(_downloadsPath, port) { PreferEncryption = false, AllowedEncryption = EncryptionTypes.All }; //engineSettings.GlobalMaxUploadSpeed = 30 * 1024; //engineSettings.GlobalMaxDownloadSpeed = 100 * 1024; //engineSettings.MaxReadRate = 1 * 1024 * 1024; // Create the default settings which a torrent will have. // 4 Upload slots - a good ratio is one slot per 5kB of upload speed // 50 open connections - should never really need to be changed // Unlimited download speed - valid range from 0 -> int.Max // Unlimited upload speed - valid range from 0 -> int.Max var torrentDefaults = new TorrentSettings(4, 150, 0, 0); // Create an instance of the engine. _engine = new ClientEngine(engineSettings); _engine.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, port)); byte[] nodes = null; try { nodes = File.ReadAllBytes(_dhtNodeFile); } catch { Console.WriteLine("No existing dht nodes could be loaded"); } DhtListener dhtListner = new DhtListener (new IPEndPoint (IPAddress.Any, port)); DhtEngine dht = new DhtEngine (dhtListner); _engine.RegisterDht(dht); dhtListner.Start(); _engine.DhtEngine.Start(nodes); // If the SavePath does not exist, we want to create it. if (!Directory.Exists(_engine.Settings.SavePath)) Directory.CreateDirectory(_engine.Settings.SavePath); // If the torrentsPath does not exist, we want to create it if (!Directory.Exists(_torrentsPath)) Directory.CreateDirectory(_torrentsPath); BEncodedDictionary fastResume; try { fastResume = BEncodedValue.Decode<BEncodedDictionary>(File.ReadAllBytes(_fastResumeFile)); } catch { fastResume = new BEncodedDictionary(); } // For each file in the torrents path that is a .torrent file, load it into the engine. foreach (string file in Directory.GetFiles(_torrentsPath)) { if (file.EndsWith(".torrent")) { try { // Load the .torrent from the file into a Torrent instance // You can use this to do preprocessing should you need to torrent = Torrent.Load(file); Console.WriteLine(torrent.InfoHash.ToString()); } catch (Exception e) { Console.Write("Couldn't decode {0}: ", file); Console.WriteLine(e.Message); continue; } // When any preprocessing has been completed, you create a TorrentManager // which you then register with the engine. var manager = new TorrentManager(torrent, _downloadsPath, torrentDefaults); if (fastResume.ContainsKey(torrent.InfoHash.ToHex ())) manager.LoadFastResume(new FastResume ((BEncodedDictionary)fastResume[torrent.infoHash.ToHex ()])); _engine.Register(manager); // Store the torrent manager in our list so we can access it later _torrents.Add(manager); manager.PeersFound += ManagerPeersFound; } } // If we loaded no torrents, just exist. The user can put files in the torrents directory and start // the client again if (_torrents.Count == 0) { Console.WriteLine("No torrents found in the Torrents directory"); Console.WriteLine("Exiting..."); _engine.Dispose(); return; } // For each torrent manager we loaded and stored in our list, hook into the events // in the torrent manager and start the engine. foreach (TorrentManager manager in _torrents) { // Every time a piece is hashed, this is fired. manager.PieceHashed += delegate(object o, PieceHashedEventArgs e) { lock (_listener) _listener.WriteLine(string.Format("Piece Hashed: {0} - {1}", e.PieceIndex, e.HashPassed ? "Pass" : "Fail")); }; // Every time the state changes (Stopped -> Seeding -> Downloading -> Hashing) this is fired manager.TorrentStateChanged += delegate (object o, TorrentStateChangedEventArgs e) { lock (_listener) _listener.WriteLine(string.Format("OldState: {0} NewState: {1}", e.OldState, e.NewState)); }; // Every time the tracker's state changes, this is fired foreach (var tracker in manager.TrackerManager.SelectMany(tier => tier.Trackers)) { tracker.AnnounceComplete += (sender, e) => _listener.WriteLine(string.Format("{0}: {1}", e.Successful, e.Tracker.ToString())); } // Start the torrentmanager. The file will then hash (if required) and begin downloading/seeding manager.Start(); } // While the torrents are still running, print out some stats to the screen. // Details for all the loaded torrent managers are shown. var i = 0; var running = true; var sb = new StringBuilder(1024); while (running) { if ((i++) % 10 == 0) { sb.Remove(0, sb.Length); running = _torrents.Exists(delegate(TorrentManager m) { return m.State != TorrentState.Stopped; }); AppendFormat(sb, "Total Download Rate: {0:0.00}kB/sec", _engine.TotalDownloadSpeed / 1024.0); AppendFormat(sb, "Total Upload Rate: {0:0.00}kB/sec", _engine.TotalUploadSpeed / 1024.0); AppendFormat(sb, "Disk Read Rate: {0:0.00} kB/s", _engine.DiskManager.ReadRate / 1024.0); AppendFormat(sb, "Disk Write Rate: {0:0.00} kB/s", _engine.DiskManager.WriteRate / 1024.0); AppendFormat(sb, "Total Read: {0:0.00} kB", _engine.DiskManager.TotalRead / 1024.0); AppendFormat(sb, "Total Written: {0:0.00} kB", _engine.DiskManager.TotalWritten / 1024.0); AppendFormat(sb, "Open Connections: {0}", _engine.ConnectionManager.OpenConnections); foreach (var manager in _torrents) { AppendSeperator(sb); AppendFormat(sb, "State: {0}", manager.State); AppendFormat(sb, "Name: {0}", manager.Torrent == null ? "MetaDataMode" : manager.Torrent.Name); AppendFormat(sb, "Progress: {0:0.00}", manager.Progress); AppendFormat(sb, "Download Speed: {0:0.00} kB/s", manager.Monitor.DownloadSpeed / 1024.0); AppendFormat(sb, "Upload Speed: {0:0.00} kB/s", manager.Monitor.UploadSpeed / 1024.0); AppendFormat(sb, "Total Downloaded: {0:0.00} MB", manager.Monitor.DataBytesDownloaded / (1024.0 * 1024.0)); AppendFormat(sb, "Total Uploaded: {0:0.00} MB", manager.Monitor.DataBytesUploaded / (1024.0 * 1024.0)); var tracker = manager.TrackerManager.CurrentTracker; //AppendFormat(sb, "Tracker Status: {0}", tracker == null ? "<no tracker>" : tracker.State.ToString()); AppendFormat(sb, "Warning Message: {0}", tracker == null ? "<no tracker>" : tracker.WarningMessage); AppendFormat(sb, "Failure Message: {0}", tracker == null ? "<no tracker>" : tracker.FailureMessage); if (manager.PieceManager != null) AppendFormat(sb, "Current Requests: {0}", manager.PieceManager.CurrentRequestCount()); foreach (var peerId in manager.GetPeers()) AppendFormat(sb, "\t{2} - {1:0.00}/{3:0.00}kB/sec - {0}", peerId.Peer.ConnectionUri, peerId.Monitor.DownloadSpeed / 1024.0, peerId.AmRequestingPiecesCount, peerId.Monitor.UploadSpeed/ 1024.0); AppendFormat(sb, "", null); if (manager.Torrent != null) foreach (var file in manager.Torrent.Files) AppendFormat(sb, "{1:0.00}% - {0}", file.Path, file.BitField.PercentComplete); } Console.Clear(); Console.WriteLine(sb.ToString()); _listener.ExportTo(Console.Out); } Thread.Sleep(500); } } static void ManagerPeersFound(object sender, PeersAddedEventArgs e) { lock (_listener) _listener.WriteLine(string.Format("Found {0} new peers and {1} existing peers", e.NewPeers, e.ExistingPeers ));//throw new Exception("The method or operation is not implemented."); } private static void AppendSeperator(StringBuilder sb) { AppendFormat(sb, "", null); AppendFormat(sb, "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -", null); AppendFormat(sb, "", null); } private static void AppendFormat(StringBuilder sb, string str, params object[] formatting) { if (formatting != null) sb.AppendFormat(str, formatting); else sb.Append(str); sb.AppendLine(); } private static void Shutdown() { var fastResume = new BEncodedDictionary(); foreach (var torrentManager in _torrents) { torrentManager.Stop(); while (torrentManager.State != TorrentState.Stopped) { Console.WriteLine("{0} is {1}", torrentManager.Torrent.Name, torrentManager.State); Thread.Sleep(250); } fastResume.Add(torrentManager.Torrent.InfoHash.ToHex (), torrentManager.SaveFastResume().Encode()); } #if !DISABLE_DHT File.WriteAllBytes(_dhtNodeFile, _engine.DhtEngine.SaveNodes()); #endif File.WriteAllBytes(_fastResumeFile, fastResume.Encode()); _engine.Dispose(); foreach (TraceListener lst in Debug.Listeners) { lst.Flush(); lst.Close(); } Thread.Sleep(2000); } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // using System; using System.IO; using DiscUtils.Streams; namespace DiscUtils { /// <summary> /// Common interface for all file systems. /// </summary> public interface IFileSystem { /// <summary> /// Gets a value indicating whether the file system is read-only or read-write. /// </summary> /// <returns>true if the file system is read-write.</returns> bool CanWrite { get; } /// <summary> /// Gets a value indicating whether the file system is thread-safe. /// </summary> bool IsThreadSafe { get; } /// <summary> /// Gets the root directory of the file system. /// </summary> DiscDirectoryInfo Root { get; } /// <summary> /// Copies an existing file to a new file. /// </summary> /// <param name="sourceFile">The source file.</param> /// <param name="destinationFile">The destination file.</param> void CopyFile(string sourceFile, string destinationFile); /// <summary> /// Copies an existing file to a new file, allowing overwriting of an existing file. /// </summary> /// <param name="sourceFile">The source file.</param> /// <param name="destinationFile">The destination file.</param> /// <param name="overwrite">Whether to permit over-writing of an existing file.</param> void CopyFile(string sourceFile, string destinationFile, bool overwrite); /// <summary> /// Creates a directory. /// </summary> /// <param name="path">The path of the new directory.</param> void CreateDirectory(string path); /// <summary> /// Deletes a directory. /// </summary> /// <param name="path">The path of the directory to delete.</param> void DeleteDirectory(string path); /// <summary> /// Deletes a directory, optionally with all descendants. /// </summary> /// <param name="path">The path of the directory to delete.</param> /// <param name="recursive">Determines if the all descendants should be deleted.</param> void DeleteDirectory(string path, bool recursive); /// <summary> /// Deletes a file. /// </summary> /// <param name="path">The path of the file to delete.</param> void DeleteFile(string path); /// <summary> /// Indicates if a directory exists. /// </summary> /// <param name="path">The path to test.</param> /// <returns>true if the directory exists.</returns> bool DirectoryExists(string path); /// <summary> /// Indicates if a file exists. /// </summary> /// <param name="path">The path to test.</param> /// <returns>true if the file exists.</returns> bool FileExists(string path); /// <summary> /// Indicates if a file or directory exists. /// </summary> /// <param name="path">The path to test.</param> /// <returns>true if the file or directory exists.</returns> bool Exists(string path); /// <summary> /// Gets the names of subdirectories in a specified directory. /// </summary> /// <param name="path">The path to search.</param> /// <returns>Array of directories.</returns> string[] GetDirectories(string path); /// <summary> /// Gets the names of subdirectories in a specified directory matching a specified /// search pattern. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <returns>Array of directories matching the search pattern.</returns> string[] GetDirectories(string path, string searchPattern); /// <summary> /// Gets the names of subdirectories in a specified directory matching a specified /// search pattern, using a value to determine whether to search subdirectories. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <param name="searchOption">Indicates whether to search subdirectories.</param> /// <returns>Array of directories matching the search pattern.</returns> string[] GetDirectories(string path, string searchPattern, SearchOption searchOption); /// <summary> /// Gets the names of files in a specified directory. /// </summary> /// <param name="path">The path to search.</param> /// <returns>Array of files.</returns> string[] GetFiles(string path); /// <summary> /// Gets the names of files in a specified directory. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <returns>Array of files matching the search pattern.</returns> string[] GetFiles(string path, string searchPattern); /// <summary> /// Gets the names of files in a specified directory matching a specified /// search pattern, using a value to determine whether to search subdirectories. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <param name="searchOption">Indicates whether to search subdirectories.</param> /// <returns>Array of files matching the search pattern.</returns> string[] GetFiles(string path, string searchPattern, SearchOption searchOption); /// <summary> /// Gets the names of all files and subdirectories in a specified directory. /// </summary> /// <param name="path">The path to search.</param> /// <returns>Array of files and subdirectories matching the search pattern.</returns> string[] GetFileSystemEntries(string path); /// <summary> /// Gets the names of files and subdirectories in a specified directory matching a specified /// search pattern. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <returns>Array of files and subdirectories matching the search pattern.</returns> string[] GetFileSystemEntries(string path, string searchPattern); /// <summary> /// Moves a directory. /// </summary> /// <param name="sourceDirectoryName">The directory to move.</param> /// <param name="destinationDirectoryName">The target directory name.</param> void MoveDirectory(string sourceDirectoryName, string destinationDirectoryName); /// <summary> /// Moves a file. /// </summary> /// <param name="sourceName">The file to move.</param> /// <param name="destinationName">The target file name.</param> void MoveFile(string sourceName, string destinationName); /// <summary> /// Moves a file, allowing an existing file to be overwritten. /// </summary> /// <param name="sourceName">The file to move.</param> /// <param name="destinationName">The target file name.</param> /// <param name="overwrite">Whether to permit a destination file to be overwritten.</param> void MoveFile(string sourceName, string destinationName, bool overwrite); /// <summary> /// Opens the specified file. /// </summary> /// <param name="path">The full path of the file to open.</param> /// <param name="mode">The file mode for the created stream.</param> /// <returns>The new stream.</returns> SparseStream OpenFile(string path, FileMode mode); /// <summary> /// Opens the specified file. /// </summary> /// <param name="path">The full path of the file to open.</param> /// <param name="mode">The file mode for the created stream.</param> /// <param name="access">The access permissions for the created stream.</param> /// <returns>The new stream.</returns> SparseStream OpenFile(string path, FileMode mode, FileAccess access); /// <summary> /// Gets the attributes of a file or directory. /// </summary> /// <param name="path">The file or directory to inspect.</param> /// <returns>The attributes of the file or directory.</returns> FileAttributes GetAttributes(string path); /// <summary> /// Sets the attributes of a file or directory. /// </summary> /// <param name="path">The file or directory to change.</param> /// <param name="newValue">The new attributes of the file or directory.</param> void SetAttributes(string path, FileAttributes newValue); /// <summary> /// Gets the creation time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The creation time.</returns> DateTime GetCreationTime(string path); /// <summary> /// Sets the creation time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> void SetCreationTime(string path, DateTime newTime); /// <summary> /// Gets the creation time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The creation time.</returns> DateTime GetCreationTimeUtc(string path); /// <summary> /// Sets the creation time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> void SetCreationTimeUtc(string path, DateTime newTime); /// <summary> /// Gets the last access time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The last access time.</returns> DateTime GetLastAccessTime(string path); /// <summary> /// Sets the last access time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> void SetLastAccessTime(string path, DateTime newTime); /// <summary> /// Gets the last access time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The last access time.</returns> DateTime GetLastAccessTimeUtc(string path); /// <summary> /// Sets the last access time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> void SetLastAccessTimeUtc(string path, DateTime newTime); /// <summary> /// Gets the last modification time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The last write time.</returns> DateTime GetLastWriteTime(string path); /// <summary> /// Sets the last modification time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> void SetLastWriteTime(string path, DateTime newTime); /// <summary> /// Gets the last modification time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The last write time.</returns> DateTime GetLastWriteTimeUtc(string path); /// <summary> /// Sets the last modification time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> void SetLastWriteTimeUtc(string path, DateTime newTime); /// <summary> /// Gets the length of a file. /// </summary> /// <param name="path">The path to the file.</param> /// <returns>The length in bytes.</returns> long GetFileLength(string path); /// <summary> /// Gets an object representing a possible file. /// </summary> /// <param name="path">The file path.</param> /// <returns>The representing object.</returns> /// <remarks>The file does not need to exist.</remarks> DiscFileInfo GetFileInfo(string path); /// <summary> /// Gets an object representing a possible directory. /// </summary> /// <param name="path">The directory path.</param> /// <returns>The representing object.</returns> /// <remarks>The directory does not need to exist.</remarks> DiscDirectoryInfo GetDirectoryInfo(string path); /// <summary> /// Gets an object representing a possible file system object (file or directory). /// </summary> /// <param name="path">The file system path.</param> /// <returns>The representing object.</returns> /// <remarks>The file system object does not need to exist.</remarks> DiscFileSystemInfo GetFileSystemInfo(string path); /// <summary> /// Reads the boot code of the file system into a byte array. /// </summary> /// <returns>The boot code, or <c>null</c> if not available.</returns> byte[] ReadBootCode(); /// <summary> /// Size of the Filesystem in bytes /// </summary> long Size { get; } /// <summary> /// Used space of the Filesystem in bytes /// </summary> long UsedSpace { get; } /// <summary> /// Available space of the Filesystem in bytes /// </summary> long AvailableSpace { get; } } }
// 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 gagvr = Google.Ads.GoogleAds.V10.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using lro = Google.LongRunning; using proto = Google.Protobuf; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V10.Services { /// <summary>Settings for <see cref="OfflineUserDataJobServiceClient"/> instances.</summary> public sealed partial class OfflineUserDataJobServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="OfflineUserDataJobServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="OfflineUserDataJobServiceSettings"/>.</returns> public static OfflineUserDataJobServiceSettings GetDefault() => new OfflineUserDataJobServiceSettings(); /// <summary> /// Constructs a new <see cref="OfflineUserDataJobServiceSettings"/> object with default settings. /// </summary> public OfflineUserDataJobServiceSettings() { } private OfflineUserDataJobServiceSettings(OfflineUserDataJobServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); CreateOfflineUserDataJobSettings = existing.CreateOfflineUserDataJobSettings; AddOfflineUserDataJobOperationsSettings = existing.AddOfflineUserDataJobOperationsSettings; RunOfflineUserDataJobSettings = existing.RunOfflineUserDataJobSettings; RunOfflineUserDataJobOperationsSettings = existing.RunOfflineUserDataJobOperationsSettings.Clone(); OnCopy(existing); } partial void OnCopy(OfflineUserDataJobServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>OfflineUserDataJobServiceClient.CreateOfflineUserDataJob</c> and /// <c>OfflineUserDataJobServiceClient.CreateOfflineUserDataJobAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings CreateOfflineUserDataJobSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>OfflineUserDataJobServiceClient.AddOfflineUserDataJobOperations</c> and /// <c>OfflineUserDataJobServiceClient.AddOfflineUserDataJobOperationsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings AddOfflineUserDataJobOperationsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>OfflineUserDataJobServiceClient.RunOfflineUserDataJob</c> and /// <c>OfflineUserDataJobServiceClient.RunOfflineUserDataJobAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings RunOfflineUserDataJobSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// Long Running Operation settings for calls to <c>OfflineUserDataJobServiceClient.RunOfflineUserDataJob</c> /// and <c>OfflineUserDataJobServiceClient.RunOfflineUserDataJobAsync</c>. /// </summary> /// <remarks> /// Uses default <see cref="gax::PollSettings"/> of: /// <list type="bullet"> /// <item><description>Initial delay: 20 seconds.</description></item> /// <item><description>Delay multiplier: 1.5</description></item> /// <item><description>Maximum delay: 45 seconds.</description></item> /// <item><description>Total timeout: 24 hours.</description></item> /// </list> /// </remarks> public lro::OperationsSettings RunOfflineUserDataJobOperationsSettings { get; set; } = new lro::OperationsSettings { DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)), }; /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="OfflineUserDataJobServiceSettings"/> object.</returns> public OfflineUserDataJobServiceSettings Clone() => new OfflineUserDataJobServiceSettings(this); } /// <summary> /// Builder class for <see cref="OfflineUserDataJobServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class OfflineUserDataJobServiceClientBuilder : gaxgrpc::ClientBuilderBase<OfflineUserDataJobServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public OfflineUserDataJobServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public OfflineUserDataJobServiceClientBuilder() { UseJwtAccessWithScopes = OfflineUserDataJobServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref OfflineUserDataJobServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<OfflineUserDataJobServiceClient> task); /// <summary>Builds the resulting client.</summary> public override OfflineUserDataJobServiceClient Build() { OfflineUserDataJobServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<OfflineUserDataJobServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<OfflineUserDataJobServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private OfflineUserDataJobServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return OfflineUserDataJobServiceClient.Create(callInvoker, Settings); } private async stt::Task<OfflineUserDataJobServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return OfflineUserDataJobServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => OfflineUserDataJobServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => OfflineUserDataJobServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => OfflineUserDataJobServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>OfflineUserDataJobService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage offline user data jobs. /// </remarks> public abstract partial class OfflineUserDataJobServiceClient { /// <summary> /// The default endpoint for the OfflineUserDataJobService service, which is a host of /// "googleads.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default OfflineUserDataJobService scopes.</summary> /// <remarks> /// The default OfflineUserDataJobService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="OfflineUserDataJobServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="OfflineUserDataJobServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="OfflineUserDataJobServiceClient"/>.</returns> public static stt::Task<OfflineUserDataJobServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new OfflineUserDataJobServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="OfflineUserDataJobServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="OfflineUserDataJobServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="OfflineUserDataJobServiceClient"/>.</returns> public static OfflineUserDataJobServiceClient Create() => new OfflineUserDataJobServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="OfflineUserDataJobServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="OfflineUserDataJobServiceSettings"/>.</param> /// <returns>The created <see cref="OfflineUserDataJobServiceClient"/>.</returns> internal static OfflineUserDataJobServiceClient Create(grpccore::CallInvoker callInvoker, OfflineUserDataJobServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } OfflineUserDataJobService.OfflineUserDataJobServiceClient grpcClient = new OfflineUserDataJobService.OfflineUserDataJobServiceClient(callInvoker); return new OfflineUserDataJobServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC OfflineUserDataJobService client</summary> public virtual OfflineUserDataJobService.OfflineUserDataJobServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Creates an offline user data job. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [NotAllowlistedError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual CreateOfflineUserDataJobResponse CreateOfflineUserDataJob(CreateOfflineUserDataJobRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates an offline user data job. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [NotAllowlistedError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<CreateOfflineUserDataJobResponse> CreateOfflineUserDataJobAsync(CreateOfflineUserDataJobRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates an offline user data job. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [NotAllowlistedError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<CreateOfflineUserDataJobResponse> CreateOfflineUserDataJobAsync(CreateOfflineUserDataJobRequest request, st::CancellationToken cancellationToken) => CreateOfflineUserDataJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates an offline user data job. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [NotAllowlistedError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer for which to create an offline user data job. /// </param> /// <param name="job"> /// Required. The offline user data job to be created. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual CreateOfflineUserDataJobResponse CreateOfflineUserDataJob(string customerId, gagvr::OfflineUserDataJob job, gaxgrpc::CallSettings callSettings = null) => CreateOfflineUserDataJob(new CreateOfflineUserDataJobRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Job = gax::GaxPreconditions.CheckNotNull(job, nameof(job)), }, callSettings); /// <summary> /// Creates an offline user data job. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [NotAllowlistedError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer for which to create an offline user data job. /// </param> /// <param name="job"> /// Required. The offline user data job to be created. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<CreateOfflineUserDataJobResponse> CreateOfflineUserDataJobAsync(string customerId, gagvr::OfflineUserDataJob job, gaxgrpc::CallSettings callSettings = null) => CreateOfflineUserDataJobAsync(new CreateOfflineUserDataJobRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Job = gax::GaxPreconditions.CheckNotNull(job, nameof(job)), }, callSettings); /// <summary> /// Creates an offline user data job. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [NotAllowlistedError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer for which to create an offline user data job. /// </param> /// <param name="job"> /// Required. The offline user data job to be created. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<CreateOfflineUserDataJobResponse> CreateOfflineUserDataJobAsync(string customerId, gagvr::OfflineUserDataJob job, st::CancellationToken cancellationToken) => CreateOfflineUserDataJobAsync(customerId, job, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Adds operations to the offline user data job. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual AddOfflineUserDataJobOperationsResponse AddOfflineUserDataJobOperations(AddOfflineUserDataJobOperationsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Adds operations to the offline user data job. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<AddOfflineUserDataJobOperationsResponse> AddOfflineUserDataJobOperationsAsync(AddOfflineUserDataJobOperationsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Adds operations to the offline user data job. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<AddOfflineUserDataJobOperationsResponse> AddOfflineUserDataJobOperationsAsync(AddOfflineUserDataJobOperationsRequest request, st::CancellationToken cancellationToken) => AddOfflineUserDataJobOperationsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Adds operations to the offline user data job. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the OfflineUserDataJob. /// </param> /// <param name="operations"> /// Required. The list of operations to be done. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual AddOfflineUserDataJobOperationsResponse AddOfflineUserDataJobOperations(string resourceName, scg::IEnumerable<OfflineUserDataJobOperation> operations, gaxgrpc::CallSettings callSettings = null) => AddOfflineUserDataJobOperations(new AddOfflineUserDataJobOperationsRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Adds operations to the offline user data job. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the OfflineUserDataJob. /// </param> /// <param name="operations"> /// Required. The list of operations to be done. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<AddOfflineUserDataJobOperationsResponse> AddOfflineUserDataJobOperationsAsync(string resourceName, scg::IEnumerable<OfflineUserDataJobOperation> operations, gaxgrpc::CallSettings callSettings = null) => AddOfflineUserDataJobOperationsAsync(new AddOfflineUserDataJobOperationsRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Adds operations to the offline user data job. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the OfflineUserDataJob. /// </param> /// <param name="operations"> /// Required. The list of operations to be done. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<AddOfflineUserDataJobOperationsResponse> AddOfflineUserDataJobOperationsAsync(string resourceName, scg::IEnumerable<OfflineUserDataJobOperation> operations, st::CancellationToken cancellationToken) => AddOfflineUserDataJobOperationsAsync(resourceName, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Adds operations to the offline user data job. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the OfflineUserDataJob. /// </param> /// <param name="operations"> /// Required. The list of operations to be done. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual AddOfflineUserDataJobOperationsResponse AddOfflineUserDataJobOperations(gagvr::OfflineUserDataJobName resourceName, scg::IEnumerable<OfflineUserDataJobOperation> operations, gaxgrpc::CallSettings callSettings = null) => AddOfflineUserDataJobOperations(new AddOfflineUserDataJobOperationsRequest { ResourceNameAsOfflineUserDataJobName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Adds operations to the offline user data job. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the OfflineUserDataJob. /// </param> /// <param name="operations"> /// Required. The list of operations to be done. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<AddOfflineUserDataJobOperationsResponse> AddOfflineUserDataJobOperationsAsync(gagvr::OfflineUserDataJobName resourceName, scg::IEnumerable<OfflineUserDataJobOperation> operations, gaxgrpc::CallSettings callSettings = null) => AddOfflineUserDataJobOperationsAsync(new AddOfflineUserDataJobOperationsRequest { ResourceNameAsOfflineUserDataJobName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Adds operations to the offline user data job. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the OfflineUserDataJob. /// </param> /// <param name="operations"> /// Required. The list of operations to be done. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<AddOfflineUserDataJobOperationsResponse> AddOfflineUserDataJobOperationsAsync(gagvr::OfflineUserDataJobName resourceName, scg::IEnumerable<OfflineUserDataJobOperation> operations, st::CancellationToken cancellationToken) => AddOfflineUserDataJobOperationsAsync(resourceName, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Runs the offline user data job. /// /// When finished, the long running operation will contain the processing /// result or failure information, if any. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [HeaderError]() /// [InternalError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<wkt::Empty, gagvr::OfflineUserDataJobMetadata> RunOfflineUserDataJob(RunOfflineUserDataJobRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Runs the offline user data job. /// /// When finished, the long running operation will contain the processing /// result or failure information, if any. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [HeaderError]() /// [InternalError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<wkt::Empty, gagvr::OfflineUserDataJobMetadata>> RunOfflineUserDataJobAsync(RunOfflineUserDataJobRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Runs the offline user data job. /// /// When finished, the long running operation will contain the processing /// result or failure information, if any. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [HeaderError]() /// [InternalError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<wkt::Empty, gagvr::OfflineUserDataJobMetadata>> RunOfflineUserDataJobAsync(RunOfflineUserDataJobRequest request, st::CancellationToken cancellationToken) => RunOfflineUserDataJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary>The long-running operations client for <c>RunOfflineUserDataJob</c>.</summary> public virtual lro::OperationsClient RunOfflineUserDataJobOperationsClient => throw new sys::NotImplementedException(); /// <summary> /// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>RunOfflineUserDataJob</c> /// . /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The result of polling the operation.</returns> public virtual lro::Operation<wkt::Empty, gagvr::OfflineUserDataJobMetadata> PollOnceRunOfflineUserDataJob(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<wkt::Empty, gagvr::OfflineUserDataJobMetadata>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), RunOfflineUserDataJobOperationsClient, callSettings); /// <summary> /// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of /// <c>RunOfflineUserDataJob</c>. /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A task representing the result of polling the operation.</returns> public virtual stt::Task<lro::Operation<wkt::Empty, gagvr::OfflineUserDataJobMetadata>> PollOnceRunOfflineUserDataJobAsync(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<wkt::Empty, gagvr::OfflineUserDataJobMetadata>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), RunOfflineUserDataJobOperationsClient, callSettings); /// <summary> /// Runs the offline user data job. /// /// When finished, the long running operation will contain the processing /// result or failure information, if any. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [HeaderError]() /// [InternalError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the OfflineUserDataJob to run. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<wkt::Empty, gagvr::OfflineUserDataJobMetadata> RunOfflineUserDataJob(string resourceName, gaxgrpc::CallSettings callSettings = null) => RunOfflineUserDataJob(new RunOfflineUserDataJobRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Runs the offline user data job. /// /// When finished, the long running operation will contain the processing /// result or failure information, if any. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [HeaderError]() /// [InternalError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the OfflineUserDataJob to run. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<wkt::Empty, gagvr::OfflineUserDataJobMetadata>> RunOfflineUserDataJobAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => RunOfflineUserDataJobAsync(new RunOfflineUserDataJobRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Runs the offline user data job. /// /// When finished, the long running operation will contain the processing /// result or failure information, if any. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [HeaderError]() /// [InternalError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the OfflineUserDataJob to run. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<wkt::Empty, gagvr::OfflineUserDataJobMetadata>> RunOfflineUserDataJobAsync(string resourceName, st::CancellationToken cancellationToken) => RunOfflineUserDataJobAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Runs the offline user data job. /// /// When finished, the long running operation will contain the processing /// result or failure information, if any. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [HeaderError]() /// [InternalError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the OfflineUserDataJob to run. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<wkt::Empty, gagvr::OfflineUserDataJobMetadata> RunOfflineUserDataJob(gagvr::OfflineUserDataJobName resourceName, gaxgrpc::CallSettings callSettings = null) => RunOfflineUserDataJob(new RunOfflineUserDataJobRequest { ResourceNameAsOfflineUserDataJobName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Runs the offline user data job. /// /// When finished, the long running operation will contain the processing /// result or failure information, if any. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [HeaderError]() /// [InternalError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the OfflineUserDataJob to run. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<wkt::Empty, gagvr::OfflineUserDataJobMetadata>> RunOfflineUserDataJobAsync(gagvr::OfflineUserDataJobName resourceName, gaxgrpc::CallSettings callSettings = null) => RunOfflineUserDataJobAsync(new RunOfflineUserDataJobRequest { ResourceNameAsOfflineUserDataJobName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Runs the offline user data job. /// /// When finished, the long running operation will contain the processing /// result or failure information, if any. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [HeaderError]() /// [InternalError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the OfflineUserDataJob to run. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<wkt::Empty, gagvr::OfflineUserDataJobMetadata>> RunOfflineUserDataJobAsync(gagvr::OfflineUserDataJobName resourceName, st::CancellationToken cancellationToken) => RunOfflineUserDataJobAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>OfflineUserDataJobService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage offline user data jobs. /// </remarks> public sealed partial class OfflineUserDataJobServiceClientImpl : OfflineUserDataJobServiceClient { private readonly gaxgrpc::ApiCall<CreateOfflineUserDataJobRequest, CreateOfflineUserDataJobResponse> _callCreateOfflineUserDataJob; private readonly gaxgrpc::ApiCall<AddOfflineUserDataJobOperationsRequest, AddOfflineUserDataJobOperationsResponse> _callAddOfflineUserDataJobOperations; private readonly gaxgrpc::ApiCall<RunOfflineUserDataJobRequest, lro::Operation> _callRunOfflineUserDataJob; /// <summary> /// Constructs a client wrapper for the OfflineUserDataJobService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="OfflineUserDataJobServiceSettings"/> used within this client. /// </param> public OfflineUserDataJobServiceClientImpl(OfflineUserDataJobService.OfflineUserDataJobServiceClient grpcClient, OfflineUserDataJobServiceSettings settings) { GrpcClient = grpcClient; OfflineUserDataJobServiceSettings effectiveSettings = settings ?? OfflineUserDataJobServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); RunOfflineUserDataJobOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClient(), effectiveSettings.RunOfflineUserDataJobOperationsSettings); _callCreateOfflineUserDataJob = clientHelper.BuildApiCall<CreateOfflineUserDataJobRequest, CreateOfflineUserDataJobResponse>(grpcClient.CreateOfflineUserDataJobAsync, grpcClient.CreateOfflineUserDataJob, effectiveSettings.CreateOfflineUserDataJobSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callCreateOfflineUserDataJob); Modify_CreateOfflineUserDataJobApiCall(ref _callCreateOfflineUserDataJob); _callAddOfflineUserDataJobOperations = clientHelper.BuildApiCall<AddOfflineUserDataJobOperationsRequest, AddOfflineUserDataJobOperationsResponse>(grpcClient.AddOfflineUserDataJobOperationsAsync, grpcClient.AddOfflineUserDataJobOperations, effectiveSettings.AddOfflineUserDataJobOperationsSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callAddOfflineUserDataJobOperations); Modify_AddOfflineUserDataJobOperationsApiCall(ref _callAddOfflineUserDataJobOperations); _callRunOfflineUserDataJob = clientHelper.BuildApiCall<RunOfflineUserDataJobRequest, lro::Operation>(grpcClient.RunOfflineUserDataJobAsync, grpcClient.RunOfflineUserDataJob, effectiveSettings.RunOfflineUserDataJobSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callRunOfflineUserDataJob); Modify_RunOfflineUserDataJobApiCall(ref _callRunOfflineUserDataJob); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_CreateOfflineUserDataJobApiCall(ref gaxgrpc::ApiCall<CreateOfflineUserDataJobRequest, CreateOfflineUserDataJobResponse> call); partial void Modify_AddOfflineUserDataJobOperationsApiCall(ref gaxgrpc::ApiCall<AddOfflineUserDataJobOperationsRequest, AddOfflineUserDataJobOperationsResponse> call); partial void Modify_RunOfflineUserDataJobApiCall(ref gaxgrpc::ApiCall<RunOfflineUserDataJobRequest, lro::Operation> call); partial void OnConstruction(OfflineUserDataJobService.OfflineUserDataJobServiceClient grpcClient, OfflineUserDataJobServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC OfflineUserDataJobService client</summary> public override OfflineUserDataJobService.OfflineUserDataJobServiceClient GrpcClient { get; } partial void Modify_CreateOfflineUserDataJobRequest(ref CreateOfflineUserDataJobRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_AddOfflineUserDataJobOperationsRequest(ref AddOfflineUserDataJobOperationsRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_RunOfflineUserDataJobRequest(ref RunOfflineUserDataJobRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Creates an offline user data job. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [NotAllowlistedError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override CreateOfflineUserDataJobResponse CreateOfflineUserDataJob(CreateOfflineUserDataJobRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_CreateOfflineUserDataJobRequest(ref request, ref callSettings); return _callCreateOfflineUserDataJob.Sync(request, callSettings); } /// <summary> /// Creates an offline user data job. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [NotAllowlistedError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<CreateOfflineUserDataJobResponse> CreateOfflineUserDataJobAsync(CreateOfflineUserDataJobRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_CreateOfflineUserDataJobRequest(ref request, ref callSettings); return _callCreateOfflineUserDataJob.Async(request, callSettings); } /// <summary> /// Adds operations to the offline user data job. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override AddOfflineUserDataJobOperationsResponse AddOfflineUserDataJobOperations(AddOfflineUserDataJobOperationsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_AddOfflineUserDataJobOperationsRequest(ref request, ref callSettings); return _callAddOfflineUserDataJobOperations.Sync(request, callSettings); } /// <summary> /// Adds operations to the offline user data job. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<AddOfflineUserDataJobOperationsResponse> AddOfflineUserDataJobOperationsAsync(AddOfflineUserDataJobOperationsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_AddOfflineUserDataJobOperationsRequest(ref request, ref callSettings); return _callAddOfflineUserDataJobOperations.Async(request, callSettings); } /// <summary>The long-running operations client for <c>RunOfflineUserDataJob</c>.</summary> public override lro::OperationsClient RunOfflineUserDataJobOperationsClient { get; } /// <summary> /// Runs the offline user data job. /// /// When finished, the long running operation will contain the processing /// result or failure information, if any. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [HeaderError]() /// [InternalError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override lro::Operation<wkt::Empty, gagvr::OfflineUserDataJobMetadata> RunOfflineUserDataJob(RunOfflineUserDataJobRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_RunOfflineUserDataJobRequest(ref request, ref callSettings); return new lro::Operation<wkt::Empty, gagvr::OfflineUserDataJobMetadata>(_callRunOfflineUserDataJob.Sync(request, callSettings), RunOfflineUserDataJobOperationsClient); } /// <summary> /// Runs the offline user data job. /// /// When finished, the long running operation will contain the processing /// result or failure information, if any. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [HeaderError]() /// [InternalError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override async stt::Task<lro::Operation<wkt::Empty, gagvr::OfflineUserDataJobMetadata>> RunOfflineUserDataJobAsync(RunOfflineUserDataJobRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_RunOfflineUserDataJobRequest(ref request, ref callSettings); return new lro::Operation<wkt::Empty, gagvr::OfflineUserDataJobMetadata>(await _callRunOfflineUserDataJob.Async(request, callSettings).ConfigureAwait(false), RunOfflineUserDataJobOperationsClient); } } public static partial class OfflineUserDataJobService { public partial class OfflineUserDataJobServiceClient { /// <summary> /// Creates a new instance of <see cref="lro::Operations.OperationsClient"/> using the same call invoker as /// this client. /// </summary> /// <returns>A new Operations client for the same target as this client.</returns> public virtual lro::Operations.OperationsClient CreateOperationsClient() => new lro::Operations.OperationsClient(CallInvoker); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================================= ** ** Class: Queue ** ** Purpose: Represents a first-in, first-out collection of objects. ** =============================================================================*/ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace System.Collections { // A simple Queue of objects. Internally it is implemented as a circular // buffer, so Enqueue can be O(n). Dequeue is O(1). [DebuggerTypeProxy(typeof(System.Collections.Queue.QueueDebugView))] [DebuggerDisplay("Count = {Count}")] [Serializable] public class Queue : ICollection { private Object[] _array; private int _head; // First valid element in the queue private int _tail; // Last valid element in the queue private int _size; // Number of elements. private int _growFactor; // 100 == 1.0, 130 == 1.3, 200 == 2.0 private int _version; [NonSerialized] private Object _syncRoot; private const int _MinimumGrow = 4; private const int _ShrinkThreshold = 32; // Creates a queue with room for capacity objects. The default initial // capacity and grow factor are used. public Queue() : this(32, (float)2.0) { } // Creates a queue with room for capacity objects. The default grow factor // is used. // public Queue(int capacity) : this(capacity, (float)2.0) { } // Creates a queue with room for capacity objects. When full, the new // capacity is set to the old capacity * growFactor. // public Queue(int capacity, float growFactor) { if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NeedNonNegNum); if (!(growFactor >= 1.0 && growFactor <= 10.0)) throw new ArgumentOutOfRangeException(nameof(growFactor), SR.Format(SR.ArgumentOutOfRange_QueueGrowFactor, 1, 10)); Contract.EndContractBlock(); _array = new Object[capacity]; _head = 0; _tail = 0; _size = 0; _growFactor = (int)(growFactor * 100); } // Fills a Queue with the elements of an ICollection. Uses the enumerator // to get each of the elements. // public Queue(ICollection col) : this((col == null ? 32 : col.Count)) { if (col == null) throw new ArgumentNullException(nameof(col)); Contract.EndContractBlock(); IEnumerator en = col.GetEnumerator(); while (en.MoveNext()) Enqueue(en.Current); } public virtual int Count { get { return _size; } } public virtual Object Clone() { Queue q = new Queue(_size); q._size = _size; int numToCopy = _size; int firstPart = (_array.Length - _head < numToCopy) ? _array.Length - _head : numToCopy; Array.Copy(_array, _head, q._array, 0, firstPart); numToCopy -= firstPart; if (numToCopy > 0) Array.Copy(_array, 0, q._array, _array.Length - _head, numToCopy); q._version = _version; return q; } public virtual bool IsSynchronized { get { return false; } } public virtual Object SyncRoot { get { if (_syncRoot == null) { System.Threading.Interlocked.CompareExchange(ref _syncRoot, new Object(), null); } return _syncRoot; } } // Removes all Objects from the queue. public virtual void Clear() { if (_size != 0) { if (_head < _tail) Array.Clear(_array, _head, _size); else { Array.Clear(_array, _head, _array.Length - _head); Array.Clear(_array, 0, _tail); } _size = 0; } _head = 0; _tail = 0; _version++; } // CopyTo copies a collection into an Array, starting at a particular // index into the array. // public virtual void CopyTo(Array array, int index) { if (array == null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); int arrayLen = array.Length; if (arrayLen - index < _size) throw new ArgumentException(SR.Argument_InvalidOffLen); int numToCopy = _size; if (numToCopy == 0) return; int firstPart = (_array.Length - _head < numToCopy) ? _array.Length - _head : numToCopy; Array.Copy(_array, _head, array, index, firstPart); numToCopy -= firstPart; if (numToCopy > 0) Array.Copy(_array, 0, array, index + _array.Length - _head, numToCopy); } // Adds obj to the tail of the queue. // public virtual void Enqueue(Object obj) { if (_size == _array.Length) { int newcapacity = (int)((long)_array.Length * (long)_growFactor / 100); if (newcapacity < _array.Length + _MinimumGrow) { newcapacity = _array.Length + _MinimumGrow; } SetCapacity(newcapacity); } _array[_tail] = obj; _tail = (_tail + 1) % _array.Length; _size++; _version++; } // GetEnumerator returns an IEnumerator over this Queue. This // Enumerator will support removing. // public virtual IEnumerator GetEnumerator() { return new QueueEnumerator(this); } // Removes the object at the head of the queue and returns it. If the queue // is empty, this method simply returns null. public virtual Object Dequeue() { if (Count == 0) throw new InvalidOperationException(SR.InvalidOperation_EmptyQueue); Contract.EndContractBlock(); Object removed = _array[_head]; _array[_head] = null; _head = (_head + 1) % _array.Length; _size--; _version++; return removed; } // Returns the object at the head of the queue. The object remains in the // queue. If the queue is empty, this method throws an // InvalidOperationException. public virtual Object Peek() { if (Count == 0) throw new InvalidOperationException(SR.InvalidOperation_EmptyQueue); Contract.EndContractBlock(); return _array[_head]; } // Returns a synchronized Queue. Returns a synchronized wrapper // class around the queue - the caller must not use references to the // original queue. // public static Queue Synchronized(Queue queue) { if (queue == null) throw new ArgumentNullException(nameof(queue)); Contract.EndContractBlock(); return new SynchronizedQueue(queue); } // Returns true if the queue contains at least one object equal to obj. // Equality is determined using obj.Equals(). // // Exceptions: ArgumentNullException if obj == null. public virtual bool Contains(Object obj) { int index = _head; int count = _size; while (count-- > 0) { if (obj == null) { if (_array[index] == null) return true; } else if (_array[index] != null && _array[index].Equals(obj)) { return true; } index = (index + 1) % _array.Length; } return false; } internal Object GetElement(int i) { return _array[(_head + i) % _array.Length]; } // Iterates over the objects in the queue, returning an array of the // objects in the Queue, or an empty array if the queue is empty. // The order of elements in the array is first in to last in, the same // order produced by successive calls to Dequeue. public virtual Object[] ToArray() { if (_size == 0) return Array.Empty<Object>(); Object[] arr = new Object[_size]; if (_head < _tail) { Array.Copy(_array, _head, arr, 0, _size); } else { Array.Copy(_array, _head, arr, 0, _array.Length - _head); Array.Copy(_array, 0, arr, _array.Length - _head, _tail); } return arr; } // PRIVATE Grows or shrinks the buffer to hold capacity objects. Capacity // must be >= _size. private void SetCapacity(int capacity) { Object[] newarray = new Object[capacity]; if (_size > 0) { if (_head < _tail) { Array.Copy(_array, _head, newarray, 0, _size); } else { Array.Copy(_array, _head, newarray, 0, _array.Length - _head); Array.Copy(_array, 0, newarray, _array.Length - _head, _tail); } } _array = newarray; _head = 0; _tail = (_size == capacity) ? 0 : _size; _version++; } public virtual void TrimToSize() { SetCapacity(_size); } // Implements a synchronization wrapper around a queue. [Serializable] private class SynchronizedQueue : Queue { private Queue _q; private Object _root; internal SynchronizedQueue(Queue q) { _q = q; _root = _q.SyncRoot; } public override bool IsSynchronized { get { return true; } } public override Object SyncRoot { get { return _root; } } public override int Count { get { lock (_root) { return _q.Count; } } } public override void Clear() { lock (_root) { _q.Clear(); } } public override Object Clone() { lock (_root) { return new SynchronizedQueue((Queue)_q.Clone()); } } public override bool Contains(Object obj) { lock (_root) { return _q.Contains(obj); } } public override void CopyTo(Array array, int arrayIndex) { lock (_root) { _q.CopyTo(array, arrayIndex); } } public override void Enqueue(Object value) { lock (_root) { _q.Enqueue(value); } } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Thread safety problems with precondition - can't express the precondition as of Dev10. public override Object Dequeue() { lock (_root) { return _q.Dequeue(); } } public override IEnumerator GetEnumerator() { lock (_root) { return _q.GetEnumerator(); } } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Thread safety problems with precondition - can't express the precondition as of Dev10. public override Object Peek() { lock (_root) { return _q.Peek(); } } public override Object[] ToArray() { lock (_root) { return _q.ToArray(); } } public override void TrimToSize() { lock (_root) { _q.TrimToSize(); } } } // Implements an enumerator for a Queue. The enumerator uses the // internal version number of the list to ensure that no modifications are // made to the list while an enumeration is in progress. [Serializable] private class QueueEnumerator : IEnumerator { private Queue _q; private int _index; private int _version; private Object _currentElement; internal QueueEnumerator(Queue q) { _q = q; _version = _q._version; _index = 0; _currentElement = _q._array; if (_q._size == 0) _index = -1; } public virtual bool MoveNext() { if (_version != _q._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); if (_index < 0) { _currentElement = _q._array; return false; } _currentElement = _q.GetElement(_index); _index++; if (_index == _q._size) _index = -1; return true; } public virtual Object Current { get { if (_currentElement == _q._array) { if (_index == 0) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); else throw new InvalidOperationException(SR.InvalidOperation_EnumEnded); } return _currentElement; } } public virtual void Reset() { if (_version != _q._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); if (_q._size == 0) _index = -1; else _index = 0; _currentElement = _q._array; } } internal class QueueDebugView { private Queue _queue; public QueueDebugView(Queue queue) { if (queue == null) throw new ArgumentNullException(nameof(queue)); Contract.EndContractBlock(); _queue = queue; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public Object[] Items { get { return _queue.ToArray(); } } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Nini.Config; using System; using System.Collections.Generic; using System.Reflection; using OpenSim.Framework; using OpenSim.Server.Base; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset { public class LocalAssetServicesConnector : ISharedRegionModule, IAssetService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private IImprovedAssetCache m_Cache = null; private IAssetService m_AssetService; private bool m_Enabled = false; public Type ReplaceableInterface { get { return null; } } public string Name { get { return "LocalAssetServicesConnector"; } } public void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("AssetServices", ""); if (name == Name) { IConfig assetConfig = source.Configs["AssetService"]; if (assetConfig == null) { m_log.Error("[ASSET CONNECTOR]: AssetService missing from OpenSim.ini"); return; } string serviceDll = assetConfig.GetString("LocalServiceModule", String.Empty); if (serviceDll == String.Empty) { m_log.Error("[ASSET CONNECTOR]: No LocalServiceModule named in section AssetService"); return; } Object[] args = new Object[] { source }; m_AssetService = ServerUtils.LoadPlugin<IAssetService>(serviceDll, args); if (m_AssetService == null) { m_log.Error("[ASSET CONNECTOR]: Can't load asset service"); return; } m_Enabled = true; m_log.Info("[ASSET CONNECTOR]: Local asset connector enabled"); } } } public void PostInitialise() { } public void Close() { } public void AddRegion(Scene scene) { if (!m_Enabled) return; scene.RegisterModuleInterface<IAssetService>(this); } public void RemoveRegion(Scene scene) { } public void RegionLoaded(Scene scene) { if (!m_Enabled) return; if (m_Cache == null) { m_Cache = scene.RequestModuleInterface<IImprovedAssetCache>(); if (!(m_Cache is ISharedRegionModule)) m_Cache = null; } m_log.InfoFormat("[ASSET CONNECTOR]: Enabled local assets for region {0}", scene.RegionInfo.RegionName); if (m_Cache != null) { m_log.InfoFormat("[ASSET CONNECTOR]: Enabled asset caching for region {0}", scene.RegionInfo.RegionName); } else { // Short-circuit directly to storage layer // scene.UnregisterModuleInterface<IAssetService>(this); scene.RegisterModuleInterface<IAssetService>(m_AssetService); } } public AssetBase Get(string id) { AssetBase asset = null; if (m_Cache != null) asset = m_Cache.Get(id); if (asset == null) { asset = m_AssetService.Get(id); if ((m_Cache != null) && (asset != null)) m_Cache.Cache(asset); } return asset; } public AssetMetadata GetMetadata(string id) { AssetBase asset = null; if (m_Cache != null) asset = m_Cache.Get(id); if (asset != null) return asset.Metadata; asset = m_AssetService.Get(id); if (asset != null) { if (m_Cache != null) m_Cache.Cache(asset); return asset.Metadata; } return null; } public byte[] GetData(string id) { AssetBase asset = m_Cache.Get(id); if (asset != null) return asset.Data; asset = m_AssetService.Get(id); if (asset != null) { if (m_Cache != null) m_Cache.Cache(asset); return asset.Data; } return null; } public bool Get(string id, Object sender, AssetRetrieved handler) { AssetBase asset = null; if (m_Cache != null) m_Cache.Get(id); if (asset != null) { Util.FireAndForget(delegate { handler(id, sender, asset); }); return true; } return m_AssetService.Get(id, sender, delegate (string assetID, Object s, AssetBase a) { if ((a != null) && (m_Cache != null)) m_Cache.Cache(a); Util.FireAndForget(delegate { handler(assetID, s, a); }); }); } public string Store(AssetBase asset) { if (m_Cache != null) m_Cache.Cache(asset); if (asset.Temporary || asset.Local) return asset.ID; return m_AssetService.Store(asset); } public bool UpdateContent(string id, byte[] data) { AssetBase asset = null; if (m_Cache != null) m_Cache.Get(id); if (asset != null) { asset.Data = data; if (m_Cache != null) m_Cache.Cache(asset); } return m_AssetService.UpdateContent(id, data); } public bool Delete(string id) { if (m_Cache != null) m_Cache.Expire(id); return m_AssetService.Delete(id); } } }