context
stringlengths
2.52k
185k
gt
stringclasses
1 value
namespace DanTup.DartVS.ProjectSystem.Controls { using System; using System.ComponentModel; using System.Drawing; using System.IO; using System.Windows.Forms; using Microsoft.VisualStudio.Shell.Interop; using Package = Microsoft.VisualStudio.Shell.Package; using Url = Microsoft.VisualStudio.Shell.Url; /// <summary> /// Extends a simple text box specialized for browsing to folders. Supports auto-complete and /// a browse button that brings up the folder browse dialog. /// </summary> internal partial class FolderBrowserTextBox : UserControl { private string _rootFolder; // ========================================================================================= // Constructors // ========================================================================================= /// <summary> /// Initializes a new instance of the <see cref="FolderBrowserTextBox"/> class. /// </summary> public FolderBrowserTextBox() { this.InitializeComponent(); folderTextBox.Enabled = Enabled; browseButton.Enabled = Enabled; } // ========================================================================================= // Events // ========================================================================================= /// <summary> /// Occurs when the text has changed. /// </summary> [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] public new event EventHandler TextChanged { add { base.TextChanged += value; } remove { base.TextChanged -= value; } } [Bindable(true)] [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [EditorBrowsable(EditorBrowsableState.Always)] public string RootFolder { get { try { if (!string.IsNullOrEmpty(_rootFolder)) Path.IsPathRooted(_rootFolder); } catch (ArgumentException) { return string.Empty; } return _rootFolder; } set { _rootFolder = value; } } [Bindable(true)] [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [EditorBrowsable(EditorBrowsableState.Always)] [DefaultValue(false)] [Description("When this property is 'true', the folder path will be made relative to RootFolder, when possible.")] public bool MakeRelative { get; set; } // ========================================================================================= // Properties // ========================================================================================= /// <summary> /// Gets or sets the path of the selected folder. /// </summary> [Bindable(true)] [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [EditorBrowsable(EditorBrowsableState.Always)] public override string Text { get { return this.folderTextBox.Text; } set { this.folderTextBox.Text = value; } } private string FullPath { get { try { string text = Text ?? string.Empty; if (!string.IsNullOrEmpty(RootFolder)) text = Path.Combine(RootFolder, text); return Path.GetFullPath(text); } catch (ArgumentException) { return string.Empty; } } } // ========================================================================================= // Methods // ========================================================================================= /// <summary> /// Sets the bounds of the control. In this case, we fix the height to the text box's height. /// </summary> /// <param name="x">The new x value.</param> /// <param name="y">The new y value.</param> /// <param name="width">The new width value.</param> /// <param name="height">The height value.</param> /// <param name="specified">A set of flags indicating which bounds to set.</param> protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { if ((specified & BoundsSpecified.Height) == BoundsSpecified.Height) { height = this.folderTextBox.Height + 1; } base.SetBoundsCore(x, y, width, height, specified); } /// <summary> /// Brings up the browse folder dialog. /// </summary> /// <param name="sender">The browse button.</param> /// <param name="e">The <see cref="EventArgs"/> object that contains the event data.</param> private void OnBrowseButtonClick(object sender, EventArgs e) { // initialize the dialog to the current directory (if it exists) bool overridePersistedInitialDirectory = false; string initialDirectory = null; if (Directory.Exists(FullPath)) { initialDirectory = FullPath; overridePersistedInitialDirectory = true; } IntPtr parentWindow = Handle; Guid persistenceSlot = typeof(FileBrowserTextBox).GUID; IVsUIShell2 shell = (IVsUIShell2)Package.GetGlobalService(typeof(SVsUIShell)); // show the dialog string path = shell.GetDirectoryViaBrowseDialog(parentWindow, persistenceSlot, "Select folder", initialDirectory, overridePersistedInitialDirectory); if (path != null) { if (MakeRelative && !string.IsNullOrEmpty(RootFolder)) { string rootFolder = Path.GetFullPath(RootFolder); if (Directory.Exists(rootFolder)) { if (!rootFolder.EndsWith(Path.DirectorySeparatorChar.ToString()) && !rootFolder.EndsWith(Path.AltDirectorySeparatorChar.ToString())) rootFolder = rootFolder + Path.DirectorySeparatorChar; path = new Url(rootFolder).MakeRelative(new Url(path)); } } this.folderTextBox.Text = path; } } /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> /// <param name="sender">The folder text box.</param> /// <param name="e">The <see cref="EventArgs"/> object that contains the event data.</param> private void OnFolderTextBoxTextChanged(object sender, EventArgs e) { UpdateColor(); this.OnTextChanged(EventArgs.Empty); } protected override void OnEnabledChanged(EventArgs e) { folderTextBox.Enabled = Enabled; browseButton.Enabled = Enabled; UpdateColor(); browseButton.Invalidate(); base.OnEnabledChanged(e); } private void UpdateColor() { if (!Enabled) { folderTextBox.BackColor = SystemColors.Control; folderTextBox.ForeColor = SystemColors.GrayText; return; } folderTextBox.ForeColor = SystemColors.ControlText; folderTextBox.BackColor = Directory.Exists(FullPath) ? SystemColors.ControlLightLight : Color.LightSalmon; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.ContainerRegistry.Fluent { using Microsoft.Azure.Management.ContainerRegistry.Fluent.Models; using Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryDockerTaskStep.Definition; using Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryDockerTaskStep.Update; using Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTask.Definition; using Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTask.Update; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResourceActions; using System.Collections.Generic; internal partial class RegistryDockerTaskStepImpl { /// <summary> /// Gets the arguments this Docker task step. /// </summary> System.Collections.Generic.IReadOnlyList<Models.Argument> Microsoft.Azure.Management.ContainerRegistry.Fluent.IRegistryDockerTaskStep.Arguments { get { return this.Arguments(); } } /// <summary> /// Gets Docker file path for this Docker task step. /// </summary> string Microsoft.Azure.Management.ContainerRegistry.Fluent.IRegistryDockerTaskStep.DockerFilePath { get { return this.DockerFilePath(); } } /// <summary> /// Gets the image names of this Docker task step. /// </summary> System.Collections.Generic.IReadOnlyList<string> Microsoft.Azure.Management.ContainerRegistry.Fluent.IRegistryDockerTaskStep.ImageNames { get { return this.ImageNames(); } } /// <summary> /// Gets whether push is enabled for this Docker task step. /// </summary> bool Microsoft.Azure.Management.ContainerRegistry.Fluent.IRegistryDockerTaskStep.IsPushEnabled { get { return this.IsPushEnabled(); } } /// <summary> /// Gets whether there is no cache for this Docker task step. /// </summary> bool Microsoft.Azure.Management.ContainerRegistry.Fluent.IRegistryDockerTaskStep.NoCache { get { return this.NoCache(); } } /// <summary> /// Attaches this child object's definition to its parent's definition. /// </summary> /// <return>The next stage of the parent object's definition.</return> RegistryTask.Definition.ISourceTriggerDefinition Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResourceActions.IAttachable<RegistryTask.Definition.ISourceTriggerDefinition>.Attach() { return this.Attach(); } /// <summary> /// Begins an update for a child resource. /// This is the beginning of the builder pattern used to update child resources /// The final method completing the update and continue /// the actual parent resource update process in Azure is Settable.parent(). /// </summary> /// <return>The stage of parent resource update.</return> RegistryTask.Update.IUpdate Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResourceActions.ISettable<RegistryTask.Update.IUpdate>.Parent() { return this.Parent(); } /// <summary> /// The function that specifies the task has a cache. /// </summary> /// <param name="enabled">Whether caching is enabled.</param> /// <return>The next stage of the container registry DockerTaskStep update.</return> RegistryDockerTaskStep.Update.IUpdate RegistryDockerTaskStep.Update.ICache.WithCacheEnabled(bool enabled) { return this.WithCacheEnabled(enabled); } /// <summary> /// The function that specifies the use of a cache based on user input parameter. /// </summary> /// <param name="enabled">Whether caching will be enabled.</param> /// <return>The next step of the container registry DockerTaskStep definition.</return> RegistryDockerTaskStep.Definition.IDockerTaskStepAttachable RegistryDockerTaskStep.Definition.IDockerTaskStepAttachable.WithCacheEnabled(bool enabled) { return this.WithCacheEnabled(enabled); } /// <summary> /// The function that specifies the path to the Docker file. /// </summary> /// <param name="path">The path to the Docker file.</param> /// <return>The next stage of the container registry DockerTaskStep definition.</return> RegistryDockerTaskStep.Definition.IDockerTaskStepAttachable RegistryDockerTaskStep.Definition.IDockerFilePath.WithDockerFilePath(string path) { return this.WithDockerFilePath(path); } /// <summary> /// The function that specifies the path to the Docker file. /// </summary> /// <param name="path">The path to the Docker file.</param> /// <return>The next stage of the container registry DockerTaskStep update.</return> RegistryDockerTaskStep.Update.IUpdate RegistryDockerTaskStep.Update.IDockerFilePath.WithDockerFilePath(string path) { return this.WithDockerFilePath(path); } /// <summary> /// The function that specifies the image names. /// </summary> /// <param name="imageNames">The list of the names of the images.</param> /// <return>The next stage of the container registry DockerTaskStep update.</return> RegistryDockerTaskStep.Update.IUpdate RegistryDockerTaskStep.Update.IImageNames.WithImageNames(IList<string> imageNames) { return this.WithImageNames(imageNames); } /// <summary> /// The function that specifies the list of image names. /// </summary> /// <param name="imageNames">The image names.</param> /// <return>The next step of the container registry DockerTaskStep definition.</return> RegistryDockerTaskStep.Definition.IDockerTaskStepAttachable RegistryDockerTaskStep.Definition.IDockerTaskStepAttachable.WithImageNames(IList<string> imageNames) { return this.WithImageNames(imageNames); } /// <summary> /// The function that specifies the overriding argument and what it will override. /// </summary> /// <param name="name">The name of the value to be overridden.</param> /// <param name="overridingArgument">The content of the overriding argument.</param> /// <return>The next stage of the container Docker task step update.</return> RegistryDockerTaskStep.Update.IUpdate RegistryDockerTaskStep.Update.IOverridingArgumentUpdate.WithOverridingArgument(string name, OverridingArgument overridingArgument) { return this.WithOverridingArgument(name, overridingArgument); } /// <summary> /// The function that specifies the overriding argument and what it will override. /// </summary> /// <param name="name">The name of the value to be overridden.</param> /// <param name="overridingArgument">The content of the overriding argument.</param> /// <return>The next stage of the container Docker task step definition.</return> RegistryDockerTaskStep.Definition.IDockerTaskStepAttachable RegistryDockerTaskStep.Definition.IDockerTaskStepAttachable.WithOverridingArgument(string name, OverridingArgument overridingArgument) { return this.WithOverridingArgument(name, overridingArgument); } /// <summary> /// The function that specifies the overriding arguments and what they will override. /// </summary> /// <param name="overridingArguments">Map with key of the name of the value to be overridden and value OverridingArgument specifying the content of the overriding argument.</param> /// <return>The next stage of the container Docker task step update.</return> RegistryDockerTaskStep.Update.IUpdate RegistryDockerTaskStep.Update.IOverridingArgumentUpdate.WithOverridingArguments(IDictionary<string,Microsoft.Azure.Management.ContainerRegistry.Fluent.OverridingArgument> overridingArguments) { return this.WithOverridingArguments(overridingArguments); } /// <summary> /// The function that specifies the overriding arguments and what they will override. /// </summary> /// <param name="overridingArguments">Map with key of the name of the value to be overridden and value OverridingArgument specifying the content of the overriding argument.</param> /// <return>The next stage of the container Docker task step definition.</return> RegistryDockerTaskStep.Definition.IDockerTaskStepAttachable RegistryDockerTaskStep.Definition.IDockerTaskStepAttachable.WithOverridingArguments(IDictionary<string,Microsoft.Azure.Management.ContainerRegistry.Fluent.OverridingArgument> overridingArguments) { return this.WithOverridingArguments(overridingArguments); } /// <summary> /// The function that specifies push is enabled. /// </summary> /// <param name="enabled">Whether push is enabled.</param> /// <return>The next stage of the container registry DockerTaskStep update.</return> RegistryDockerTaskStep.Update.IUpdate RegistryDockerTaskStep.Update.IPush.WithPushEnabled(bool enabled) { return this.WithPushEnabled(enabled); } /// <summary> /// The function that enables push depending on user input parameter. /// </summary> /// <param name="enabled">Whether push will be enabled.</param> /// <return>The next step of the container registry DockerTaskStep definition.</return> RegistryDockerTaskStep.Definition.IDockerTaskStepAttachable RegistryDockerTaskStep.Definition.IDockerTaskStepAttachable.WithPushEnabled(bool enabled) { return this.WithPushEnabled(enabled); } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Algo.Candles.Compression.Algo File: RealTimeCandleBuilderSource.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Algo.Candles.Compression { using System; using System.Collections.Generic; using System.Linq; using Ecng.Collections; using Ecng.ComponentModel; using StockSharp.BusinessEntities; /// <summary> /// The base data source for <see cref="ICandleBuilder"/> which receives data from <see cref="IConnector"/>. /// </summary> /// <typeparam name="T">The source data type (for example, <see cref="Trade"/>).</typeparam> public abstract class RealTimeCandleBuilderSource<T> : ConvertableCandleBuilderSource<T> { private readonly SynchronizedDictionary<Security, CachedSynchronizedList<CandleSeries>> _registeredSeries = new SynchronizedDictionary<Security, CachedSynchronizedList<CandleSeries>>(); private readonly OrderedPriorityQueue<DateTimeOffset, CandleSeries> _seriesByDates = new OrderedPriorityQueue<DateTimeOffset, CandleSeries>(); /// <summary> /// Initializes a new instance of the <see cref="RealTimeCandleBuilderSource{T}"/>. /// </summary> /// <param name="connector">The connection through which new data will be received.</param> protected RealTimeCandleBuilderSource(IConnector connector) { if (connector == null) throw new ArgumentNullException(nameof(connector)); Connector = connector; Connector.MarketTimeChanged += OnConnectorMarketTimeChanged; } /// <summary> /// The source priority by speed (0 - the best). /// </summary> public override int SpeedPriority => 1; /// <summary> /// The connection through which new data will be received. /// </summary> public IConnector Connector { get; } /// <summary> /// To send data request. /// </summary> /// <param name="series">The candles series for which data receiving should be started.</param> /// <param name="from">The initial date from which you need to get data.</param> /// <param name="to">The final date by which you need to get data.</param> public override void Start(CandleSeries series, DateTimeOffset from, DateTimeOffset to) { if (series == null) throw new ArgumentNullException(nameof(series)); bool registerSecurity; series.IsNew = true; _registeredSeries.SafeAdd(series.Security, out registerSecurity).Add(series); if (registerSecurity) RegisterSecurity(series.Security); _seriesByDates.Add(new KeyValuePair<DateTimeOffset, CandleSeries>(to, series)); } /// <summary> /// To stop data receiving starting through <see cref="Start"/>. /// </summary> /// <param name="series">Candles series.</param> public override void Stop(CandleSeries series) { if (series == null) throw new ArgumentNullException(nameof(series)); var registeredSeries = _registeredSeries.TryGetValue(series.Security); if (registeredSeries == null) return; registeredSeries.Remove(series); if (registeredSeries.Count == 0) { UnRegisterSecurity(series.Security); _registeredSeries.Remove(series.Security); } _seriesByDates.RemoveWhere(i => i.Value == series); RaiseStopped(series); } /// <summary> /// To register the getting data for the instrument. /// </summary> /// <param name="security">Security.</param> protected abstract void RegisterSecurity(Security security); /// <summary> /// To stop the getting data for the instrument. /// </summary> /// <param name="security">Security.</param> protected abstract void UnRegisterSecurity(Security security); /// <summary> /// To get previously accumulated values. /// </summary> /// <param name="security">Security.</param> /// <returns>Accumulated values.</returns> protected abstract IEnumerable<T> GetSecurityValues(Security security); /// <summary> /// Synchronously to add new data received from <see cref="Connector"/>. /// </summary> /// <param name="values">New data.</param> protected void AddNewValues(IEnumerable<T> values) { if (_registeredSeries.Count == 0) return; foreach (var group in Convert(values).GroupBy(v => v.Security)) { var security = group.Key; var registeredSeries = _registeredSeries.TryGetValue(security); if (registeredSeries == null) continue; var seriesCache = registeredSeries.Cache; var securityValues = group.OrderBy(v => v.Time).ToArray(); foreach (var series in seriesCache) { if (series.IsNew) { RaiseProcessing(series, Convert(GetSecurityValues(security)).OrderBy(v => v.Time)); series.IsNew = false; } else { RaiseProcessing(series, securityValues); } } } } private void OnConnectorMarketTimeChanged(TimeSpan value) { if (_seriesByDates.Count == 0) return; var pair = _seriesByDates.Peek(); while (pair.Key <= Connector.CurrentTime) { _seriesByDates.Dequeue(); Stop(pair.Value); if (_seriesByDates.Count == 0) break; pair = _seriesByDates.Peek(); } } } /// <summary> /// The data source for <see cref="CandleBuilder{T}"/> which creates <see cref="ICandleBuilderSourceValue"/> from tick trades <see cref="Trade"/>. /// </summary> public class TradeCandleBuilderSource : RealTimeCandleBuilderSource<Trade> { /// <summary> /// Initializes a new instance of the <see cref="TradeCandleBuilderSource"/>. /// </summary> /// <param name="connector">The connection through which new trades will be received using the event <see cref="IConnector.NewTrades"/>.</param> public TradeCandleBuilderSource(IConnector connector) : base(connector) { Connector.NewTrades += AddNewValues; } /// <summary> /// To get time ranges for which this source of passed candles series has data. /// </summary> /// <param name="series">Candles series.</param> /// <returns>Time ranges.</returns> public override IEnumerable<Range<DateTimeOffset>> GetSupportedRanges(CandleSeries series) { if (series == null) throw new ArgumentNullException(nameof(series)); var trades = GetSecurityValues(series.Security); yield return new Range<DateTimeOffset>(trades.IsEmpty() ? Connector.CurrentTime : trades.Min(v => v.Time), DateTimeOffset.MaxValue); } /// <summary> /// To register the getting data for the instrument. /// </summary> /// <param name="security">Security.</param> protected override void RegisterSecurity(Security security) { Connector.RegisterTrades(security); } /// <summary> /// To stop the getting data for the instrument. /// </summary> /// <param name="security">Security.</param> protected override void UnRegisterSecurity(Security security) { Connector.UnRegisterTrades(security); } /// <summary> /// To get previously accumulated values. /// </summary> /// <param name="security">Security.</param> /// <returns>Accumulated values.</returns> protected override IEnumerable<Trade> GetSecurityValues(Security security) { return Connector.Trades.Filter(security); } /// <summary> /// Release resources. /// </summary> protected override void DisposeManaged() { Connector.NewTrades -= AddNewValues; base.DisposeManaged(); } } /// <summary> /// The data source for <see cref="CandleBuilder{T}"/> which creates <see cref="ICandleBuilderSourceValue"/> from the order book <see cref="MarketDepth"/>. /// </summary> public class MarketDepthCandleBuilderSource : RealTimeCandleBuilderSource<MarketDepth> { /// <summary> /// Initializes a new instance of the <see cref="MarketDepthCandleBuilderSource"/>. /// </summary> /// <param name="connector">The connection through which changed order books will be received using the event <see cref="IConnector.MarketDepthsChanged"/>.</param> public MarketDepthCandleBuilderSource(IConnector connector) : base(connector) { Connector.MarketDepthsChanged += OnMarketDepthsChanged; } /// <summary> /// To get time ranges for which this source of passed candles series has data. /// </summary> /// <param name="series">Candles series.</param> /// <returns>Time ranges.</returns> public override IEnumerable<Range<DateTimeOffset>> GetSupportedRanges(CandleSeries series) { if (series == null) throw new ArgumentNullException(nameof(series)); yield return new Range<DateTimeOffset>(Connector.CurrentTime, DateTimeOffset.MaxValue); } /// <summary> /// To register the getting data for the instrument. /// </summary> /// <param name="security">Security.</param> protected override void RegisterSecurity(Security security) { Connector.RegisterMarketDepth(security); } /// <summary> /// To stop the getting data for the instrument. /// </summary> /// <param name="security">Security.</param> protected override void UnRegisterSecurity(Security security) { Connector.UnRegisterMarketDepth(security); } /// <summary> /// To get previously accumulated values. /// </summary> /// <param name="security">Security.</param> /// <returns>Accumulated values.</returns> protected override IEnumerable<MarketDepth> GetSecurityValues(Security security) { return Enumerable.Empty<MarketDepth>(); } private void OnMarketDepthsChanged(IEnumerable<MarketDepth> depths) { AddNewValues(depths.Select(d => d.Clone())); } /// <summary> /// Release resources. /// </summary> protected override void DisposeManaged() { Connector.MarketDepthsChanged -= OnMarketDepthsChanged; base.DisposeManaged(); } } }
/* * Infoplus API * * Infoplus API. * * OpenAPI spec version: v1.0 * Contact: api@infopluscommerce.com * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Infoplus.Model { /// <summary> /// ShoppingCartConnection /// </summary> [DataContract] public partial class ShoppingCartConnection : IEquatable<ShoppingCartConnection> { /// <summary> /// Initializes a new instance of the <see cref="ShoppingCartConnection" /> class. /// </summary> [JsonConstructorAttribute] protected ShoppingCartConnection() { } /// <summary> /// Initializes a new instance of the <see cref="ShoppingCartConnection" /> class. /// </summary> /// <param name="LobId">LobId (required).</param> /// <param name="OrderSourceId">OrderSourceId (required).</param> /// <param name="IntegrationPartnerId">IntegrationPartnerId (required).</param> /// <param name="ConnectionType">ConnectionType (required).</param> /// <param name="ItemFilterId">ItemFilterId.</param> /// <param name="InfoplusSKUFieldToMap">InfoplusSKUFieldToMap (required).</param> /// <param name="ShoppingCartSKUFieldToMap">ShoppingCartSKUFieldToMap (required).</param> /// <param name="Name">Name (required).</param> /// <param name="ShoppingCartStoreURL">ShoppingCartStoreURL (required).</param> /// <param name="AccessCode">AccessCode.</param> /// <param name="AccessToken">AccessToken.</param> /// <param name="SyncOrders">SyncOrders (required) (default to false).</param> /// <param name="SyncInventory">SyncInventory (required) (default to false).</param> /// <param name="SyncTrackingData">SyncTrackingData (required) (default to false).</param> public ShoppingCartConnection(int? LobId = null, int? OrderSourceId = null, int? IntegrationPartnerId = null, string ConnectionType = null, int? ItemFilterId = null, string InfoplusSKUFieldToMap = null, string ShoppingCartSKUFieldToMap = null, string Name = null, string ShoppingCartStoreURL = null, string AccessCode = null, string AccessToken = null, bool? SyncOrders = null, bool? SyncInventory = null, bool? SyncTrackingData = null) { // to ensure "LobId" is required (not null) if (LobId == null) { throw new InvalidDataException("LobId is a required property for ShoppingCartConnection and cannot be null"); } else { this.LobId = LobId; } // to ensure "OrderSourceId" is required (not null) if (OrderSourceId == null) { throw new InvalidDataException("OrderSourceId is a required property for ShoppingCartConnection and cannot be null"); } else { this.OrderSourceId = OrderSourceId; } // to ensure "IntegrationPartnerId" is required (not null) if (IntegrationPartnerId == null) { throw new InvalidDataException("IntegrationPartnerId is a required property for ShoppingCartConnection and cannot be null"); } else { this.IntegrationPartnerId = IntegrationPartnerId; } // to ensure "ConnectionType" is required (not null) if (ConnectionType == null) { throw new InvalidDataException("ConnectionType is a required property for ShoppingCartConnection and cannot be null"); } else { this.ConnectionType = ConnectionType; } // to ensure "InfoplusSKUFieldToMap" is required (not null) if (InfoplusSKUFieldToMap == null) { throw new InvalidDataException("InfoplusSKUFieldToMap is a required property for ShoppingCartConnection and cannot be null"); } else { this.InfoplusSKUFieldToMap = InfoplusSKUFieldToMap; } // to ensure "ShoppingCartSKUFieldToMap" is required (not null) if (ShoppingCartSKUFieldToMap == null) { throw new InvalidDataException("ShoppingCartSKUFieldToMap is a required property for ShoppingCartConnection and cannot be null"); } else { this.ShoppingCartSKUFieldToMap = ShoppingCartSKUFieldToMap; } // to ensure "Name" is required (not null) if (Name == null) { throw new InvalidDataException("Name is a required property for ShoppingCartConnection and cannot be null"); } else { this.Name = Name; } // to ensure "ShoppingCartStoreURL" is required (not null) if (ShoppingCartStoreURL == null) { throw new InvalidDataException("ShoppingCartStoreURL is a required property for ShoppingCartConnection and cannot be null"); } else { this.ShoppingCartStoreURL = ShoppingCartStoreURL; } // to ensure "SyncOrders" is required (not null) if (SyncOrders == null) { throw new InvalidDataException("SyncOrders is a required property for ShoppingCartConnection and cannot be null"); } else { this.SyncOrders = SyncOrders; } // to ensure "SyncInventory" is required (not null) if (SyncInventory == null) { throw new InvalidDataException("SyncInventory is a required property for ShoppingCartConnection and cannot be null"); } else { this.SyncInventory = SyncInventory; } // to ensure "SyncTrackingData" is required (not null) if (SyncTrackingData == null) { throw new InvalidDataException("SyncTrackingData is a required property for ShoppingCartConnection and cannot be null"); } else { this.SyncTrackingData = SyncTrackingData; } this.ItemFilterId = ItemFilterId; this.AccessCode = AccessCode; this.AccessToken = AccessToken; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public int? Id { get; private set; } /// <summary> /// Gets or Sets CreateDate /// </summary> [DataMember(Name="createDate", EmitDefaultValue=false)] public DateTime? CreateDate { get; private set; } /// <summary> /// Gets or Sets ModifyDate /// </summary> [DataMember(Name="modifyDate", EmitDefaultValue=false)] public DateTime? ModifyDate { get; private set; } /// <summary> /// Gets or Sets ClientId /// </summary> [DataMember(Name="clientId", EmitDefaultValue=false)] public int? ClientId { get; private set; } /// <summary> /// Gets or Sets Nonce /// </summary> [DataMember(Name="nonce", EmitDefaultValue=false)] public string Nonce { get; private set; } /// <summary> /// Gets or Sets LobId /// </summary> [DataMember(Name="lobId", EmitDefaultValue=false)] public int? LobId { get; set; } /// <summary> /// Gets or Sets OrderSourceId /// </summary> [DataMember(Name="orderSourceId", EmitDefaultValue=false)] public int? OrderSourceId { get; set; } /// <summary> /// Gets or Sets IntegrationPartnerId /// </summary> [DataMember(Name="integrationPartnerId", EmitDefaultValue=false)] public int? IntegrationPartnerId { get; set; } /// <summary> /// Gets or Sets ConnectionType /// </summary> [DataMember(Name="connectionType", EmitDefaultValue=false)] public string ConnectionType { get; set; } /// <summary> /// Gets or Sets ItemFilterId /// </summary> [DataMember(Name="itemFilterId", EmitDefaultValue=false)] public int? ItemFilterId { get; set; } /// <summary> /// Gets or Sets InfoplusSKUFieldToMap /// </summary> [DataMember(Name="infoplusSKUFieldToMap", EmitDefaultValue=false)] public string InfoplusSKUFieldToMap { get; set; } /// <summary> /// Gets or Sets ShoppingCartSKUFieldToMap /// </summary> [DataMember(Name="shoppingCartSKUFieldToMap", EmitDefaultValue=false)] public string ShoppingCartSKUFieldToMap { get; set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Gets or Sets ShoppingCartStoreURL /// </summary> [DataMember(Name="shoppingCartStoreURL", EmitDefaultValue=false)] public string ShoppingCartStoreURL { get; set; } /// <summary> /// Gets or Sets AccessCode /// </summary> [DataMember(Name="accessCode", EmitDefaultValue=false)] public string AccessCode { get; set; } /// <summary> /// Gets or Sets AccessToken /// </summary> [DataMember(Name="accessToken", EmitDefaultValue=false)] public string AccessToken { get; set; } /// <summary> /// Gets or Sets SyncOrders /// </summary> [DataMember(Name="syncOrders", EmitDefaultValue=false)] public bool? SyncOrders { get; set; } /// <summary> /// Gets or Sets SyncInventory /// </summary> [DataMember(Name="syncInventory", EmitDefaultValue=false)] public bool? SyncInventory { get; set; } /// <summary> /// Gets or Sets SyncTrackingData /// </summary> [DataMember(Name="syncTrackingData", EmitDefaultValue=false)] public bool? SyncTrackingData { get; set; } /// <summary> /// Gets or Sets SyncInventoryLevelsLastRunTime /// </summary> [DataMember(Name="syncInventoryLevelsLastRunTime", EmitDefaultValue=false)] public DateTime? SyncInventoryLevelsLastRunTime { get; private set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ShoppingCartConnection {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" CreateDate: ").Append(CreateDate).Append("\n"); sb.Append(" ModifyDate: ").Append(ModifyDate).Append("\n"); sb.Append(" ClientId: ").Append(ClientId).Append("\n"); sb.Append(" Nonce: ").Append(Nonce).Append("\n"); sb.Append(" LobId: ").Append(LobId).Append("\n"); sb.Append(" OrderSourceId: ").Append(OrderSourceId).Append("\n"); sb.Append(" IntegrationPartnerId: ").Append(IntegrationPartnerId).Append("\n"); sb.Append(" ConnectionType: ").Append(ConnectionType).Append("\n"); sb.Append(" ItemFilterId: ").Append(ItemFilterId).Append("\n"); sb.Append(" InfoplusSKUFieldToMap: ").Append(InfoplusSKUFieldToMap).Append("\n"); sb.Append(" ShoppingCartSKUFieldToMap: ").Append(ShoppingCartSKUFieldToMap).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" ShoppingCartStoreURL: ").Append(ShoppingCartStoreURL).Append("\n"); sb.Append(" AccessCode: ").Append(AccessCode).Append("\n"); sb.Append(" AccessToken: ").Append(AccessToken).Append("\n"); sb.Append(" SyncOrders: ").Append(SyncOrders).Append("\n"); sb.Append(" SyncInventory: ").Append(SyncInventory).Append("\n"); sb.Append(" SyncTrackingData: ").Append(SyncTrackingData).Append("\n"); sb.Append(" SyncInventoryLevelsLastRunTime: ").Append(SyncInventoryLevelsLastRunTime).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as ShoppingCartConnection); } /// <summary> /// Returns true if ShoppingCartConnection instances are equal /// </summary> /// <param name="other">Instance of ShoppingCartConnection to be compared</param> /// <returns>Boolean</returns> public bool Equals(ShoppingCartConnection other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.CreateDate == other.CreateDate || this.CreateDate != null && this.CreateDate.Equals(other.CreateDate) ) && ( this.ModifyDate == other.ModifyDate || this.ModifyDate != null && this.ModifyDate.Equals(other.ModifyDate) ) && ( this.ClientId == other.ClientId || this.ClientId != null && this.ClientId.Equals(other.ClientId) ) && ( this.Nonce == other.Nonce || this.Nonce != null && this.Nonce.Equals(other.Nonce) ) && ( this.LobId == other.LobId || this.LobId != null && this.LobId.Equals(other.LobId) ) && ( this.OrderSourceId == other.OrderSourceId || this.OrderSourceId != null && this.OrderSourceId.Equals(other.OrderSourceId) ) && ( this.IntegrationPartnerId == other.IntegrationPartnerId || this.IntegrationPartnerId != null && this.IntegrationPartnerId.Equals(other.IntegrationPartnerId) ) && ( this.ConnectionType == other.ConnectionType || this.ConnectionType != null && this.ConnectionType.Equals(other.ConnectionType) ) && ( this.ItemFilterId == other.ItemFilterId || this.ItemFilterId != null && this.ItemFilterId.Equals(other.ItemFilterId) ) && ( this.InfoplusSKUFieldToMap == other.InfoplusSKUFieldToMap || this.InfoplusSKUFieldToMap != null && this.InfoplusSKUFieldToMap.Equals(other.InfoplusSKUFieldToMap) ) && ( this.ShoppingCartSKUFieldToMap == other.ShoppingCartSKUFieldToMap || this.ShoppingCartSKUFieldToMap != null && this.ShoppingCartSKUFieldToMap.Equals(other.ShoppingCartSKUFieldToMap) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.ShoppingCartStoreURL == other.ShoppingCartStoreURL || this.ShoppingCartStoreURL != null && this.ShoppingCartStoreURL.Equals(other.ShoppingCartStoreURL) ) && ( this.AccessCode == other.AccessCode || this.AccessCode != null && this.AccessCode.Equals(other.AccessCode) ) && ( this.AccessToken == other.AccessToken || this.AccessToken != null && this.AccessToken.Equals(other.AccessToken) ) && ( this.SyncOrders == other.SyncOrders || this.SyncOrders != null && this.SyncOrders.Equals(other.SyncOrders) ) && ( this.SyncInventory == other.SyncInventory || this.SyncInventory != null && this.SyncInventory.Equals(other.SyncInventory) ) && ( this.SyncTrackingData == other.SyncTrackingData || this.SyncTrackingData != null && this.SyncTrackingData.Equals(other.SyncTrackingData) ) && ( this.SyncInventoryLevelsLastRunTime == other.SyncInventoryLevelsLastRunTime || this.SyncInventoryLevelsLastRunTime != null && this.SyncInventoryLevelsLastRunTime.Equals(other.SyncInventoryLevelsLastRunTime) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.CreateDate != null) hash = hash * 59 + this.CreateDate.GetHashCode(); if (this.ModifyDate != null) hash = hash * 59 + this.ModifyDate.GetHashCode(); if (this.ClientId != null) hash = hash * 59 + this.ClientId.GetHashCode(); if (this.Nonce != null) hash = hash * 59 + this.Nonce.GetHashCode(); if (this.LobId != null) hash = hash * 59 + this.LobId.GetHashCode(); if (this.OrderSourceId != null) hash = hash * 59 + this.OrderSourceId.GetHashCode(); if (this.IntegrationPartnerId != null) hash = hash * 59 + this.IntegrationPartnerId.GetHashCode(); if (this.ConnectionType != null) hash = hash * 59 + this.ConnectionType.GetHashCode(); if (this.ItemFilterId != null) hash = hash * 59 + this.ItemFilterId.GetHashCode(); if (this.InfoplusSKUFieldToMap != null) hash = hash * 59 + this.InfoplusSKUFieldToMap.GetHashCode(); if (this.ShoppingCartSKUFieldToMap != null) hash = hash * 59 + this.ShoppingCartSKUFieldToMap.GetHashCode(); if (this.Name != null) hash = hash * 59 + this.Name.GetHashCode(); if (this.ShoppingCartStoreURL != null) hash = hash * 59 + this.ShoppingCartStoreURL.GetHashCode(); if (this.AccessCode != null) hash = hash * 59 + this.AccessCode.GetHashCode(); if (this.AccessToken != null) hash = hash * 59 + this.AccessToken.GetHashCode(); if (this.SyncOrders != null) hash = hash * 59 + this.SyncOrders.GetHashCode(); if (this.SyncInventory != null) hash = hash * 59 + this.SyncInventory.GetHashCode(); if (this.SyncTrackingData != null) hash = hash * 59 + this.SyncTrackingData.GetHashCode(); if (this.SyncInventoryLevelsLastRunTime != null) hash = hash * 59 + this.SyncInventoryLevelsLastRunTime.GetHashCode(); return hash; } } } }
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 ErrorHandling.Areas.HelpPage.ModelDescriptions; using ErrorHandling.Areas.HelpPage.Models; namespace ErrorHandling.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
//------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ namespace System.ServiceModel.Configuration { using System.Collections.Generic; using System.Configuration; using System.Reflection; using System.Runtime; using System.Security; using System.ServiceModel; using System.ServiceModel.Channels; using System.Xml; using System.Runtime.Diagnostics; public sealed partial class BindingsSection : ConfigurationSection, IConfigurationContextProviderInternal { static Configuration configuration; ConfigurationPropertyCollection properties; public BindingsSection() { } Dictionary<string, BindingCollectionElement> BindingCollectionElements { get { Dictionary<string, BindingCollectionElement> bindingCollectionElements = new Dictionary<string, BindingCollectionElement>(); foreach (ConfigurationProperty property in this.Properties) { bindingCollectionElements.Add(property.Name, this[property.Name]); } return bindingCollectionElements; } } new public BindingCollectionElement this[string binding] { get { return (BindingCollectionElement)base[binding]; } } protected override ConfigurationPropertyCollection Properties { get { if (this.properties == null) { this.properties = new ConfigurationPropertyCollection(); } this.UpdateBindingSections(); return this.properties; } } [ConfigurationProperty(ConfigurationStrings.BasicHttpBindingCollectionElementName, Options = ConfigurationPropertyOptions.None)] public BasicHttpBindingCollectionElement BasicHttpBinding { get { return (BasicHttpBindingCollectionElement)base[ConfigurationStrings.BasicHttpBindingCollectionElementName]; } } [ConfigurationProperty(ConfigurationStrings.BasicHttpsBindingCollectionElementName, Options = ConfigurationPropertyOptions.None)] public BasicHttpsBindingCollectionElement BasicHttpsBinding { get { return (BasicHttpsBindingCollectionElement)base[ConfigurationStrings.BasicHttpsBindingCollectionElementName]; } } // This property should only be called/set from BindingsSectionGroup TryAdd static Configuration Configuration { get { return BindingsSection.configuration; } set { BindingsSection.configuration = value; } } [ConfigurationProperty(ConfigurationStrings.CustomBindingCollectionElementName, Options = ConfigurationPropertyOptions.None)] public CustomBindingCollectionElement CustomBinding { get { return (CustomBindingCollectionElement)base[ConfigurationStrings.CustomBindingCollectionElementName]; } } [ConfigurationProperty(ConfigurationStrings.MsmqIntegrationBindingCollectionElementName, Options = ConfigurationPropertyOptions.None)] public MsmqIntegrationBindingCollectionElement MsmqIntegrationBinding { get { return (MsmqIntegrationBindingCollectionElement)base[ConfigurationStrings.MsmqIntegrationBindingCollectionElementName]; } } [ConfigurationProperty(ConfigurationStrings.NetHttpBindingCollectionElementName, Options = ConfigurationPropertyOptions.None)] public NetHttpBindingCollectionElement NetHttpBinding { get { return (NetHttpBindingCollectionElement)base[ConfigurationStrings.NetHttpBindingCollectionElementName]; } } [ConfigurationProperty(ConfigurationStrings.NetHttpsBindingCollectionElementName, Options = ConfigurationPropertyOptions.None)] public NetHttpsBindingCollectionElement NetHttpsBinding { get { return (NetHttpsBindingCollectionElement)base[ConfigurationStrings.NetHttpsBindingCollectionElementName]; } } [ConfigurationProperty(ConfigurationStrings.NetPeerTcpBindingCollectionElementName, Options = ConfigurationPropertyOptions.None)] [ObsoleteAttribute ("PeerChannel feature is obsolete and will be removed in the future.", false)] public NetPeerTcpBindingCollectionElement NetPeerTcpBinding { get { return (NetPeerTcpBindingCollectionElement)base[ConfigurationStrings.NetPeerTcpBindingCollectionElementName]; } } [ConfigurationProperty(ConfigurationStrings.NetMsmqBindingCollectionElementName, Options = ConfigurationPropertyOptions.None)] public NetMsmqBindingCollectionElement NetMsmqBinding { get { return (NetMsmqBindingCollectionElement)base[ConfigurationStrings.NetMsmqBindingCollectionElementName]; } } [ConfigurationProperty(ConfigurationStrings.NetNamedPipeBindingCollectionElementName, Options = ConfigurationPropertyOptions.None)] public NetNamedPipeBindingCollectionElement NetNamedPipeBinding { get { return (NetNamedPipeBindingCollectionElement)base[ConfigurationStrings.NetNamedPipeBindingCollectionElementName]; } } [ConfigurationProperty(ConfigurationStrings.NetTcpBindingCollectionElementName, Options = ConfigurationPropertyOptions.None)] public NetTcpBindingCollectionElement NetTcpBinding { get { return (NetTcpBindingCollectionElement)base[ConfigurationStrings.NetTcpBindingCollectionElementName]; } } [ConfigurationProperty(ConfigurationStrings.WSFederationHttpBindingCollectionElementName, Options = ConfigurationPropertyOptions.None)] public WSFederationHttpBindingCollectionElement WSFederationHttpBinding { get { return (WSFederationHttpBindingCollectionElement)base[ConfigurationStrings.WSFederationHttpBindingCollectionElementName]; } } [ConfigurationProperty(ConfigurationStrings.WS2007FederationHttpBindingCollectionElementName, Options = ConfigurationPropertyOptions.None)] public WS2007FederationHttpBindingCollectionElement WS2007FederationHttpBinding { get { return (WS2007FederationHttpBindingCollectionElement)base[ConfigurationStrings.WS2007FederationHttpBindingCollectionElementName]; } } [ConfigurationProperty(ConfigurationStrings.WSHttpBindingCollectionElementName, Options = ConfigurationPropertyOptions.None)] public WSHttpBindingCollectionElement WSHttpBinding { get { return (WSHttpBindingCollectionElement)base[ConfigurationStrings.WSHttpBindingCollectionElementName]; } } [ConfigurationProperty(ConfigurationStrings.WS2007HttpBindingCollectionElementName, Options = ConfigurationPropertyOptions.None)] public WS2007HttpBindingCollectionElement WS2007HttpBinding { get { return (WS2007HttpBindingCollectionElement)base[ConfigurationStrings.WS2007HttpBindingCollectionElementName]; } } [ConfigurationProperty(ConfigurationStrings.WSDualHttpBindingCollectionElementName, Options = ConfigurationPropertyOptions.None)] public WSDualHttpBindingCollectionElement WSDualHttpBinding { get { return (WSDualHttpBindingCollectionElement)base[ConfigurationStrings.WSDualHttpBindingCollectionElementName]; } } public static BindingsSection GetSection(Configuration config) { if (config == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("config"); } return (BindingsSection)config.GetSection(ConfigurationStrings.BindingsSectionGroupPath); } public List<BindingCollectionElement> BindingCollections { get { List<BindingCollectionElement> bindingCollections = new List<BindingCollectionElement>(); foreach (ConfigurationProperty property in this.Properties) { bindingCollections.Add(this[property.Name]); } return bindingCollections; } } protected override bool OnDeserializeUnrecognizedElement(string elementName, XmlReader reader) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ConfigurationErrorsException(SR.GetString(SR.ConfigBindingExtensionNotFound, ConfigurationHelpers.GetBindingsSectionPath(elementName)))); } internal static bool TryAdd(string name, Binding binding, Configuration config, out string bindingSectionName) { bool retval = false; BindingsSection.Configuration = config; try { retval = BindingsSection.TryAdd(name, binding, out bindingSectionName); } finally { BindingsSection.Configuration = null; } return retval; } internal static bool TryAdd(string name, Binding binding, out string bindingSectionName) { // TryAdd built on assumption that BindingsSectionGroup.Configuration is valid. // This should be protected at the callers site. If assumption is invalid, then // configuration system is in an indeterminate state. Need to stop in a manner that // user code can not capture. if (null == BindingsSection.Configuration) { Fx.Assert("The TryAdd(string name, Binding binding, Configuration config, out string binding) variant of this function should always be called first. The Configuration object is not set."); DiagnosticUtility.FailFast("The TryAdd(string name, Binding binding, Configuration config, out string binding) variant of this function should always be called first. The Configuration object is not set."); } bool retval = false; string outBindingSectionName = null; BindingsSection sectionGroup = BindingsSection.GetSection(BindingsSection.Configuration); sectionGroup.UpdateBindingSections(); foreach (string sectionName in sectionGroup.BindingCollectionElements.Keys) { BindingCollectionElement bindingCollectionElement = sectionGroup.BindingCollectionElements[sectionName]; // Save the custom bindings as the last choice if (!(bindingCollectionElement is CustomBindingCollectionElement)) { MethodInfo tryAddMethod = bindingCollectionElement.GetType().GetMethod("TryAdd", BindingFlags.Instance | BindingFlags.NonPublic); if (tryAddMethod != null) { retval = (bool)tryAddMethod.Invoke(bindingCollectionElement, new object[] { name, binding, BindingsSection.Configuration }); if (retval) { outBindingSectionName = sectionName; break; } } } } if (!retval) { // Much of the time, the custombinding should come out ok. CustomBindingCollectionElement customBindingSection = CustomBindingCollectionElement.GetBindingCollectionElement(); retval = customBindingSection.TryAdd(name, binding, BindingsSection.Configuration); if (retval) { outBindingSectionName = ConfigurationStrings.CustomBindingCollectionElementName; } } // This little oddity exists to make sure that the out param is assigned to before the method // exits. bindingSectionName = outBindingSectionName; return retval; } void UpdateBindingSections() { UpdateBindingSections(ConfigurationHelpers.GetEvaluationContext(this)); } [Fx.Tag.SecurityNote(Critical = "Calls UnsafeLookupCollection which elevates.", Safe = "Doesn't leak resultant config.")] [SecuritySafeCritical] internal void UpdateBindingSections(ContextInformation evaluationContext) { ExtensionElementCollection bindingExtensions = ExtensionsSection.UnsafeLookupCollection(ConfigurationStrings.BindingExtensions, evaluationContext); // Extension collections are additive only (BasicMap) and do not allow for <clear> // or <remove> tags, nor do they allow for overriding an entry. This allows us // to optimize this to only walk the binding extension collection if the counts // mismatch. if (bindingExtensions.Count != this.properties.Count) { foreach (ExtensionElement bindingExtension in bindingExtensions) { if (null != bindingExtension) { if (!this.properties.Contains(bindingExtension.Name)) { Type extensionType = Type.GetType(bindingExtension.Type, false); if (extensionType == null) { ConfigurationHelpers.TraceExtensionTypeNotFound(bindingExtension); } else { ConfigurationProperty property = new ConfigurationProperty(bindingExtension.Name, extensionType, null, ConfigurationPropertyOptions.None); this.properties.Add(property); } } } } } } [Fx.Tag.SecurityNote(Critical = "Calls UnsafeGetAssociatedBindingCollectionElement which elevates.", Safe = "Doesn't leak resultant config.")] [SecuritySafeCritical] internal static void ValidateBindingReference(string binding, string bindingConfiguration, ContextInformation evaluationContext, ConfigurationElement configurationElement) { // ValidateBindingReference built on assumption that evaluationContext is valid. // This should be protected at the callers site. If assumption is invalid, then // configuration system is in an indeterminate state. Need to stop in a manner that // user code can not capture. if (null == evaluationContext) { Fx.Assert("ValidateBindingReference() should only called with valid ContextInformation"); DiagnosticUtility.FailFast("ValidateBindingReference() should only called with valid ContextInformation"); } if (!String.IsNullOrEmpty(binding)) { BindingCollectionElement bindingCollectionElement = null; if (null != evaluationContext) { bindingCollectionElement = ConfigurationHelpers.UnsafeGetAssociatedBindingCollectionElement(evaluationContext, binding); } else { bindingCollectionElement = ConfigurationHelpers.UnsafeGetBindingCollectionElement(binding); } if (bindingCollectionElement == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(SR.GetString(SR.ConfigInvalidSection, ConfigurationHelpers.GetBindingsSectionPath(binding)), configurationElement.ElementInformation.Source, configurationElement.ElementInformation.LineNumber)); } if (!String.IsNullOrEmpty(bindingConfiguration)) { if (!bindingCollectionElement.ContainsKey(bindingConfiguration)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(SR.GetString(SR.ConfigInvalidBindingName, bindingConfiguration, ConfigurationHelpers.GetBindingsSectionPath(binding), ConfigurationStrings.BindingConfiguration), configurationElement.ElementInformation.Source, configurationElement.ElementInformation.LineNumber)); } } } } ContextInformation IConfigurationContextProviderInternal.GetEvaluationContext() { return this.EvaluationContext; } [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - the return value will be used for a security decision -- see comment in interface definition.")] ContextInformation IConfigurationContextProviderInternal.GetOriginalEvaluationContext() { Fx.Assert("Not implemented: IConfigurationContextProviderInternal.GetOriginalEvaluationContext"); return null; } } }
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: blah@cliffano.com * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; namespace Org.OpenAPITools.Models { /// <summary> /// HudsonMasterComputermonitorData /// </summary> [DataContract(Name = "HudsonMasterComputermonitorData")] public partial class HudsonMasterComputermonitorData : IEquatable<HudsonMasterComputermonitorData>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="HudsonMasterComputermonitorData" /> class. /// </summary> /// <param name="hudsonNodeMonitorsSwapSpaceMonitor">hudsonNodeMonitorsSwapSpaceMonitor.</param> /// <param name="hudsonNodeMonitorsTemporarySpaceMonitor">hudsonNodeMonitorsTemporarySpaceMonitor.</param> /// <param name="hudsonNodeMonitorsDiskSpaceMonitor">hudsonNodeMonitorsDiskSpaceMonitor.</param> /// <param name="hudsonNodeMonitorsArchitectureMonitor">hudsonNodeMonitorsArchitectureMonitor.</param> /// <param name="hudsonNodeMonitorsResponseTimeMonitor">hudsonNodeMonitorsResponseTimeMonitor.</param> /// <param name="hudsonNodeMonitorsClockMonitor">hudsonNodeMonitorsClockMonitor.</param> /// <param name="_class">_class.</param> public HudsonMasterComputermonitorData(SwapSpaceMonitorMemoryUsage2 hudsonNodeMonitorsSwapSpaceMonitor = default(SwapSpaceMonitorMemoryUsage2), DiskSpaceMonitorDescriptorDiskSpace hudsonNodeMonitorsTemporarySpaceMonitor = default(DiskSpaceMonitorDescriptorDiskSpace), DiskSpaceMonitorDescriptorDiskSpace hudsonNodeMonitorsDiskSpaceMonitor = default(DiskSpaceMonitorDescriptorDiskSpace), string hudsonNodeMonitorsArchitectureMonitor = default(string), ResponseTimeMonitorData hudsonNodeMonitorsResponseTimeMonitor = default(ResponseTimeMonitorData), ClockDifference hudsonNodeMonitorsClockMonitor = default(ClockDifference), string _class = default(string)) { this.HudsonNodeMonitorsSwapSpaceMonitor = hudsonNodeMonitorsSwapSpaceMonitor; this.HudsonNodeMonitorsTemporarySpaceMonitor = hudsonNodeMonitorsTemporarySpaceMonitor; this.HudsonNodeMonitorsDiskSpaceMonitor = hudsonNodeMonitorsDiskSpaceMonitor; this.HudsonNodeMonitorsArchitectureMonitor = hudsonNodeMonitorsArchitectureMonitor; this.HudsonNodeMonitorsResponseTimeMonitor = hudsonNodeMonitorsResponseTimeMonitor; this.HudsonNodeMonitorsClockMonitor = hudsonNodeMonitorsClockMonitor; this.Class = _class; } /// <summary> /// Gets or Sets HudsonNodeMonitorsSwapSpaceMonitor /// </summary> [DataMember(Name = "hudson.node_monitors.SwapSpaceMonitor", EmitDefaultValue = false)] public SwapSpaceMonitorMemoryUsage2 HudsonNodeMonitorsSwapSpaceMonitor { get; set; } /// <summary> /// Gets or Sets HudsonNodeMonitorsTemporarySpaceMonitor /// </summary> [DataMember(Name = "hudson.node_monitors.TemporarySpaceMonitor", EmitDefaultValue = false)] public DiskSpaceMonitorDescriptorDiskSpace HudsonNodeMonitorsTemporarySpaceMonitor { get; set; } /// <summary> /// Gets or Sets HudsonNodeMonitorsDiskSpaceMonitor /// </summary> [DataMember(Name = "hudson.node_monitors.DiskSpaceMonitor", EmitDefaultValue = false)] public DiskSpaceMonitorDescriptorDiskSpace HudsonNodeMonitorsDiskSpaceMonitor { get; set; } /// <summary> /// Gets or Sets HudsonNodeMonitorsArchitectureMonitor /// </summary> [DataMember(Name = "hudson.node_monitors.ArchitectureMonitor", EmitDefaultValue = false)] public string HudsonNodeMonitorsArchitectureMonitor { get; set; } /// <summary> /// Gets or Sets HudsonNodeMonitorsResponseTimeMonitor /// </summary> [DataMember(Name = "hudson.node_monitors.ResponseTimeMonitor", EmitDefaultValue = false)] public ResponseTimeMonitorData HudsonNodeMonitorsResponseTimeMonitor { get; set; } /// <summary> /// Gets or Sets HudsonNodeMonitorsClockMonitor /// </summary> [DataMember(Name = "hudson.node_monitors.ClockMonitor", EmitDefaultValue = false)] public ClockDifference HudsonNodeMonitorsClockMonitor { get; set; } /// <summary> /// Gets or Sets Class /// </summary> [DataMember(Name = "_class", EmitDefaultValue = false)] public string Class { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class HudsonMasterComputermonitorData {\n"); sb.Append(" HudsonNodeMonitorsSwapSpaceMonitor: ").Append(HudsonNodeMonitorsSwapSpaceMonitor).Append("\n"); sb.Append(" HudsonNodeMonitorsTemporarySpaceMonitor: ").Append(HudsonNodeMonitorsTemporarySpaceMonitor).Append("\n"); sb.Append(" HudsonNodeMonitorsDiskSpaceMonitor: ").Append(HudsonNodeMonitorsDiskSpaceMonitor).Append("\n"); sb.Append(" HudsonNodeMonitorsArchitectureMonitor: ").Append(HudsonNodeMonitorsArchitectureMonitor).Append("\n"); sb.Append(" HudsonNodeMonitorsResponseTimeMonitor: ").Append(HudsonNodeMonitorsResponseTimeMonitor).Append("\n"); sb.Append(" HudsonNodeMonitorsClockMonitor: ").Append(HudsonNodeMonitorsClockMonitor).Append("\n"); sb.Append(" Class: ").Append(Class).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as HudsonMasterComputermonitorData); } /// <summary> /// Returns true if HudsonMasterComputermonitorData instances are equal /// </summary> /// <param name="input">Instance of HudsonMasterComputermonitorData to be compared</param> /// <returns>Boolean</returns> public bool Equals(HudsonMasterComputermonitorData input) { if (input == null) return false; return ( this.HudsonNodeMonitorsSwapSpaceMonitor == input.HudsonNodeMonitorsSwapSpaceMonitor || (this.HudsonNodeMonitorsSwapSpaceMonitor != null && this.HudsonNodeMonitorsSwapSpaceMonitor.Equals(input.HudsonNodeMonitorsSwapSpaceMonitor)) ) && ( this.HudsonNodeMonitorsTemporarySpaceMonitor == input.HudsonNodeMonitorsTemporarySpaceMonitor || (this.HudsonNodeMonitorsTemporarySpaceMonitor != null && this.HudsonNodeMonitorsTemporarySpaceMonitor.Equals(input.HudsonNodeMonitorsTemporarySpaceMonitor)) ) && ( this.HudsonNodeMonitorsDiskSpaceMonitor == input.HudsonNodeMonitorsDiskSpaceMonitor || (this.HudsonNodeMonitorsDiskSpaceMonitor != null && this.HudsonNodeMonitorsDiskSpaceMonitor.Equals(input.HudsonNodeMonitorsDiskSpaceMonitor)) ) && ( this.HudsonNodeMonitorsArchitectureMonitor == input.HudsonNodeMonitorsArchitectureMonitor || (this.HudsonNodeMonitorsArchitectureMonitor != null && this.HudsonNodeMonitorsArchitectureMonitor.Equals(input.HudsonNodeMonitorsArchitectureMonitor)) ) && ( this.HudsonNodeMonitorsResponseTimeMonitor == input.HudsonNodeMonitorsResponseTimeMonitor || (this.HudsonNodeMonitorsResponseTimeMonitor != null && this.HudsonNodeMonitorsResponseTimeMonitor.Equals(input.HudsonNodeMonitorsResponseTimeMonitor)) ) && ( this.HudsonNodeMonitorsClockMonitor == input.HudsonNodeMonitorsClockMonitor || (this.HudsonNodeMonitorsClockMonitor != null && this.HudsonNodeMonitorsClockMonitor.Equals(input.HudsonNodeMonitorsClockMonitor)) ) && ( this.Class == input.Class || (this.Class != null && this.Class.Equals(input.Class)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.HudsonNodeMonitorsSwapSpaceMonitor != null) hashCode = hashCode * 59 + this.HudsonNodeMonitorsSwapSpaceMonitor.GetHashCode(); if (this.HudsonNodeMonitorsTemporarySpaceMonitor != null) hashCode = hashCode * 59 + this.HudsonNodeMonitorsTemporarySpaceMonitor.GetHashCode(); if (this.HudsonNodeMonitorsDiskSpaceMonitor != null) hashCode = hashCode * 59 + this.HudsonNodeMonitorsDiskSpaceMonitor.GetHashCode(); if (this.HudsonNodeMonitorsArchitectureMonitor != null) hashCode = hashCode * 59 + this.HudsonNodeMonitorsArchitectureMonitor.GetHashCode(); if (this.HudsonNodeMonitorsResponseTimeMonitor != null) hashCode = hashCode * 59 + this.HudsonNodeMonitorsResponseTimeMonitor.GetHashCode(); if (this.HudsonNodeMonitorsClockMonitor != null) hashCode = hashCode * 59 + this.HudsonNodeMonitorsClockMonitor.GetHashCode(); if (this.Class != null) hashCode = hashCode * 59 + this.Class.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
using NUnit.Framework; using System; using System.Collections.Generic; using System.Globalization; #if net452 using System.Threading; #endif using System.Threading.Tasks; namespace Braintree.Tests.Integration { [TestFixture] public class SettlementBatchSummaryIntegrationTest { private BraintreeGateway gateway; [SetUp] public void Setup() { gateway = new BraintreeGateway { Environment = Environment.DEVELOPMENT, MerchantId = "integration_merchant_id", PublicKey = "integration_public_key", PrivateKey = "integration_private_key" }; } [Test] public void Generate_ReturnsAnEmptyCollectionIfThereIsNoData() { Result<SettlementBatchSummary> result = gateway.SettlementBatchSummary.Generate(DateTime.Parse("1979-01-01")); Assert.AreEqual(0, result.Target.Records.Count); } [Test] public void Generate_ReturnsTransactionsSettledOnAGivenDay() { TransactionRequest request = new TransactionRequest { Amount = 1000M, CreditCard = new TransactionCreditCardRequest { Number = "4111111111111111", ExpirationDate = "05/2012", CardholderName = "Tom Smith", }, Options = new TransactionOptionsRequest { SubmitForSettlement = true }, }; Transaction transaction = gateway.Transaction.Sale(request).Target; Transaction settlementResult = gateway.TestTransaction.Settle(transaction.Id); var settlementDate = settlementResult.SettlementBatchId.Substring(0,10); var result = gateway.SettlementBatchSummary.Generate(System.DateTime.Parse(settlementDate)); var visas = new List<IDictionary<string,string>>(); foreach (var row in result.Target.Records) { if (CreditCardCardType.VISA.GetDescription().Equals(row["card_type"])) { visas.Add(row); } } Assert.IsTrue(visas.Count >= 1); } [Test] #if netcore public async Task GenerateAsync_ReturnsTransactionsSettledOnAGivenDay() #else public void GenerateAsync_ReturnsTransactionsSettledOnAGivenDay() { Task.Run(async () => #endif { TransactionRequest request = new TransactionRequest { Amount = 1000M, CreditCard = new TransactionCreditCardRequest { Number = "5555555555554444", ExpirationDate = "05/2012", CardholderName = "Jane Smith", }, Options = new TransactionOptionsRequest { SubmitForSettlement = true }, }; Result<Transaction> transactionResult = await gateway.Transaction.SaleAsync(request); Transaction transaction = transactionResult.Target; Transaction settlementResult = await gateway.TestTransaction.SettleAsync(transaction.Id); var settlementDate = settlementResult.SettlementBatchId.Substring(0,10); var result = await gateway.SettlementBatchSummary.GenerateAsync(System.DateTime.Parse(settlementDate)); var mastercards = new List<IDictionary<string,string>>(); foreach (var row in result.Target.Records) { if (CreditCardCardType.MASTER_CARD.GetDescription().Equals(row["card_type"])) { mastercards.Add(row); } } Assert.IsTrue(mastercards.Count >= 1); } #if net452 ).GetAwaiter().GetResult(); } #endif [Test] public void Generate_AcceptsDatesInNonUSFormats() { #if netcore CultureInfo originalCulture = CultureInfo.CurrentCulture; CultureInfo australianCulture = new CultureInfo("en-AU"); CultureInfo.CurrentCulture = australianCulture; #else CultureInfo originalCulture = Thread.CurrentThread.CurrentCulture; CultureInfo australianCulture = new CultureInfo("en-AU"); Thread.CurrentThread.CurrentCulture = australianCulture; #endif DateTime date = new DateTime(2014, 8, 20); var result = gateway.SettlementBatchSummary.Generate(date); Assert.IsTrue(result.IsSuccess()); #if netcore Assert.AreEqual(australianCulture, CultureInfo.CurrentCulture); CultureInfo.CurrentCulture = originalCulture; #else Assert.AreEqual(australianCulture, Thread.CurrentThread.CurrentCulture); Thread.CurrentThread.CurrentCulture = originalCulture; #endif } [Test] public void Generate_CanBeGroupedByACustomField() { TransactionRequest request = new TransactionRequest { Amount = 1000M, CreditCard = new TransactionCreditCardRequest { Number = "4111111111111111", ExpirationDate = "05/2012", CardholderName = "Tom Smith", }, Options = new TransactionOptionsRequest { SubmitForSettlement = true }, CustomFields = new Dictionary<string, string> { { "store_me", "custom value" } } }; Transaction transaction = gateway.Transaction.Sale(request).Target; Transaction settlementResult = gateway.TestTransaction.Settle(transaction.Id); var settlementDate = settlementResult.SettlementBatchId.Substring(0,10); var result = gateway.SettlementBatchSummary.Generate(System.DateTime.Parse(settlementDate), "store_me"); var customValues = new List<IDictionary<string, string>>(); foreach (var row in result.Target.Records) { if ("custom value".Equals(row["store_me"])) { customValues.Add(row); } } Assert.IsTrue(customValues.Count >= 1); } [Test] #if netcore public async Task GenerateAsync_CanBeGroupedByACustomField() #else public void GenerateAsync_CanBeGroupedByACustomField() { Task.Run(async () => #endif { TransactionRequest request = new TransactionRequest { Amount = 1000M, CreditCard = new TransactionCreditCardRequest { Number = "5555555555554444", ExpirationDate = "05/2012", CardholderName = "Jane Smith", }, Options = new TransactionOptionsRequest { SubmitForSettlement = true }, CustomFields = new Dictionary<string, string> { { "store_me", "custom value async" } } }; Result<Transaction> transactionResult = await gateway.Transaction.SaleAsync(request); Transaction transaction = transactionResult.Target; Transaction settlementResult = await gateway.TestTransaction.SettleAsync(transaction.Id); var settlementDate = settlementResult.SettlementBatchId.Substring(0,10); var result = await gateway.SettlementBatchSummary.GenerateAsync(System.DateTime.Parse(settlementDate), "store_me"); var customValues = new List<IDictionary<string, string>>(); foreach (var row in result.Target.Records) { if ("custom value async".Equals(row["store_me"])) { customValues.Add(row); } } Assert.AreEqual(1, customValues.Count); } #if net452 ).GetAwaiter().GetResult(); } #endif } }
// Visual Studio Shared Project // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.IO; using System.Runtime.InteropServices; using Microsoft.Build.Construction; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudioTools.Infrastructure; using MSBuild = Microsoft.Build.Evaluation; namespace Microsoft.VisualStudioTools.Project { /// <summary> /// Creates projects within the solution /// </summary> public abstract class ProjectFactory : FlavoredProjectFactoryBase, #if DEV11_OR_LATER IVsAsynchronousProjectCreate, IVsProjectUpgradeViaFactory4, #endif IVsProjectUpgradeViaFactory { #region fields private System.IServiceProvider site; /// <summary> /// The msbuild engine that we are going to use. /// </summary> private MSBuild.ProjectCollection buildEngine; /// <summary> /// The msbuild project for the project file. /// </summary> private MSBuild.Project buildProject; #if DEV11_OR_LATER private readonly Lazy<IVsTaskSchedulerService> taskSchedulerService; #endif // (See GetSccInfo below.) // When we upgrade a project, we need to cache the SCC info in case // somebody calls to ask for it via GetSccInfo. // We only need to know about the most recently upgraded project, and // can fail for other projects. private string _cachedSccProject; private string _cachedSccProjectName, _cachedSccAuxPath, _cachedSccLocalPath, _cachedSccProvider; #endregion #region properties [Obsolete("Use Site instead")] protected Microsoft.VisualStudio.Shell.Package Package { get { return (Microsoft.VisualStudio.Shell.Package)this.site; } } protected internal System.IServiceProvider Site { get { return this.site; } internal set { this.site = value; } } #endregion #region ctor [Obsolete("Provide an IServiceProvider instead of a package")] protected ProjectFactory(Microsoft.VisualStudio.Shell.Package package) : this((IServiceProvider)package) { } protected ProjectFactory(IServiceProvider serviceProvider) : base(serviceProvider) { this.site = serviceProvider; this.buildEngine = MSBuild.ProjectCollection.GlobalProjectCollection; #if DEV11_OR_LATER this.taskSchedulerService = new Lazy<IVsTaskSchedulerService>(() => Site.GetService(typeof(SVsTaskSchedulerService)) as IVsTaskSchedulerService); #endif } #endregion #region abstract methods internal abstract ProjectNode CreateProject(); #endregion #region overriden methods /// <summary> /// Rather than directly creating the project, ask VS to initate the process of /// creating an aggregated project in case we are flavored. We will be called /// on the IVsAggregatableProjectFactory to do the real project creation. /// </summary> /// <param name="fileName">Project file</param> /// <param name="location">Path of the project</param> /// <param name="name">Project Name</param> /// <param name="flags">Creation flags</param> /// <param name="projectGuid">Guid of the project</param> /// <param name="project">Project that end up being created by this method</param> /// <param name="canceled">Was the project creation canceled</param> protected override void CreateProject(string fileName, string location, string name, uint flags, ref Guid projectGuid, out IntPtr project, out int canceled) { using (new DebugTimer("CreateProject")) { project = IntPtr.Zero; canceled = 0; // Get the list of GUIDs from the project/template string guidsList = this.ProjectTypeGuids(fileName); // Launch the aggregate creation process (we should be called back on our IVsAggregatableProjectFactoryCorrected implementation) IVsCreateAggregateProject aggregateProjectFactory = (IVsCreateAggregateProject)this.Site.GetService(typeof(SVsCreateAggregateProject)); int hr = aggregateProjectFactory.CreateAggregateProject(guidsList, fileName, location, name, flags, ref projectGuid, out project); if (hr == VSConstants.E_ABORT) canceled = 1; ErrorHandler.ThrowOnFailure(hr); this.buildProject = null; } } /// <summary> /// Instantiate the project class, but do not proceed with the /// initialization just yet. /// Delegate to CreateProject implemented by the derived class. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "The global property handles is instantiated here and used in the project node that will Dispose it")] protected override object PreCreateForOuter(IntPtr outerProjectIUnknown) { Utilities.CheckNotNull(this.buildProject, "The build project should have been initialized before calling PreCreateForOuter."); // Please be very carefull what is initialized here on the ProjectNode. Normally this should only instantiate and return a project node. // The reason why one should very carefully add state to the project node here is that at this point the aggregation has not yet been created and anything that would cause a CCW for the project to be created would cause the aggregation to fail // Our reasoning is that there is no other place where state on the project node can be set that is known by the Factory and has to execute before the Load method. ProjectNode node = this.CreateProject(); Utilities.CheckNotNull(node, "The project failed to be created"); node.BuildEngine = this.buildEngine; node.BuildProject = this.buildProject; return node; } /// <summary> /// Retrives the list of project guids from the project file. /// If you don't want your project to be flavorable, override /// to only return your project factory Guid: /// return this.GetType().GUID.ToString("B"); /// </summary> /// <param name="file">Project file to look into to find the Guid list</param> /// <returns>List of semi-colon separated GUIDs</returns> protected override string ProjectTypeGuids(string file) { // Load the project so we can extract the list of GUIDs this.buildProject = Utilities.ReinitializeMsBuildProject(this.buildEngine, file, this.buildProject); // Retrieve the list of GUIDs, if it is not specify, make it our GUID string guids = buildProject.GetPropertyValue(ProjectFileConstants.ProjectTypeGuids); if (String.IsNullOrEmpty(guids)) guids = this.GetType().GUID.ToString("B"); return guids; } #endregion #if DEV11_OR_LATER public virtual bool CanCreateProjectAsynchronously(ref Guid rguidProjectID, string filename, uint flags) { return true; } public void OnBeforeCreateProjectAsync(ref Guid rguidProjectID, string filename, string location, string pszName, uint flags) { } public IVsTask CreateProjectAsync(ref Guid rguidProjectID, string filename, string location, string pszName, uint flags) { Guid iid = typeof(IVsHierarchy).GUID; return VsTaskLibraryHelper.CreateAndStartTask(taskSchedulerService.Value, VsTaskRunContext.UIThreadBackgroundPriority, VsTaskLibraryHelper.CreateTaskBody(() => { IntPtr project; int cancelled; CreateProject(filename, location, pszName, flags, ref iid, out project, out cancelled); if (cancelled != 0) { throw new OperationCanceledException(); } return Marshal.GetObjectForIUnknown(project); })); } #endif #region Project Upgrades /// <summary> /// Override this method to upgrade project files. /// </summary> /// <param name="projectXml"> /// The XML of the project file being upgraded. This may be modified /// directly or replaced with a new element. /// </param> /// <param name="userProjectXml"> /// The XML of the user file being upgraded. This may be modified /// directly or replaced with a new element. /// /// If there is no user file before upgrading, this may be null. If it /// is non-null on return, the file is created. /// </param> /// <param name="log"> /// Callback to log messages. These messages will be added to the /// migration log that is displayed after upgrading completes. /// </param> protected virtual void UpgradeProject( ref ProjectRootElement projectXml, ref ProjectRootElement userProjectXml, Action<__VSUL_ERRORLEVEL, string> log ) { } /// <summary> /// Determines whether a project needs to be upgraded. /// </summary> /// <param name="projectXml"> /// The XML of the project file being upgraded. /// </param> /// <param name="userProjectXml"> /// The XML of the user file being upgraded, or null if no user file /// exists. /// </param> /// <param name="log"> /// Callback to log messages. These messages will be added to the /// migration log that is displayed after upgrading completes. /// </param> /// <param name="projectFactory"> /// The project factory that will be used. This may be replaced with /// another Guid if a new project factory should be used to upgrade the /// project. /// </param> /// <param name="backupSupport"> /// The level of backup support requested for the project. By default, /// the project file (and user file, if any) will be copied alongside /// the originals with ".old" added to the filenames. /// </param> /// <returns> /// The form of upgrade required. /// </returns> protected virtual ProjectUpgradeState UpgradeProjectCheck( ProjectRootElement projectXml, ProjectRootElement userProjectXml, Action<__VSUL_ERRORLEVEL, string> log, ref Guid projectFactory, ref __VSPPROJECTUPGRADEVIAFACTORYFLAGS backupSupport ) { return ProjectUpgradeState.NotNeeded; } class UpgradeLogger { private readonly string _projectFile; private readonly string _projectName; private readonly IVsUpgradeLogger _logger; public UpgradeLogger(string projectFile, IVsUpgradeLogger logger) { _projectFile = projectFile; _projectName = Path.GetFileNameWithoutExtension(projectFile); _logger = logger; } public void Log(__VSUL_ERRORLEVEL level, string text) { if (_logger != null) { ErrorHandler.ThrowOnFailure(_logger.LogMessage((uint)level, _projectName, _projectFile, text)); } } } int IVsProjectUpgradeViaFactory.GetSccInfo( string bstrProjectFileName, out string pbstrSccProjectName, out string pbstrSccAuxPath, out string pbstrSccLocalPath, out string pbstrProvider ) { if (string.Equals(_cachedSccProject, bstrProjectFileName, StringComparison.OrdinalIgnoreCase)) { pbstrSccProjectName = _cachedSccProjectName; pbstrSccAuxPath = _cachedSccAuxPath; pbstrSccLocalPath = _cachedSccLocalPath; pbstrProvider = _cachedSccProvider; return VSConstants.S_OK; } pbstrSccProjectName = null; pbstrSccAuxPath = null; pbstrSccLocalPath = null; pbstrProvider = null; return VSConstants.E_FAIL; } int IVsProjectUpgradeViaFactory.UpgradeProject( string bstrFileName, uint fUpgradeFlag, string bstrCopyLocation, out string pbstrUpgradedFullyQualifiedFileName, IVsUpgradeLogger pLogger, out int pUpgradeRequired, out Guid pguidNewProjectFactory ) { pbstrUpgradedFullyQualifiedFileName = null; // We first run (or re-run) the upgrade check and bail out early if // there is actually no need to upgrade. uint dummy; var hr = ((IVsProjectUpgradeViaFactory)this).UpgradeProject_CheckOnly( bstrFileName, pLogger, out pUpgradeRequired, out pguidNewProjectFactory, out dummy ); if (!ErrorHandler.Succeeded(hr)) { return hr; } var logger = new UpgradeLogger(bstrFileName, pLogger); var backup = (__VSPPROJECTUPGRADEVIAFACTORYFLAGS)fUpgradeFlag; bool anyBackup, sxsBackup, copyBackup; anyBackup = backup.HasFlag(__VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_BACKUPSUPPORTED); if (anyBackup) { sxsBackup = backup.HasFlag(__VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_SXSBACKUP); copyBackup = !sxsBackup && backup.HasFlag(__VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_COPYBACKUP); } else { sxsBackup = copyBackup = false; } if (copyBackup) { throw new NotSupportedException("PUVFF_COPYBACKUP is not supported"); } pbstrUpgradedFullyQualifiedFileName = bstrFileName; if (pUpgradeRequired == 0 && !copyBackup) { // No upgrade required, and no backup required. logger.Log(__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, SR.GetString(SR.UpgradeNotRequired)); return VSConstants.S_OK; } try { UpgradeLogger logger2 = null; var userFileName = bstrFileName + ".user"; if (File.Exists(userFileName)) { logger2 = new UpgradeLogger(userFileName, pLogger); } else { userFileName = null; } if (sxsBackup) { // For SxS backups we want to put the old project file alongside // the current one. bstrCopyLocation = Path.GetDirectoryName(bstrFileName); } if (anyBackup) { var namePart = Path.GetFileNameWithoutExtension(bstrFileName); var extPart = Path.GetExtension(bstrFileName) + (sxsBackup ? ".old" : ""); var projectFileBackup = Path.Combine(bstrCopyLocation, namePart + extPart); for (int i = 1; File.Exists(projectFileBackup); ++i) { projectFileBackup = Path.Combine( bstrCopyLocation, string.Format("{0}{1}{2}", namePart, i, extPart) ); } File.Copy(bstrFileName, projectFileBackup); // Back up the .user file if there is one if (userFileName != null) { if (sxsBackup) { File.Copy( userFileName, Path.ChangeExtension(projectFileBackup, ".user.old") ); } else { File.Copy(userFileName, projectFileBackup + ".old"); } } // TODO: Implement support for backing up all files //if (copyBackup) { // - Open the project // - Inspect all Items // - Copy those items that are referenced relative to the // project file into bstrCopyLocation //} } var queryEdit = site.GetService(typeof(SVsQueryEditQuerySave)) as IVsQueryEditQuerySave2; if (queryEdit != null) { uint editVerdict; uint queryEditMoreInfo; var tagVSQueryEditFlags_QEF_AllowUnopenedProjects = (tagVSQueryEditFlags)0x80; ErrorHandler.ThrowOnFailure(queryEdit.QueryEditFiles( (uint)(tagVSQueryEditFlags.QEF_ForceEdit_NoPrompting | tagVSQueryEditFlags.QEF_DisallowInMemoryEdits | tagVSQueryEditFlags_QEF_AllowUnopenedProjects), 1, new[] { bstrFileName }, null, null, out editVerdict, out queryEditMoreInfo )); if (editVerdict != (uint)tagVSQueryEditResult.QER_EditOK) { logger.Log(__VSUL_ERRORLEVEL.VSUL_ERROR, SR.GetString(SR.UpgradeCannotCheckOutProject)); return VSConstants.E_FAIL; } // File may have been updated during checkout, so check // again whether we need to upgrade. if ((queryEditMoreInfo & (uint)tagVSQueryEditResultFlags.QER_MaybeChanged) != 0) { hr = ((IVsProjectUpgradeViaFactory)this).UpgradeProject_CheckOnly( bstrFileName, pLogger, out pUpgradeRequired, out pguidNewProjectFactory, out dummy ); if (!ErrorHandler.Succeeded(hr)) { return hr; } if (pUpgradeRequired == 0) { logger.Log(__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, SR.GetString(SR.UpgradeNotRequired)); return VSConstants.S_OK; } } } // Load the project file and user file into MSBuild as plain // XML to make it easier for subclasses. var projectXml = ProjectRootElement.Open(bstrFileName); if (projectXml == null) { throw new Exception(SR.GetString(SR.UpgradeCannotLoadProject)); } var userXml = userFileName != null ? ProjectRootElement.Open(userFileName) : null; // Invoke our virtual UpgradeProject function. If it fails, it // will throw and we will log the exception. UpgradeProject(ref projectXml, ref userXml, logger.Log); // Get the SCC info from the project file. if (projectXml != null) { _cachedSccProject = bstrFileName; _cachedSccProjectName = string.Empty; _cachedSccAuxPath = string.Empty; _cachedSccLocalPath = string.Empty; _cachedSccProvider = string.Empty; foreach (var property in projectXml.Properties) { switch (property.Name) { case ProjectFileConstants.SccProjectName: _cachedSccProjectName = property.Value; break; case ProjectFileConstants.SccAuxPath: _cachedSccAuxPath = property.Value; break; case ProjectFileConstants.SccLocalPath: _cachedSccLocalPath = property.Value; break; case ProjectFileConstants.SccProvider: _cachedSccProvider = property.Value; break; default: break; } } } // Save the updated files. if (projectXml != null) { projectXml.Save(); } if (userXml != null) { userXml.Save(); } // Need to add "Converted" (unlocalized) to the report because // the XSLT refers to it. logger.Log(__VSUL_ERRORLEVEL.VSUL_STATUSMSG, "Converted"); return VSConstants.S_OK; } catch (Exception ex) { if (ex.IsCriticalException()) { throw; } logger.Log(__VSUL_ERRORLEVEL.VSUL_ERROR, SR.GetString(SR.UnexpectedUpgradeError, ex.Message)); try { ActivityLog.LogError(GetType().FullName, ex.ToString()); } catch (InvalidOperationException) { // Cannot log to ActivityLog. This may occur if we are // outside of VS right now (for example, unit tests). System.Diagnostics.Trace.TraceError(ex.ToString()); } return VSConstants.E_FAIL; } } int IVsProjectUpgradeViaFactory.UpgradeProject_CheckOnly( string bstrFileName, IVsUpgradeLogger pLogger, out int pUpgradeRequired, out Guid pguidNewProjectFactory, out uint pUpgradeProjectCapabilityFlags ) { pUpgradeRequired = 0; pguidNewProjectFactory = Guid.Empty; if (!File.Exists(bstrFileName)) { pUpgradeProjectCapabilityFlags = 0; return VSConstants.E_INVALIDARG; } var backupSupport = __VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_BACKUPSUPPORTED | __VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_COPYBACKUP | __VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_SXSBACKUP; var logger = new UpgradeLogger(bstrFileName, pLogger); try { var projectXml = ProjectRootElement.Open(bstrFileName); var userProjectName = bstrFileName + ".user"; var userProjectXml = File.Exists(userProjectName) ? ProjectRootElement.Open(userProjectName) : null; var upgradeRequired = UpgradeProjectCheck( projectXml, userProjectXml, logger.Log, ref pguidNewProjectFactory, ref backupSupport ); if (upgradeRequired != ProjectUpgradeState.NotNeeded) { pUpgradeRequired = 1; } } catch (Exception ex) { if (ex.IsCriticalException()) { throw; } // Log the error and don't attempt to upgrade the project. logger.Log(__VSUL_ERRORLEVEL.VSUL_ERROR, SR.GetString(SR.UnexpectedUpgradeError, ex.Message)); try { ActivityLog.LogError(GetType().FullName, ex.ToString()); } catch (InvalidOperationException) { // Cannot log to ActivityLog. This may occur if we are // outside of VS right now (for example, unit tests). System.Diagnostics.Trace.TraceError(ex.ToString()); } pUpgradeRequired = 0; } pUpgradeProjectCapabilityFlags = (uint)backupSupport; // If the upgrade checker set the factory GUID to ourselves, we need // to clear it if (pguidNewProjectFactory == GetType().GUID) { pguidNewProjectFactory = Guid.Empty; } return VSConstants.S_OK; } #if DEV11_OR_LATER void IVsProjectUpgradeViaFactory4.UpgradeProject_CheckOnly( string bstrFileName, IVsUpgradeLogger pLogger, out uint pUpgradeRequired, out Guid pguidNewProjectFactory, out uint pUpgradeProjectCapabilityFlags ) { pguidNewProjectFactory = Guid.Empty; if (!File.Exists(bstrFileName)) { pUpgradeRequired = 0; pUpgradeProjectCapabilityFlags = 0; return; } var backupSupport = __VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_BACKUPSUPPORTED | __VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_COPYBACKUP | __VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_SXSBACKUP; var logger = new UpgradeLogger(bstrFileName, pLogger); try { var projectXml = ProjectRootElement.Open(bstrFileName); var userProjectName = bstrFileName + ".user"; var userProjectXml = File.Exists(userProjectName) ? ProjectRootElement.Open(userProjectName) : null; var upgradeRequired = UpgradeProjectCheck( projectXml, userProjectXml, logger.Log, ref pguidNewProjectFactory, ref backupSupport ); switch (upgradeRequired) { case ProjectUpgradeState.SafeRepair: pUpgradeRequired = (uint)__VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_SAFEREPAIR; break; case ProjectUpgradeState.UnsafeRepair: pUpgradeRequired = (uint)__VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_UNSAFEREPAIR; break; case ProjectUpgradeState.OneWayUpgrade: pUpgradeRequired = (uint)__VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_ONEWAYUPGRADE; break; case ProjectUpgradeState.Incompatible: pUpgradeRequired = (uint)__VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_INCOMPATIBLE; break; case ProjectUpgradeState.Deprecated: pUpgradeRequired = (uint)__VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_DEPRECATED; break; default: case ProjectUpgradeState.NotNeeded: pUpgradeRequired = (uint)__VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_NOREPAIR; break; } } catch (Exception ex) { if (ex.IsCriticalException()) { throw; } // Log the error and don't attempt to upgrade the project. logger.Log(__VSUL_ERRORLEVEL.VSUL_ERROR, SR.GetString(SR.UnexpectedUpgradeError, ex.Message)); try { ActivityLog.LogError(GetType().FullName, ex.ToString()); } catch (InvalidOperationException) { // Cannot log to ActivityLog. This may occur if we are // outside of VS right now (for example, unit tests). System.Diagnostics.Trace.TraceError(ex.ToString()); } pUpgradeRequired = (uint)__VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_NOREPAIR; } pUpgradeProjectCapabilityFlags = (uint)backupSupport; // If the upgrade checker set the factory GUID to ourselves, we need // to clear it if (pguidNewProjectFactory == GetType().GUID) { pguidNewProjectFactory = Guid.Empty; } } #endif #endregion } /// <summary> /// Status indicating whether a project upgrade should occur and how the /// project will be affected. /// </summary> public enum ProjectUpgradeState { /// <summary> /// No action will be taken. /// </summary> NotNeeded, /// <summary> /// The project will be upgraded without asking the user. /// </summary> SafeRepair, /// <summary> /// The project will be upgraded with the user's permission. /// </summary> UnsafeRepair, /// <summary> /// The project will be upgraded with the user's permission and they /// will be informed that the project will no longer work with earlier /// versions of Visual Studio. /// </summary> OneWayUpgrade, /// <summary> /// The project will be marked as incompatible. /// </summary> Incompatible, /// <summary> /// The project will be marked as deprecated. /// </summary> Deprecated } }
using System; using System.Collections.Generic; namespace GalaxyGen.Engine.Ai.Goap { /** * Plans what actions can be completed in order to fulfill a goal state. */ public class GoapPlanner { /** * Plan what sequence of actions can fulfill the goal. * Returns null if a plan could not be found, or a list of the actions * that must be performed, in order, to fulfill the goal. */ public Queue<GoapAction> Plan(object agent, HashSet<GoapAction> availableActions, Dictionary<string, object> worldState, Dictionary<Int64, Int64> resourceState, Dictionary<string, object> goal, Dictionary<Int64, Int64> resourceGoal) { // reset the actions so we can start fresh with them foreach (GoapAction a in availableActions) { a.doReset(); } // check what actions can run using their checkProceduralPrecondition HashSet<GoapAction> usableActions = new HashSet<GoapAction>(); foreach (GoapAction a in availableActions) { if (a.checkProceduralPrecondition(agent)) usableActions.Add(a); } // we now have all actions that can run, stored in usableActions // build up the tree and record the leaf nodes that provide a solution to the goal. List<GoapNode> leaves = new List<GoapNode>(); // build graph GoapNode start = new GoapNode(null, 0, 0, worldState, resourceState, null); bool success = buildGraph(start, leaves, usableActions, goal, resourceGoal); if (!success) { // oh no, we didn't get a plan // Console.WriteLine("NO PLAN"); return null; } // get the cheapest leaf GoapNode cheapest = null; foreach (GoapNode leaf in leaves) { if (cheapest == null) cheapest = leaf; else { if (leaf.BetterThan(cheapest)) cheapest = leaf; } } // get its node and work back through the parents List<GoapAction> result = new List<GoapAction>(); GoapNode n = cheapest; while (n != null) { if (n.action != null) { result.Insert(0, n.action); // insert the action in the front } n = n.parent; } // we now have this action list in correct order Queue<GoapAction> queue = new Queue<GoapAction>(); foreach (GoapAction a in result) { queue.Enqueue(a); } // hooray we have a plan! return queue; } /** * Returns true if at least one solution was found. * The possible paths are stored in the leaves list. Each leaf has a * 'runningCost' value where the lowest cost will be the best action * sequence. */ private bool buildGraph(GoapNode parent, List<GoapNode> leaves, HashSet<GoapAction> usableActions, Dictionary<string, object> goal, Dictionary<Int64, Int64> resourceGoal) { bool foundOne = false; // go through each action available at this node and see if we can use it here foreach (GoapAction action in usableActions) { // if the parent state has the conditions for this action's preconditions, we can use it here if (inState(action.Preconditions, parent.state)) { // apply the action's effects to the parent state Dictionary<string, object> currentState = populateState(parent.state, action.Effects); Dictionary<Int64, Int64> currentResources = populateResource(parent.resources, action.Resources); // Console.WriteLine(GoapAgent.PrettyPrint(currentState)); GoapNode node = new GoapNode(parent, parent.runningCost + action.GetCost(), parent.weight + action.GetWeight(), currentState, currentResources, action); if (inState(goal, currentState) && inResources(resourceGoal, currentResources)) { // we found a solution! leaves.Add(node); foundOne = true; } else { // not at a solution yet, so test all the remaining actions and branch out the tree HashSet<GoapAction> subset = actionSubset(usableActions, action); bool found = buildGraph(node, leaves, subset, goal, resourceGoal); if (found) foundOne = true; } } } return foundOne; } /** * Create a subset of the actions excluding the removeMe one. Creates a new set. */ private HashSet<GoapAction> actionSubset(HashSet<GoapAction> actions, GoapAction removeMe) { HashSet<GoapAction> subset = new HashSet<GoapAction>(); foreach (GoapAction a in actions) { if (!a.Equals(removeMe)) subset.Add(a); } return subset; } /** * Check that all items in 'test' are in 'state'. If just one does not match or is not there * then this returns false. */ private bool inState(Dictionary<string, object> test, Dictionary<string, object> state) { var allMatch = true; foreach (var t in test) { var match = state.ContainsKey(t.Key) && state[t.Key].Equals(t.Value); if (!match) { allMatch = false; break; } } return allMatch; } private bool inResources(Dictionary<Int64, Int64> resourceGoal, Dictionary<Int64, Int64> currentResources) { var allMatch = true; foreach (var t in resourceGoal) { var match = currentResources.ContainsKey(t.Key) && currentResources[t.Key] >= t.Value; if (!match) { allMatch = false; break; } } return allMatch; } //if there is one true relationship private bool CondRelation(Dictionary<string, object> preconditions , Dictionary<string, object> effects) { foreach (var t in preconditions) { var match = effects.ContainsKey(t.Key) && effects[t.Key].Equals(t.Value); if (match) return true; } return false; } /** * Apply the stateChange to the currentState */ private Dictionary<string, object> populateState(Dictionary<string, object> currentState, Dictionary<string, object> stateChange) { Dictionary<string, object> state = new Dictionary<string, object>(); foreach (var s in currentState) { state.Add(s.Key, s.Value); } foreach (var change in stateChange) { // if the key exists in the current state, update the Value if (state.ContainsKey(change.Key)) { state[change.Key] = change.Value; } else { state.Add(change.Key, change.Value); } } return state; } private Dictionary<Int64, Int64> populateResource(Dictionary<Int64, Int64> currentResource, Dictionary<Int64, Int64> resourceChange) { Dictionary<Int64, Int64> resources = new Dictionary<Int64, Int64>(); foreach (var res in currentResource) { resources.Add(res.Key, res.Value); } foreach (var res in resourceChange) { if (!resources.ContainsKey(res.Key)) { resources.Add(res.Key, res.Value); } else { resources[res.Key] += res.Value; } } return resources; } } }
// 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.Runtime.InteropServices; using Windows.Foundation; #pragma warning disable 436 // Redefining types from Windows.Foundation namespace Windows.UI.Xaml.Media.Media3D { // // Matrix3D is the managed projection of Windows.UI.Xaml.Media.Media3D.Matrix3D. Any // changes to the layout of this type must be exactly mirrored on the native WinRT side as well. // // Note that this type is owned by the Jupiter team. Please contact them before making any // changes here. // [StructLayout(LayoutKind.Sequential)] public struct Matrix3D : IFormattable { // Assuming this matrix has fourth column of 0,0,0,1 and isn't identity this function: // Returns false if HasInverse is false, otherwise inverts the matrix. private bool NormalizedAffineInvert() { double z20 = _m12 * _m23 - _m22 * _m13; double z10 = _m32 * _m13 - _m12 * _m33; double z00 = _m22 * _m33 - _m32 * _m23; double det = _m31 * z20 + _m21 * z10 + _m11 * z00; if (IsZero(det)) { return false; } // Compute 3x3 non-zero cofactors for the 2nd column double z21 = _m21 * _m13 - _m11 * _m23; double z11 = _m11 * _m33 - _m31 * _m13; double z01 = _m31 * _m23 - _m21 * _m33; // Compute all six 2x2 determinants of 1st two columns double y01 = _m11 * _m22 - _m21 * _m12; double y02 = _m11 * _m32 - _m31 * _m12; double y03 = _m11 * _offsetY - _offsetX * _m12; double y12 = _m21 * _m32 - _m31 * _m22; double y13 = _m21 * _offsetY - _offsetX * _m22; double y23 = _m31 * _offsetY - _offsetX * _m32; // Compute all non-zero and non-one 3x3 cofactors for 2nd // two columns double z23 = _m23 * y03 - _offsetZ * y01 - _m13 * y13; double z13 = _m13 * y23 - _m33 * y03 + _offsetZ * y02; double z03 = _m33 * y13 - _offsetZ * y12 - _m23 * y23; double z22 = y01; double z12 = -y02; double z02 = y12; double rcp = 1.0 / det; // Multiply all 3x3 cofactors by reciprocal & transpose _m11 = (z00 * rcp); _m12 = (z10 * rcp); _m13 = (z20 * rcp); _m21 = (z01 * rcp); _m22 = (z11 * rcp); _m23 = (z21 * rcp); _m31 = (z02 * rcp); _m32 = (z12 * rcp); _m33 = (z22 * rcp); _offsetX = (z03 * rcp); _offsetY = (z13 * rcp); _offsetZ = (z23 * rcp); return true; } // RETURNS true if has inverse & invert was done. Otherwise returns false & leaves matrix unchanged. private bool InvertCore() { if (IsAffine) { return NormalizedAffineInvert(); } // compute all six 2x2 determinants of 2nd two columns double y01 = _m13 * _m24 - _m23 * _m14; double y02 = _m13 * _m34 - _m33 * _m14; double y03 = _m13 * _m44 - _offsetZ * _m14; double y12 = _m23 * _m34 - _m33 * _m24; double y13 = _m23 * _m44 - _offsetZ * _m24; double y23 = _m33 * _m44 - _offsetZ * _m34; // Compute 3x3 cofactors for 1st the column double z30 = _m22 * y02 - _m32 * y01 - _m12 * y12; double z20 = _m12 * y13 - _m22 * y03 + _offsetY * y01; double z10 = _m32 * y03 - _offsetY * y02 - _m12 * y23; double z00 = _m22 * y23 - _m32 * y13 + _offsetY * y12; // Compute 4x4 determinant double det = _offsetX * z30 + _m31 * z20 + _m21 * z10 + _m11 * z00; if (IsZero(det)) { return false; } // Compute 3x3 cofactors for the 2nd column double z31 = _m11 * y12 - _m21 * y02 + _m31 * y01; double z21 = _m21 * y03 - _offsetX * y01 - _m11 * y13; double z11 = _m11 * y23 - _m31 * y03 + _offsetX * y02; double z01 = _m31 * y13 - _offsetX * y12 - _m21 * y23; // Compute all six 2x2 determinants of 1st two columns y01 = _m11 * _m22 - _m21 * _m12; y02 = _m11 * _m32 - _m31 * _m12; y03 = _m11 * _offsetY - _offsetX * _m12; y12 = _m21 * _m32 - _m31 * _m22; y13 = _m21 * _offsetY - _offsetX * _m22; y23 = _m31 * _offsetY - _offsetX * _m32; // Compute all 3x3 cofactors for 2nd two columns double z33 = _m13 * y12 - _m23 * y02 + _m33 * y01; double z23 = _m23 * y03 - _offsetZ * y01 - _m13 * y13; double z13 = _m13 * y23 - _m33 * y03 + _offsetZ * y02; double z03 = _m33 * y13 - _offsetZ * y12 - _m23 * y23; double z32 = _m24 * y02 - _m34 * y01 - _m14 * y12; double z22 = _m14 * y13 - _m24 * y03 + _m44 * y01; double z12 = _m34 * y03 - _m44 * y02 - _m14 * y23; double z02 = _m24 * y23 - _m34 * y13 + _m44 * y12; double rcp = 1.0 / det; // Multiply all 3x3 cofactors by reciprocal & transpose _m11 = (z00 * rcp); _m12 = (z10 * rcp); _m13 = (z20 * rcp); _m14 = (z30 * rcp); _m21 = (z01 * rcp); _m22 = (z11 * rcp); _m23 = (z21 * rcp); _m24 = (z31 * rcp); _m31 = (z02 * rcp); _m32 = (z12 * rcp); _m33 = (z22 * rcp); _m34 = (z32 * rcp); _offsetX = (z03 * rcp); _offsetY = (z13 * rcp); _offsetZ = (z23 * rcp); _m44 = (z33 * rcp); return true; } public Matrix3D(double m11, double m12, double m13, double m14, double m21, double m22, double m23, double m24, double m31, double m32, double m33, double m34, double offsetX, double offsetY, double offsetZ, double m44) { _m11 = m11; _m12 = m12; _m13 = m13; _m14 = m14; _m21 = m21; _m22 = m22; _m23 = m23; _m24 = m24; _m31 = m31; _m32 = m32; _m33 = m33; _m34 = m34; _offsetX = offsetX; _offsetY = offsetY; _offsetZ = offsetZ; _m44 = m44; } // the transform is identity by default // Actually fill in the fields - some (internal) code uses the fields directly for perf. private static Matrix3D s_identity = CreateIdentity(); public double M11 { get { return _m11; } set { _m11 = value; } } public double M12 { get { return _m12; } set { _m12 = value; } } public double M13 { get { return _m13; } set { _m13 = value; } } public double M14 { get { return _m14; } set { _m14 = value; } } public double M21 { get { return _m21; } set { _m21 = value; } } public double M22 { get { return _m22; } set { _m22 = value; } } public double M23 { get { return _m23; } set { _m23 = value; } } public double M24 { get { return _m24; } set { _m24 = value; } } public double M31 { get { return _m31; } set { _m31 = value; } } public double M32 { get { return _m32; } set { _m32 = value; } } public double M33 { get { return _m33; } set { _m33 = value; } } public double M34 { get { return _m34; } set { _m34 = value; } } public double OffsetX { get { return _offsetX; } set { _offsetX = value; } } public double OffsetY { get { return _offsetY; } set { _offsetY = value; } } public double OffsetZ { get { return _offsetZ; } set { _offsetZ = value; } } public double M44 { get { return _m44; } set { _m44 = value; } } public static Matrix3D Identity { get { return s_identity; } } public bool IsIdentity { get { return (_m11 == 1 && _m12 == 0 && _m13 == 0 && _m14 == 0 && _m21 == 0 && _m22 == 1 && _m23 == 0 && _m24 == 0 && _m31 == 0 && _m32 == 0 && _m33 == 1 && _m34 == 0 && _offsetX == 0 && _offsetY == 0 && _offsetZ == 0 && _m44 == 1); } } public override string ToString() { // Delegate to the internal method which implements all ToString calls. return ConvertToString(null /* format string */, null /* format provider */); } public string ToString(IFormatProvider provider) { // Delegate to the internal method which implements all ToString calls. return ConvertToString(null /* format string */, provider); } string IFormattable.ToString(string format, IFormatProvider provider) { // Delegate to the internal method which implements all ToString calls. return ConvertToString(format, provider); } private string ConvertToString(string format, IFormatProvider provider) { if (IsIdentity) { return "Identity"; } // Helper to get the numeric list separator for a given culture. char separator = TokenizerHelper.GetNumericListSeparator(provider); return String.Format(provider, "{1:" + format + "}{0}{2:" + format + "}{0}{3:" + format + "}{0}{4:" + format + "}{0}{5:" + format + "}{0}{6:" + format + "}{0}{7:" + format + "}{0}{8:" + format + "}{0}{9:" + format + "}{0}{10:" + format + "}{0}{11:" + format + "}{0}{12:" + format + "}{0}{13:" + format + "}{0}{14:" + format + "}{0}{15:" + format + "}{0}{16:" + format + "}", separator, _m11, _m12, _m13, _m14, _m21, _m22, _m23, _m24, _m31, _m32, _m33, _m34, _offsetX, _offsetY, _offsetZ, _m44); } public override int GetHashCode() { // Perform field-by-field XOR of HashCodes return M11.GetHashCode() ^ M12.GetHashCode() ^ M13.GetHashCode() ^ M14.GetHashCode() ^ M21.GetHashCode() ^ M22.GetHashCode() ^ M23.GetHashCode() ^ M24.GetHashCode() ^ M31.GetHashCode() ^ M32.GetHashCode() ^ M33.GetHashCode() ^ M34.GetHashCode() ^ OffsetX.GetHashCode() ^ OffsetY.GetHashCode() ^ OffsetZ.GetHashCode() ^ M44.GetHashCode(); } public override bool Equals(object o) { return o is Matrix3D && Matrix3D.Equals(this, (Matrix3D)o); } public bool Equals(Matrix3D value) { return Matrix3D.Equals(this, value); } public static bool operator ==(Matrix3D matrix1, Matrix3D matrix2) { return matrix1.M11 == matrix2.M11 && matrix1.M12 == matrix2.M12 && matrix1.M13 == matrix2.M13 && matrix1.M14 == matrix2.M14 && matrix1.M21 == matrix2.M21 && matrix1.M22 == matrix2.M22 && matrix1.M23 == matrix2.M23 && matrix1.M24 == matrix2.M24 && matrix1.M31 == matrix2.M31 && matrix1.M32 == matrix2.M32 && matrix1.M33 == matrix2.M33 && matrix1.M34 == matrix2.M34 && matrix1.OffsetX == matrix2.OffsetX && matrix1.OffsetY == matrix2.OffsetY && matrix1.OffsetZ == matrix2.OffsetZ && matrix1.M44 == matrix2.M44; } public static bool operator !=(Matrix3D matrix1, Matrix3D matrix2) { return !(matrix1 == matrix2); } public static Matrix3D operator *(Matrix3D matrix1, Matrix3D matrix2) { Matrix3D matrix3D = new Matrix3D(); matrix3D.M11 = matrix1.M11 * matrix2.M11 + matrix1.M12 * matrix2.M21 + matrix1.M13 * matrix2.M31 + matrix1.M14 * matrix2.OffsetX; matrix3D.M12 = matrix1.M11 * matrix2.M12 + matrix1.M12 * matrix2.M22 + matrix1.M13 * matrix2.M32 + matrix1.M14 * matrix2.OffsetY; matrix3D.M13 = matrix1.M11 * matrix2.M13 + matrix1.M12 * matrix2.M23 + matrix1.M13 * matrix2.M33 + matrix1.M14 * matrix2.OffsetZ; matrix3D.M14 = matrix1.M11 * matrix2.M14 + matrix1.M12 * matrix2.M24 + matrix1.M13 * matrix2.M34 + matrix1.M14 * matrix2.M44; matrix3D.M21 = matrix1.M21 * matrix2.M11 + matrix1.M22 * matrix2.M21 + matrix1.M23 * matrix2.M31 + matrix1.M24 * matrix2.OffsetX; matrix3D.M22 = matrix1.M21 * matrix2.M12 + matrix1.M22 * matrix2.M22 + matrix1.M23 * matrix2.M32 + matrix1.M24 * matrix2.OffsetY; matrix3D.M23 = matrix1.M21 * matrix2.M13 + matrix1.M22 * matrix2.M23 + matrix1.M23 * matrix2.M33 + matrix1.M24 * matrix2.OffsetZ; matrix3D.M24 = matrix1.M21 * matrix2.M14 + matrix1.M22 * matrix2.M24 + matrix1.M23 * matrix2.M34 + matrix1.M24 * matrix2.M44; matrix3D.M31 = matrix1.M31 * matrix2.M11 + matrix1.M32 * matrix2.M21 + matrix1.M33 * matrix2.M31 + matrix1.M34 * matrix2.OffsetX; matrix3D.M32 = matrix1.M31 * matrix2.M12 + matrix1.M32 * matrix2.M22 + matrix1.M33 * matrix2.M32 + matrix1.M34 * matrix2.OffsetY; matrix3D.M33 = matrix1.M31 * matrix2.M13 + matrix1.M32 * matrix2.M23 + matrix1.M33 * matrix2.M33 + matrix1.M34 * matrix2.OffsetZ; matrix3D.M34 = matrix1.M31 * matrix2.M14 + matrix1.M32 * matrix2.M24 + matrix1.M33 * matrix2.M34 + matrix1.M34 * matrix2.M44; matrix3D.OffsetX = matrix1.OffsetX * matrix2.M11 + matrix1.OffsetY * matrix2.M21 + matrix1.OffsetZ * matrix2.M31 + matrix1.M44 * matrix2.OffsetX; matrix3D.OffsetY = matrix1.OffsetX * matrix2.M12 + matrix1.OffsetY * matrix2.M22 + matrix1.OffsetZ * matrix2.M32 + matrix1.M44 * matrix2.OffsetY; matrix3D.OffsetZ = matrix1.OffsetX * matrix2.M13 + matrix1.OffsetY * matrix2.M23 + matrix1.OffsetZ * matrix2.M33 + matrix1.M44 * matrix2.OffsetZ; matrix3D.M44 = matrix1.OffsetX * matrix2.M14 + matrix1.OffsetY * matrix2.M24 + matrix1.OffsetZ * matrix2.M34 + matrix1.M44 * matrix2.M44; // matrix3D._type is not set. return matrix3D; } public bool HasInverse { get { return !IsZero(Determinant); } } public void Invert() { if (!InvertCore()) { throw new InvalidOperationException(); } } private static Matrix3D CreateIdentity() { Matrix3D matrix3D = new Matrix3D(); matrix3D.SetMatrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); return matrix3D; } private void SetMatrix(double m11, double m12, double m13, double m14, double m21, double m22, double m23, double m24, double m31, double m32, double m33, double m34, double offsetX, double offsetY, double offsetZ, double m44) { _m11 = m11; _m12 = m12; _m13 = m13; _m14 = m14; _m21 = m21; _m22 = m22; _m23 = m23; _m24 = m24; _m31 = m31; _m32 = m32; _m33 = m33; _m34 = m34; _offsetX = offsetX; _offsetY = offsetY; _offsetZ = offsetZ; _m44 = m44; } private static bool Equals(Matrix3D matrix1, Matrix3D matrix2) { return matrix1.M11.Equals(matrix2.M11) && matrix1.M12.Equals(matrix2.M12) && matrix1.M13.Equals(matrix2.M13) && matrix1.M14.Equals(matrix2.M14) && matrix1.M21.Equals(matrix2.M21) && matrix1.M22.Equals(matrix2.M22) && matrix1.M23.Equals(matrix2.M23) && matrix1.M24.Equals(matrix2.M24) && matrix1.M31.Equals(matrix2.M31) && matrix1.M32.Equals(matrix2.M32) && matrix1.M33.Equals(matrix2.M33) && matrix1.M34.Equals(matrix2.M34) && matrix1.OffsetX.Equals(matrix2.OffsetX) && matrix1.OffsetY.Equals(matrix2.OffsetY) && matrix1.OffsetZ.Equals(matrix2.OffsetZ) && matrix1.M44.Equals(matrix2.M44); } private double GetNormalizedAffineDeterminant() { double z20 = _m12 * _m23 - _m22 * _m13; double z10 = _m32 * _m13 - _m12 * _m33; double z00 = _m22 * _m33 - _m32 * _m23; return _m31 * z20 + _m21 * z10 + _m11 * z00; } private bool IsAffine { get { return (_m14 == 0.0 && _m24 == 0.0 && _m34 == 0.0 && _m44 == 1.0); } } private double Determinant { get { if (IsAffine) { return GetNormalizedAffineDeterminant(); } // compute all six 2x2 determinants of 2nd two columns double y01 = _m13 * _m24 - _m23 * _m14; double y02 = _m13 * _m34 - _m33 * _m14; double y03 = _m13 * _m44 - _offsetZ * _m14; double y12 = _m23 * _m34 - _m33 * _m24; double y13 = _m23 * _m44 - _offsetZ * _m24; double y23 = _m33 * _m44 - _offsetZ * _m34; // Compute 3x3 cofactors for 1st the column double z30 = _m22 * y02 - _m32 * y01 - _m12 * y12; double z20 = _m12 * y13 - _m22 * y03 + _offsetY * y01; double z10 = _m32 * y03 - _offsetY * y02 - _m12 * y23; double z00 = _m22 * y23 - _m32 * y13 + _offsetY * y12; return _offsetX * z30 + _m31 * z20 + _m21 * z10 + _m11 * z00; } } private static bool IsZero(double value) { return Math.Abs(value) < 10.0 * DBL_EPSILON_RELATIVE_1; } private const double DBL_EPSILON_RELATIVE_1 = 1.1102230246251567e-016; /* smallest such that 1.0+DBL_EPSILON != 1.0 */ private double _m11; private double _m12; private double _m13; private double _m14; private double _m21; private double _m22; private double _m23; private double _m24; private double _m31; private double _m32; private double _m33; private double _m34; private double _offsetX; private double _offsetY; private double _offsetZ; private double _m44; } } #pragma warning restore 436
using System; using System.Collections.Generic; using System.Linq; using System.Reactive; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Reactive.Threading.Tasks; using System.Threading.Tasks; using F2F.ReactiveNavigation.ViewModel; using F2F.Testing.Xunit.FakeItEasy; using FakeItEasy; using FluentAssertions; using Microsoft.Reactive.Testing; using Ploeh.AutoFixture; using Ploeh.AutoFixture.AutoFakeItEasy; using ReactiveUI; using ReactiveUI.Testing; using Xunit; namespace F2F.ReactiveNavigation.UnitTests { public class ReactiveViewModel_BusyIndication_Test : AutoMockFeature { [Fact] public void IsBusy_ShouldBeFalseByDefault() { new TestScheduler().With(scheduler => { var sut = Fixture.Create<ReactiveViewModel>(); sut.InitializeAsync().Schedule(scheduler); sut.IsBusy.Should().BeFalse(); }); } [Fact] public void IsBusy_ShouldBeTrueWhenNotYetInitialized() { new TestScheduler().With(scheduler => { var sut = Fixture.Create<ReactiveViewModel>(); sut.IsBusy.Should().BeTrue(); }); } [Fact] public void Task_ShouldBeTrueWhenNavigateToAsyncIsExecuting() { new TestScheduler().With(scheduler => { var navigatedToObservable = Observable .Return(Unit.Default) .Delay(TimeSpan.FromMilliseconds(100), scheduler); var task = navigatedToObservable.ToTask(); task.IsCompleted.Should().BeFalse(); scheduler.AdvanceByMs(101); task.IsCompleted.Should().BeTrue(); }); } [Fact(Skip = "Rethink this test")] public void IsBusy_ShouldBeTrueWhenNavigateToAsyncIsExecuting() { new TestScheduler().With(scheduler => { var sut = Fixture.Create<ReactiveViewModel>(); var navigatedToObservable = Observable .Return(Unit.Default) .Delay(TimeSpan.FromMilliseconds(1), scheduler); sut.WhenNavigatedTo() .DoAsync(_ => navigatedToObservable.ToTask() as Task) .Subscribe(); sut.InitializeAsync().Schedule(scheduler); for (int i = 0; i < 10; i++) { sut.NavigateTo(null); scheduler.Advance(); // schedule navigation call sut.IsBusy.Should().BeTrue(); scheduler.Advance(); // pass delay in navigatedToObservable sut.IsBusy.Should().BeFalse(); } }); } [Fact(Skip = "Rethink this test")] public void IsBusy_ShouldBeTrueWhenNavigateToAsyncWithResultIsExecuting() { new TestScheduler().With(scheduler => { var sut = Fixture.Create<ReactiveViewModel>(); var navigatedToObservable = Observable .Return(Unit.Default) .Delay(TimeSpan.FromMilliseconds(1), scheduler); sut.WhenNavigatedTo() .DoAsync(_ => navigatedToObservable.ToTask()) .Subscribe(); sut.InitializeAsync().Schedule(scheduler); for (int i = 0; i < 10; i++) { sut.NavigateTo(null); scheduler.Advance(); // schedule navigation call sut.IsBusy.Should().BeTrue(); scheduler.Advance(); // pass delay in navigatedToObservable sut.IsBusy.Should().BeFalse(); } }); } [Fact] public void IsBusy_WhenHavingOneBusyObservable_ShouldBeTrueAsLongAsBusyObservableYieldsTrue() { new TestScheduler().With(scheduler => { var sut = A.Fake<ReactiveViewModel>(); var busySubject = new Subject<bool>(); A.CallTo(() => sut.BusyObservables).Returns(new[] { busySubject }); sut.IsBusy.Should().BeTrue(); sut.InitializeAsync().Schedule(scheduler); sut.IsBusy.Should().BeFalse(); busySubject.OnNext(true); sut.IsBusy.Should().BeTrue(); busySubject.OnNext(false); sut.IsBusy.Should().BeFalse(); }); } [Fact] public void IsBusy_WhenHavingTwoBusyObservables_ShouldBeTrueAsLongAsOneBusyObservableYieldsTrue() { new TestScheduler().With(scheduler => { var sut = A.Fake<ReactiveViewModel>(); var busySubject1 = new Subject<bool>(); var busySubject2 = new Subject<bool>(); A.CallTo(() => sut.BusyObservables).Returns(new[] { busySubject1, busySubject2 }); sut.IsBusy.Should().BeTrue(); sut.InitializeAsync().Schedule(scheduler); sut.IsBusy.Should().BeFalse(); busySubject1.OnNext(true); sut.IsBusy.Should().BeTrue(); busySubject2.OnNext(true); sut.IsBusy.Should().BeTrue(); busySubject1.OnNext(false); sut.IsBusy.Should().BeTrue(); busySubject2.OnNext(false); sut.IsBusy.Should().BeFalse(); }); } [Fact(Skip = "Rethink this test")] public void IsBusy_WhenHavingTwoBusyObservables_AndNavigation_ShouldBeTrueAsLongAsOneBusyObservableYieldsTrue() { new TestScheduler().With(scheduler => { var sut = A.Fake<ReactiveViewModel>(); var busySubject1 = new Subject<bool>(); var busySubject2 = new Subject<bool>(); A.CallTo(() => sut.BusyObservables).Returns(new[] { busySubject1, busySubject2 }); var navigatedToTask = Observable .Return(Unit.Default) .Delay(TimeSpan.FromMilliseconds(2), scheduler) .ToTask(); sut.IsBusy.Should().BeTrue(); sut.WhenNavigatedTo() .DoAsync(_ => navigatedToTask) .Subscribe(); sut.InitializeAsync().Schedule(scheduler); sut.IsBusy.Should().BeFalse(); sut.NavigateTo(NavigationParameters.Empty); sut.IsBusy.Should().BeFalse(); scheduler.Advance(); // schedule navigation call start sut.IsBusy.Should().BeTrue(); scheduler.Advance(); sut.IsBusy.Should().BeFalse(); // schedule navigation call end busySubject2.OnNext(true); sut.IsBusy.Should().BeTrue(); busySubject2.OnNext(false); sut.IsBusy.Should().BeFalse(); }); } [Fact] public void IsBusy_WhenBusyObservableThrowsObservedException_ShouldPushExceptionToThrownExceptionsObservable() { new TestScheduler().With(scheduler => { var sut = A.Fake<ReactiveViewModel>(); var exception = Fixture.Create<Exception>(); var errorSubject = new Subject<bool>(); A.CallTo(() => sut.BusyObservables).Returns(new[] { errorSubject }); sut.InitializeAsync(); var busyExceptions = sut.ThrownExceptions.CreateCollection(); errorSubject.OnError(exception); scheduler.Advance(); busyExceptions.Single().Should().Be(exception); }); } [Fact] public void IsBusy_WhenBusyObservableThrowsUnobservedException_ShouldThrowDefaultExceptionAtCallSite() { new TestScheduler().With(scheduler => { var sut = A.Fake<ReactiveViewModel>(); var exception = Fixture.Create<Exception>(); var errorSubject = new Subject<bool>(); A.CallTo(() => sut.BusyObservables).Returns(new[] { errorSubject }); sut.InitializeAsync(); errorSubject.OnError(exception); scheduler .Invoking(x => x.Advance()) .ShouldThrow<Exception>() .Which .InnerException .Should() .Be(exception); }); } } }

Dataset Card for "LCC_csharp"

More Information needed

Downloads last month
28
Edit dataset card

Models trained or fine-tuned on microsoft/LCC_csharp