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: [email protected]
* 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: [email protected]
* 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);
});
}
}
}
| |
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
using System.Linq;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.TestData.LifeCycleTests;
using NUnit.TestUtilities;
namespace NUnit.Framework.Attributes
{
[TestFixture]
[NonParallelizable]
public class LifeCycleAttributeTests
{
[SetUp]
public void SetUp()
{
BaseLifeCycle.Reset();
}
#region Basic Lifecycle
[Test]
public void InstancePerTestCaseCreatesAnInstanceForEachTestCase()
{
var fixture = TestBuilder.MakeFixture(typeof(CountingLifeCycleTestFixture));
var attr = new FixtureLifeCycleAttribute(LifeCycle.InstancePerTestCase);
attr.ApplyToTest(fixture);
ITestResult result = TestBuilder.RunTest(fixture);
Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Passed));
}
[Test]
public void SingleInstanceSharesAnInstanceForEachTestCase()
{
var fixture = TestBuilder.MakeFixture(typeof(CountingLifeCycleTestFixture));
var attr = new FixtureLifeCycleAttribute(LifeCycle.SingleInstance);
attr.ApplyToTest(fixture);
ITestResult result = TestBuilder.RunTest(fixture);
Assert.That(
result.Children.Select(t => t.ResultState),
Is.EquivalentTo(new[] { ResultState.Success, ResultState.Failure }));
}
[Test]
public void InstancePerTestCaseFullLifeCycleTest()
{
BaseLifeCycle.Reset();
var fixture = TestBuilder.MakeFixture(typeof(FullLifecycleTestCase));
var attr = new FixtureLifeCycleAttribute(LifeCycle.InstancePerTestCase);
attr.ApplyToTest(fixture);
ITestResult result = TestBuilder.RunTest(fixture);
Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Passed), result.Message);
BaseLifeCycle.VerifyInstancePerTestCase(3);
}
[Test]
public void SingleInstanceFullLifeCycleTest()
{
BaseLifeCycle.Reset();
var fixture = TestBuilder.MakeFixture(typeof(FullLifecycleTestCase));
var attr = new FixtureLifeCycleAttribute(LifeCycle.SingleInstance);
attr.ApplyToTest(fixture);
ITestResult result = TestBuilder.RunTest(fixture);
Assert.That(
result.Children.Select(t => t.ResultState),
Is.EquivalentTo(new[] { ResultState.Success, ResultState.Failure, ResultState.Failure }));
BaseLifeCycle.VerifySingleInstance(3);
}
#endregion
#region Fixture Validation
[Test]
public void InstanceOneTimeSetupTearDownThrows()
{
var fixture = TestBuilder.MakeFixture(typeof(InstanceOneTimeSetupAndTearDownFixtureInstancePerTestCase));
ITestResult result = TestBuilder.RunTest(fixture);
Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Failed));
Assert.That(result.ResultState.Label, Is.EqualTo("Error"));
}
#endregion
#region Test Annotations
[Test]
public void InstancePerTestCaseShouldApplyToTestFixtureSourceTests()
{
var fixture = TestBuilder.MakeFixture(typeof(LifeCycleWithTestFixtureSourceFixture));
ITestResult result = TestBuilder.RunTest(fixture);
Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Passed));
// TODO: OneTimeSetUpCount is called twice. Expected? Does seem consistent w/ reusing the class; then there are also two calls.
BaseLifeCycle.VerifyInstancePerTestCase(4, 2);
}
[Test]
public void InstancePerTestCaseShouldApplyToTestCaseTests()
{
var fixture = TestBuilder.MakeFixture(typeof(FixtureWithTestCases));
ITestResult result = TestBuilder.RunTest(fixture);
Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Passed));
BaseLifeCycle.VerifyInstancePerTestCase(4);
}
[Test]
public void InstancePerTestCaseShouldApplyToTestCaseSourceTests()
{
var fixture = TestBuilder.MakeFixture(typeof(FixtureWithTestCaseSource));
ITestResult result = TestBuilder.RunTest(fixture);
Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Passed));
BaseLifeCycle.VerifyInstancePerTestCase(2);
}
[Test]
public void InstancePerTestCaseShouldApplyToTestsWithValuesParameters()
{
var fixture = TestBuilder.MakeFixture(typeof(FixtureWithValuesAttributeTest));
ITestResult result = TestBuilder.RunTest(fixture);
Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Passed));
BaseLifeCycle.VerifyInstancePerTestCase(3);
}
[Test]
public void InstancePerTestCaseShouldApplyToTheories()
{
var fixture = TestBuilder.MakeFixture(typeof(FixtureWithTheoryTest));
ITestResult result = TestBuilder.RunTest(fixture);
Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Passed));
BaseLifeCycle.VerifyInstancePerTestCase(3);
}
[Test]
public void InstancePerTestCaseShouldApplyToRepeat()
{
RepeatingLifeCycleFixtureInstancePerTestCase.RepeatCounter = 0;
var fixture = TestBuilder.MakeFixture(typeof(RepeatingLifeCycleFixtureInstancePerTestCase));
ITestResult result = TestBuilder.RunTest(fixture);
Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Passed));
Assert.AreEqual(3, RepeatingLifeCycleFixtureInstancePerTestCase.RepeatCounter);
BaseLifeCycle.VerifyInstancePerTestCase(3);
}
[Test]
public void InstancePerTestCaseShouldApplyToParralelTests()
{
var fixture = TestBuilder.MakeFixture(typeof(ParallelLifeCycleFixtureInstancePerTestCase));
ITestResult result = TestBuilder.RunTest(fixture);
Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Passed));
BaseLifeCycle.VerifyInstancePerTestCase(3);
}
#endregion
#region Nesting and inheritance
[Test]
public void NestedFeatureWithoutLifeCycleShouldInheritLifeCycle()
{
var fixture = TestBuilder.MakeFixture(typeof(LifeCycleWithNestedFixture.NestedFixture));
ITestResult result = TestBuilder.RunTest(fixture);
Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Passed));
BaseLifeCycle.VerifyInstancePerTestCase(2);
}
[Test]
public void NestedFeatureWithLifeCycleShouldOverrideLifeCycle()
{
var fixture = TestBuilder.MakeFixture(typeof(LifeCycleWithNestedOverridingFixture.NestedFixture));
ITestResult result = TestBuilder.RunTest(fixture);
Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Passed));
BaseLifeCycle.VerifySingleInstance(2);
}
[Test]
public void ChildClassWithoutLifeCycleShouldInheritLifeCycle()
{
var fixture = TestBuilder.MakeFixture(typeof(LifeCycleInheritedFixture));
ITestResult result = TestBuilder.RunTest(fixture);
Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Passed));
BaseLifeCycle.VerifyInstancePerTestCase(2);
}
[Test]
public void ChildClassWithLifeCycleShouldOverrideLifeCycle()
{
var fixture = TestBuilder.MakeFixture(typeof(LifeCycleInheritanceOverriddenFixture));
ITestResult result = TestBuilder.RunTest(fixture);
Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Passed));
BaseLifeCycle.VerifySingleInstance(2);
}
#endregion
#region DisposeOnly
[Test]
public void InstancePerTestCaseWithDispose()
{
var fixture = TestBuilder.MakeFixture(typeof(InstancePerTestCaseWithDisposeTestCase));
ITestResult result = TestBuilder.RunTest(fixture);
Assert.That(InstancePerTestCaseWithDisposeTestCase.DisposeCount, Is.EqualTo(2));
Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Passed));
}
#endregion
#region Assembly level InstancePerTestCase
#if NETFRAMEWORK
[Test]
public void AssemblyLevelInstancePerTestCaseShouldCreateInstanceForEachTestCase()
{
var asm = TestAssemblyHelper.GenerateInMemoryAssembly(
AssemblyLevelFixtureLifeCycleTest.Code, new[] { typeof(Test).Assembly.Location, typeof(BaseLifeCycle).Assembly.Location });
var testType = asm.GetType("FixtureUnderTest");
var fixture = TestBuilder.MakeFixture(testType);
ITestResult result = TestBuilder.RunTest(fixture);
Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Passed));
BaseLifeCycle.VerifyInstancePerTestCase(2);
}
[Test]
public void FixtureLevelLifeCycleShouldOverrideAssemblyLevelLifeCycle()
{
var asm = TestAssemblyHelper.GenerateInMemoryAssembly(
OverrideAssemblyLevelFixtureLifeCycleTest.Code,
new[] { typeof(Test).Assembly.Location, typeof(BaseLifeCycle).Assembly.Location });
var testType = asm.GetType("FixtureUnderTest");
var fixture = TestBuilder.MakeFixture(testType);
ITestResult result = TestBuilder.RunTest(fixture);
Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Passed));
BaseLifeCycle.VerifySingleInstance(2);
}
[Test]
public void OuterFixtureLevelLifeCycleShouldOverrideAssemblyLevelLifeCycleInNestedFixture()
{
var asm = TestAssemblyHelper.GenerateInMemoryAssembly(
NestedOverrideAssemblyLevelFixtureLifeCycleTest.OuterClass,
new[] { typeof(Test).Assembly.Location, typeof(BaseLifeCycle).Assembly.Location });
var testType = asm.GetType("FixtureUnderTest+NestedFixture");
var fixture = TestBuilder.MakeFixture(testType);
ITestResult result = TestBuilder.RunTest(fixture);
Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Passed));
BaseLifeCycle.VerifySingleInstance(2);
}
[Test]
public void InnerFixtureLevelLifeCycleShouldOverrideAssemblyLevelLifeCycleInNestedFixture()
{
var asm = TestAssemblyHelper.GenerateInMemoryAssembly(
NestedOverrideAssemblyLevelFixtureLifeCycleTest.InnerClass,
new[] { typeof(Test).Assembly.Location, typeof(BaseLifeCycle).Assembly.Location });
var testType = asm.GetType("FixtureUnderTest+NestedFixture");
var fixture = TestBuilder.MakeFixture(testType);
ITestResult result = TestBuilder.RunTest(fixture);
Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Passed));
BaseLifeCycle.VerifySingleInstance(2);
}
[Test]
public void BaseLifecycleShouldOverrideAssemblyLevelLifeCycle()
{
var asm = TestAssemblyHelper.GenerateInMemoryAssembly(
InheritedOverrideTest.InheritClassWithOtherLifecycle,
new[] { typeof(Test).Assembly.Location, typeof(BaseLifeCycle).Assembly.Location });
var testType = asm.GetType("FixtureUnderTest");
var fixture = TestBuilder.MakeFixture(testType);
ITestResult result = TestBuilder.RunTest(fixture);
Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Passed));
BaseLifeCycle.VerifySingleInstance(2);
}
[Test]
public void BaseLifecycleFromOtherAssemblyShouldOverrideAssemblyLevelLifeCycle()
{
var asm = TestAssemblyHelper.GenerateInMemoryAssembly(
InheritedOverrideTest.InheritClassWithOtherLifecycleFromOtherAssembly,
new[] { typeof(Test).Assembly.Location, typeof(BaseLifeCycle).Assembly.Location });
var testType = asm.GetType("FixtureUnderTest");
var fixture = TestBuilder.MakeFixture(testType);
ITestResult result = TestBuilder.RunTest(fixture);
Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Passed));
BaseLifeCycle.VerifySingleInstance(2);
}
[Test]
public void GivenFixtureWithTestFixtureSource_AssemblyLevelInstancePerTestCaseShouldCreateInstanceForEachTestCase()
{
var asm = TestAssemblyHelper.GenerateInMemoryAssembly(
AssemblyLevelLifeCycleTestFixtureSourceTest.Code, new[] { typeof(Test).Assembly.Location });
var testType = asm.GetType("FixtureUnderTest");
var fixture = TestBuilder.MakeFixture(testType);
ITestResult result = TestBuilder.RunTest(fixture);
Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Passed));
}
[Test]
public void GivenFixtureWithTestCases_AssemblyLevelInstancePerTestCaseShouldCreateInstanceForEachTestCase()
{
var asm = TestAssemblyHelper.GenerateInMemoryAssembly(
AssemblyLevelLifeCycleFixtureWithTestCasesTest.Code, new[] { typeof(Test).Assembly.Location });
var testType = asm.GetType("FixtureUnderTest");
var fixture = TestBuilder.MakeFixture(testType);
ITestResult result = TestBuilder.RunTest(fixture);
Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Passed));
}
[Test]
public void GivenFixtureWithTestCaseSource_AssemblyLevelInstancePerTestCaseShouldCreateInstanceForEachTestCase()
{
var asm = TestAssemblyHelper.GenerateInMemoryAssembly(
AssemblyLevelLifeCycleFixtureWithTestCaseSourceTest.Code, new[] { typeof(Test).Assembly.Location });
var testType = asm.GetType("FixtureUnderTest");
var fixture = TestBuilder.MakeFixture(testType);
ITestResult result = TestBuilder.RunTest(fixture);
Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Passed));
}
[Test]
public void GivenFixtureWithValuesAttribute_AssemblyLevelInstancePerTestCaseShouldCreateInstanceForEachTestCase()
{
var asm = TestAssemblyHelper.GenerateInMemoryAssembly(
AssemblyLevelLifeCycleFixtureWithValuesTest.Code, new[] { typeof(Test).Assembly.Location });
var testType = asm.GetType("FixtureUnderTest");
var fixture = TestBuilder.MakeFixture(testType);
ITestResult result = TestBuilder.RunTest(fixture);
Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Passed));
}
[Test]
public void GivenFixtureWithTheory_AssemblyLevelInstancePerTestCaseShouldCreateInstanceForEachTestCase()
{
var asm = TestAssemblyHelper.GenerateInMemoryAssembly(
AssemblyLevelLifeCycleFixtureWithTheoryTest.Code, new[] { typeof(Test).Assembly.Location });
var testType = asm.GetType("FixtureUnderTest");
var fixture = TestBuilder.MakeFixture(testType);
ITestResult result = TestBuilder.RunTest(fixture);
Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Passed));
}
#endif
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers.Binary;
using System.Diagnostics;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Net
{
/// <devdoc>
/// <para>
/// Provides an Internet Protocol (IP) address.
/// </para>
/// </devdoc>
public class IPAddress
{
public static readonly IPAddress Any = new ReadOnlyIPAddress(0x0000000000000000);
public static readonly IPAddress Loopback = new ReadOnlyIPAddress(0x000000000100007F);
public static readonly IPAddress Broadcast = new ReadOnlyIPAddress(0x00000000FFFFFFFF);
public static readonly IPAddress None = Broadcast;
internal const long LoopbackMask = 0x00000000000000FF;
public static readonly IPAddress IPv6Any = new IPAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0);
public static readonly IPAddress IPv6Loopback = new IPAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, 0);
public static readonly IPAddress IPv6None = new IPAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0);
private static readonly IPAddress s_loopbackMappedToIPv6 = new IPAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 127, 0, 0, 1 }, 0);
/// <summary>
/// For IPv4 addresses, this field stores the Address.
/// For IPv6 addresses, this field stores the ScopeId.
/// Instead of accessing this field directly, use the <see cref="PrivateAddress"/> or <see cref="PrivateScopeId"/> properties.
/// </summary>
private uint _addressOrScopeId;
/// <summary>
/// This field is only used for IPv6 addresses. A null value indicates that this instance is an IPv4 address.
/// </summary>
private readonly ushort[] _numbers;
/// <summary>
/// A lazily initialized cache of the result of calling <see cref="ToString"/>.
/// </summary>
private string _toString;
/// <summary>
/// A lazily initialized cache of the <see cref="GetHashCode"/> value.
/// </summary>
private int _hashCode;
internal const int NumberOfLabels = IPAddressParserStatics.IPv6AddressBytes / 2;
private bool IsIPv4
{
get { return _numbers == null; }
}
private bool IsIPv6
{
get { return _numbers != null; }
}
private uint PrivateAddress
{
get
{
Debug.Assert(IsIPv4);
return _addressOrScopeId;
}
set
{
Debug.Assert(IsIPv4);
_toString = null;
_hashCode = 0;
_addressOrScopeId = value;
}
}
private uint PrivateScopeId
{
get
{
Debug.Assert(IsIPv6);
return _addressOrScopeId;
}
set
{
Debug.Assert(IsIPv6);
_toString = null;
_hashCode = 0;
_addressOrScopeId = value;
}
}
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Net.IPAddress'/>
/// class with the specified address.
/// </para>
/// </devdoc>
public IPAddress(long newAddress)
{
if (newAddress < 0 || newAddress > 0x00000000FFFFFFFF)
{
throw new ArgumentOutOfRangeException(nameof(newAddress));
}
PrivateAddress = (uint)newAddress;
}
/// <devdoc>
/// <para>
/// Constructor for an IPv6 Address with a specified Scope.
/// </para>
/// </devdoc>
public IPAddress(byte[] address, long scopeid) :
this(new ReadOnlySpan<byte>(address ?? ThrowAddressNullException()), scopeid)
{
}
public IPAddress(ReadOnlySpan<byte> address, long scopeid)
{
if (address.Length != IPAddressParserStatics.IPv6AddressBytes)
{
throw new ArgumentException(SR.dns_bad_ip_address, nameof(address));
}
// Consider: Since scope is only valid for link-local and site-local
// addresses we could implement some more robust checking here
if (scopeid < 0 || scopeid > 0x00000000FFFFFFFF)
{
throw new ArgumentOutOfRangeException(nameof(scopeid));
}
_numbers = new ushort[NumberOfLabels];
for (int i = 0; i < NumberOfLabels; i++)
{
_numbers[i] = (ushort)(address[i * 2] * 256 + address[i * 2 + 1]);
}
PrivateScopeId = (uint)scopeid;
}
internal unsafe IPAddress(ushort* numbers, int numbersLength, uint scopeid)
{
Debug.Assert(numbers != null);
Debug.Assert(numbersLength == NumberOfLabels);
var arr = new ushort[NumberOfLabels];
for (int i = 0; i < arr.Length; i++)
{
arr[i] = numbers[i];
}
_numbers = arr;
PrivateScopeId = scopeid;
}
private IPAddress(ushort[] numbers, uint scopeid)
{
Debug.Assert(numbers != null);
Debug.Assert(numbers.Length == NumberOfLabels);
_numbers = numbers;
PrivateScopeId = scopeid;
}
/// <devdoc>
/// <para>
/// Constructor for IPv4 and IPv6 Address.
/// </para>
/// </devdoc>
public IPAddress(byte[] address) :
this(new ReadOnlySpan<byte>(address ?? ThrowAddressNullException()))
{
}
public IPAddress(ReadOnlySpan<byte> address)
{
if (address.Length == IPAddressParserStatics.IPv4AddressBytes)
{
PrivateAddress = (uint)((address[3] << 24 | address[2] << 16 | address[1] << 8 | address[0]) & 0x0FFFFFFFF);
}
else if (address.Length == IPAddressParserStatics.IPv6AddressBytes)
{
_numbers = new ushort[NumberOfLabels];
for (int i = 0; i < NumberOfLabels; i++)
{
_numbers[i] = (ushort)(address[i * 2] * 256 + address[i * 2 + 1]);
}
}
else
{
throw new ArgumentException(SR.dns_bad_ip_address, nameof(address));
}
}
// We need this internally since we need to interface with winsock,
// and winsock only understands Int32.
internal IPAddress(int newAddress)
{
PrivateAddress = (uint)newAddress;
}
/// <devdoc>
/// <para>
/// Converts an IP address string to an <see cref='System.Net.IPAddress'/> instance.
/// </para>
/// </devdoc>
public static bool TryParse(string ipString, out IPAddress address)
{
if (ipString == null)
{
address = null;
return false;
}
address = IPAddressParser.Parse(ipString.AsSpan(), tryParse: true);
return (address != null);
}
public static bool TryParse(ReadOnlySpan<char> ipSpan, out IPAddress address)
{
address = IPAddressParser.Parse(ipSpan, tryParse: true);
return (address != null);
}
public static IPAddress Parse(string ipString)
{
if (ipString == null)
{
throw new ArgumentNullException(nameof(ipString));
}
return IPAddressParser.Parse(ipString.AsSpan(), tryParse: false);
}
public static IPAddress Parse(ReadOnlySpan<char> ipSpan)
{
return IPAddressParser.Parse(ipSpan, tryParse: false);
}
public bool TryWriteBytes(Span<byte> destination, out int bytesWritten)
{
if (IsIPv6)
{
if (destination.Length < IPAddressParserStatics.IPv6AddressBytes)
{
bytesWritten = 0;
return false;
}
WriteIPv6Bytes(destination);
bytesWritten = IPAddressParserStatics.IPv6AddressBytes;
}
else
{
if (destination.Length < IPAddressParserStatics.IPv4AddressBytes)
{
bytesWritten = 0;
return false;
}
WriteIPv4Bytes(destination);
bytesWritten = IPAddressParserStatics.IPv4AddressBytes;
}
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void WriteIPv6Bytes(Span<byte> destination)
{
Debug.Assert(_numbers != null && _numbers.Length == NumberOfLabels);
int j = 0;
for (int i = 0; i < NumberOfLabels; i++)
{
destination[j++] = (byte)((_numbers[i] >> 8) & 0xFF);
destination[j++] = (byte)((_numbers[i]) & 0xFF);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void WriteIPv4Bytes(Span<byte> destination)
{
uint address = PrivateAddress;
destination[0] = (byte)(address);
destination[1] = (byte)(address >> 8);
destination[2] = (byte)(address >> 16);
destination[3] = (byte)(address >> 24);
}
/// <devdoc>
/// <para>
/// Provides a copy of the IPAddress internals as an array of bytes.
/// </para>
/// </devdoc>
public byte[] GetAddressBytes()
{
if (IsIPv6)
{
Debug.Assert(_numbers != null && _numbers.Length == NumberOfLabels);
byte[] bytes = new byte[IPAddressParserStatics.IPv6AddressBytes];
WriteIPv6Bytes(bytes);
return bytes;
}
else
{
byte[] bytes = new byte[IPAddressParserStatics.IPv4AddressBytes];
WriteIPv4Bytes(bytes);
return bytes;
}
}
public AddressFamily AddressFamily
{
get
{
return IsIPv4 ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6;
}
}
/// <devdoc>
/// <para>
/// IPv6 Scope identifier. This is really a uint32, but that isn't CLS compliant
/// </para>
/// </devdoc>
public long ScopeId
{
get
{
// Not valid for IPv4 addresses
if (IsIPv4)
{
throw new SocketException(SocketError.OperationNotSupported);
}
return PrivateScopeId;
}
set
{
// Not valid for IPv4 addresses
if (IsIPv4)
{
throw new SocketException(SocketError.OperationNotSupported);
}
// Consider: Since scope is only valid for link-local and site-local
// addresses we could implement some more robust checking here
if (value < 0 || value > 0x00000000FFFFFFFF)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
PrivateScopeId = (uint)value;
}
}
/// <devdoc>
/// <para>
/// Converts the Internet address to either standard dotted quad format
/// or standard IPv6 representation.
/// </para>
/// </devdoc>
public override string ToString()
{
if (_toString == null)
{
_toString = IsIPv4 ?
IPAddressParser.IPv4AddressToString(PrivateAddress) :
IPAddressParser.IPv6AddressToString(_numbers, PrivateScopeId);
}
return _toString;
}
public bool TryFormat(Span<char> destination, out int charsWritten)
{
return IsIPv4 ?
IPAddressParser.IPv4AddressToString(PrivateAddress, destination, out charsWritten) :
IPAddressParser.IPv6AddressToString(_numbers, PrivateScopeId, destination, out charsWritten);
}
public static long HostToNetworkOrder(long host)
{
return BitConverter.IsLittleEndian ? BinaryPrimitives.ReverseEndianness(host) : host;
}
public static int HostToNetworkOrder(int host)
{
return BitConverter.IsLittleEndian ? BinaryPrimitives.ReverseEndianness(host) : host;
}
public static short HostToNetworkOrder(short host)
{
return BitConverter.IsLittleEndian ? BinaryPrimitives.ReverseEndianness(host) : host;
}
public static long NetworkToHostOrder(long network)
{
return HostToNetworkOrder(network);
}
public static int NetworkToHostOrder(int network)
{
return HostToNetworkOrder(network);
}
public static short NetworkToHostOrder(short network)
{
return HostToNetworkOrder(network);
}
public static bool IsLoopback(IPAddress address)
{
if (address == null)
{
ThrowAddressNullException();
}
if (address.IsIPv6)
{
// Do Equals test for IPv6 addresses
return address.Equals(IPv6Loopback) || address.Equals(s_loopbackMappedToIPv6);
}
else
{
return ((address.PrivateAddress & LoopbackMask) == (Loopback.PrivateAddress & LoopbackMask));
}
}
/// <devdoc>
/// <para>
/// Determines if an address is an IPv6 Multicast address
/// </para>
/// </devdoc>
public bool IsIPv6Multicast
{
get
{
return IsIPv6 && ((_numbers[0] & 0xFF00) == 0xFF00);
}
}
/// <devdoc>
/// <para>
/// Determines if an address is an IPv6 Link Local address
/// </para>
/// </devdoc>
public bool IsIPv6LinkLocal
{
get
{
return IsIPv6 && ((_numbers[0] & 0xFFC0) == 0xFE80);
}
}
/// <devdoc>
/// <para>
/// Determines if an address is an IPv6 Site Local address
/// </para>
/// </devdoc>
public bool IsIPv6SiteLocal
{
get
{
return IsIPv6 && ((_numbers[0] & 0xFFC0) == 0xFEC0);
}
}
public bool IsIPv6Teredo
{
get
{
return IsIPv6 &&
(_numbers[0] == 0x2001) &&
(_numbers[1] == 0);
}
}
// 0:0:0:0:0:FFFF:x.x.x.x
public bool IsIPv4MappedToIPv6
{
get
{
if (IsIPv4)
{
return false;
}
for (int i = 0; i < 5; i++)
{
if (_numbers[i] != 0)
{
return false;
}
}
return (_numbers[5] == 0xFFFF);
}
}
[Obsolete("This property has been deprecated. It is address family dependent. Please use IPAddress.Equals method to perform comparisons. https://go.microsoft.com/fwlink/?linkid=14202")]
public long Address
{
get
{
//
// IPv6 Changes: Can't do this for IPv6, so throw an exception.
//
//
if (AddressFamily == AddressFamily.InterNetworkV6)
{
throw new SocketException(SocketError.OperationNotSupported);
}
else
{
return PrivateAddress;
}
}
set
{
//
// IPv6 Changes: Can't do this for IPv6 addresses
if (AddressFamily == AddressFamily.InterNetworkV6)
{
throw new SocketException(SocketError.OperationNotSupported);
}
else
{
if (PrivateAddress != value)
{
if (this is ReadOnlyIPAddress)
{
throw new SocketException(SocketError.OperationNotSupported);
}
PrivateAddress = unchecked((uint)value);
}
}
}
}
/// <summary>Compares two IP addresses.</summary>
public override bool Equals(object comparand)
{
return comparand is IPAddress address && Equals(address);
}
internal bool Equals(IPAddress comparand)
{
Debug.Assert(comparand != null);
// Compare families before address representations
if (AddressFamily != comparand.AddressFamily)
{
return false;
}
if (IsIPv6)
{
// For IPv6 addresses, we must compare the full 128-bit representation and the scope IDs.
ReadOnlySpan<byte> thisNumbers = MemoryMarshal.AsBytes<ushort>(_numbers);
ReadOnlySpan<byte> comparandNumbers = MemoryMarshal.AsBytes<ushort>(comparand._numbers);
return
MemoryMarshal.Read<ulong>(thisNumbers) == MemoryMarshal.Read<ulong>(comparandNumbers) &&
MemoryMarshal.Read<ulong>(thisNumbers.Slice(sizeof(ulong))) == MemoryMarshal.Read<ulong>(comparandNumbers.Slice(sizeof(ulong))) &&
PrivateScopeId == comparand.PrivateScopeId;
}
else
{
// For IPv4 addresses, compare the integer representation.
return comparand.PrivateAddress == PrivateAddress;
}
}
public override int GetHashCode()
{
if (_hashCode != 0)
{
return _hashCode;
}
// For IPv6 addresses, we calculate the hashcode by using Marvin
// on a stack-allocated array containing the Address bytes and ScopeId.
int hashCode;
if (IsIPv6)
{
const int AddressAndScopeIdLength = IPAddressParserStatics.IPv6AddressBytes + sizeof(uint);
Span<byte> addressAndScopeIdSpan = stackalloc byte[AddressAndScopeIdLength];
MemoryMarshal.AsBytes(new ReadOnlySpan<ushort>(_numbers)).CopyTo(addressAndScopeIdSpan);
Span<byte> scopeIdSpan = addressAndScopeIdSpan.Slice(IPAddressParserStatics.IPv6AddressBytes);
bool scopeWritten = BitConverter.TryWriteBytes(scopeIdSpan, _addressOrScopeId);
Debug.Assert(scopeWritten);
hashCode = Marvin.ComputeHash32(
addressAndScopeIdSpan,
Marvin.DefaultSeed);
}
else
{
// For IPv4 addresses, we use Marvin on the integer representation of the Address.
hashCode = Marvin.ComputeHash32(
MemoryMarshal.AsBytes(MemoryMarshal.CreateReadOnlySpan(ref _addressOrScopeId, 1)),
Marvin.DefaultSeed);
}
_hashCode = hashCode;
return _hashCode;
}
// IPv4 192.168.1.1 maps as ::FFFF:192.168.1.1
public IPAddress MapToIPv6()
{
if (IsIPv6)
{
return this;
}
uint address = PrivateAddress;
ushort[] labels = new ushort[NumberOfLabels];
labels[5] = 0xFFFF;
labels[6] = (ushort)(((address & 0x0000FF00) >> 8) | ((address & 0x000000FF) << 8));
labels[7] = (ushort)(((address & 0xFF000000) >> 24) | ((address & 0x00FF0000) >> 8));
return new IPAddress(labels, 0);
}
// Takes the last 4 bytes of an IPv6 address and converts it to an IPv4 address.
// This does not restrict to address with the ::FFFF: prefix because other types of
// addresses display the tail segments as IPv4 like Terado.
public IPAddress MapToIPv4()
{
if (IsIPv4)
{
return this;
}
// Cast the ushort values to a uint and mask with unsigned literal before bit shifting.
// Otherwise, we can end up getting a negative value for any IPv4 address that ends with
// a byte higher than 127 due to sign extension of the most significant 1 bit.
long address = ((((uint)_numbers[6] & 0x0000FF00u) >> 8) | (((uint)_numbers[6] & 0x000000FFu) << 8)) |
(((((uint)_numbers[7] & 0x0000FF00u) >> 8) | (((uint)_numbers[7] & 0x000000FFu) << 8)) << 16);
return new IPAddress(address);
}
private static byte[] ThrowAddressNullException() => throw new ArgumentNullException("address");
private sealed class ReadOnlyIPAddress : IPAddress
{
public ReadOnlyIPAddress(long newAddress) : base(newAddress)
{ }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Msagl.Core.Geometry;
using Microsoft.Msagl.Core.Layout;
namespace Microsoft.Msagl.Layout.Incremental {
/// <summary>
/// Fix the position of a node.
/// Create locks using FastIncrementalLayoutSettings.CreateLock method.
/// </summary>
public class LockPosition : IConstraint {
private double weight = 1e6;
internal Node node;
internal LinkedListNode<LockPosition> listNode;
/// <summary>
/// Makes a constraint preserve the nodes' bounding box with a very large weight
/// </summary>
/// <param name="node"></param>
/// <param name="bounds"></param>
internal LockPosition(Node node, Rectangle bounds) {
this.node = node;
this.Bounds = bounds;
}
/// <summary>
/// Makes a constraint to preserve the nodes' position with the specified weight
/// </summary>
/// <param name="node"></param>
/// <param name="bounds"></param>
/// <param name="weight"></param>
internal LockPosition(Node node, Rectangle bounds, double weight)
: this(node, bounds)
{
Weight = weight;
}
/// <summary>
/// Set the weight for this lock constraint, i.e. if this constraint conflicts with some other constraint,
/// projection of that constraint be biased by the weights of the nodes involved
/// </summary>
public double Weight {
get {
return weight;
}
set {
if (value > 1e20) {
throw new ArgumentOutOfRangeException("value", "must be < 1e10 or we run out of precision");
}
if (value < 1e-3) {
throw new ArgumentOutOfRangeException("value", "must be > 1e-3 or we run out of precision");
}
weight = value;
}
}
/// <summary>
/// This assigns the new bounds and needs to be called after Solve() because
/// multiple locked nodes may cause each other to move.
/// </summary>
public Rectangle Bounds {
get;
set;
}
/// <summary>
/// By default locks are not sticky and their ideal Position gets updated when they are pushed by another node.
/// Making them Sticky causes the locked node to spring back to its ideal Position when whatever was pushing it
/// slides past.
/// </summary>
public bool Sticky {
get;
set;
}
/// <summary>
/// Move node (or cluster + children) to lock position
/// I use stay weight in "project" of any constraints involving the locked node
/// </summary>
public virtual double Project() {
var delta = Bounds.LeftBottom - node.BoundingBox.LeftBottom;
double deltaLength = delta.Length;
double displacement = deltaLength;
var cluster = node as Cluster;
if (cluster != null)
{
foreach(var c in cluster.AllClustersDepthFirst())
{
foreach(var v in c.Nodes)
{
v.Center += delta;
displacement += deltaLength;
}
if(c == cluster) {
cluster.RectangularBoundary.Rect = Bounds;
}
else
{
var r = c.RectangularBoundary.Rect;
c.RectangularBoundary.Rect = new Rectangle(r.LeftBottom + delta, r.RightTop + delta);
}
}
}
else
{
node.BoundingBox = Bounds;
}
return displacement;
}
/// <summary>
/// LockPosition is always applied (level 0)
/// </summary>
/// <returns>0</returns>
public int Level { get { return 0; } }
/// <summary>
/// Sets the weight of the node (the FINode actually) to the weight required by this lock.
/// If the node is a Cluster then:
/// - its boundaries are locked
/// - all of its descendant nodes have their lock weight set
/// - all of its descendant clusters are set to generate fixed constraints (so they don't get squashed)
/// Then, the node (or clusters) parents (all the way to the root) have their borders set to generate unfixed constraints
/// (so that this node can move freely inside its ancestors
/// </summary>
internal void SetLockNodeWeight()
{
Cluster cluster = node as Cluster;
if (cluster != null)
{
RectangularClusterBoundary cb = cluster.RectangularBoundary;
cb.Lock(Bounds.Left, Bounds.Right, Bounds.Top, Bounds.Bottom);
foreach (var c in cluster.AllClustersDepthFirst())
{
c.RectangularBoundary.GenerateFixedConstraints = true;
foreach (var child in c.Nodes)
{
SetFINodeWeight(child, weight);
}
}
}
else
{
SetFINodeWeight(node, weight);
}
foreach (Cluster ancestor in this.node.AllClusterAncestors)
{
if (ancestor.RectangularBoundary != null)
{
ancestor.RectangularBoundary.GenerateFixedConstraints = false;
}
ancestor.UnsetInitialLayoutState();
}
}
/// <summary>
/// Reverses the changes made by SetLockNodeWeight
/// </summary>
internal void RestoreNodeWeight() {
Cluster cluster = node as Cluster;
if (cluster != null)
{
cluster.RectangularBoundary.Unlock();
foreach (var c in cluster.AllClustersDepthFirst())
{
c.RectangularBoundary.GenerateFixedConstraints = c.RectangularBoundary.GenerateFixedConstraintsDefault;
foreach (var child in c.Nodes)
{
SetFINodeWeight(child, 1);
}
}
}
else
{
SetFINodeWeight(node, 1);
}
Cluster parent = node.ClusterParents.FirstOrDefault();
while (parent != null)
{
if (parent.RectangularBoundary != null)
{
parent.RectangularBoundary.GenerateFixedConstraints = parent.RectangularBoundary.GenerateFixedConstraintsDefault;
}
parent = parent.ClusterParents.FirstOrDefault();
}
}
private static void SetFINodeWeight(Node child, double weight)
{
var v = child.AlgorithmData as FiNode;
if (v != null)
{
v.stayWeight = weight;
}
}
/// <summary>
/// Get the list of nodes involved in the constraint
/// </summary>
public IEnumerable<Node> Nodes
{
get
{
var nodes = new List<Node>();
var cluster = node as Cluster;
if(cluster!=null)
{
cluster.ForEachNode(nodes.Add);
}
else
{
nodes.Add(node);
}
return nodes;
}
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// Game1.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
#endregion
namespace TouchGestureSample
{
public class Game1 : Microsoft.Xna.Framework.Game
{
private GraphicsDeviceManager graphics;
private SpriteBatch spriteBatch;
private SpriteFont font;
private Texture2D cat;
// the text we display on screen, created here to make our Draw method cleaner
private const string helpText =
"Hold (in empty space) - Create sprite\n" +
"Hold (on sprite) - Remove sprite\n" +
"Tap - Change sprite color\n" +
"Drag - Move sprite\n" +
"Flick - Throws sprite\n" +
"Pinch - Scale sprite";
// a list to hold all of our sprites
private List<Sprite> sprites = new List<Sprite>();
// we track our selected sprite so we can drag it around
private Sprite selectedSprite;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
graphics.IsFullScreen = true;
Content.RootDirectory = "Content";
// Frame rate is 30 fps by default for Windows Phone.
TargetElapsedTime = TimeSpan.FromTicks(333333);
}
protected override void Initialize()
{
// enable the gestures we care about. you must set EnabledGestures before
// you can use any of the other gesture APIs.
// we use both Tap and DoubleTap to workaround a bug in the XNA GS 4.0 Beta
// where some Taps are missed if only Tap is specified.
TouchPanel.EnabledGestures =
GestureType.Hold |
GestureType.Tap |
GestureType.DoubleTap |
GestureType.FreeDrag |
GestureType.Flick |
GestureType.Pinch;
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
cat = Content.Load<Texture2D>("cat");
font = Content.Load<SpriteFont>("Font");
}
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
// handle the touch input
HandleTouchInput();
// update all of the sprites
foreach (Sprite sprite in sprites)
{
sprite.Update(gameTime, GraphicsDevice.Viewport.Bounds);
}
base.Update(gameTime);
}
private void HandleTouchInput()
{
// we use raw touch points for selection, since they are more appropriate
// for that use than gestures. so we need to get that raw touch data.
TouchCollection touches = TouchPanel.GetState();
// see if we have a new primary point down. when the first touch
// goes down, we do hit detection to try and select one of our sprites.
if (touches.Count > 0 && touches[0].State == TouchLocationState.Pressed)
{
// convert the touch position into a Point for hit testing
Point touchPoint = new Point((int)touches[0].Position.X, (int)touches[0].Position.Y);
// iterate our sprites to find which sprite is being touched. we iterate backwards
// since that will cause sprites that are drawn on top to be selected before
// sprites drawn on the bottom.
selectedSprite = null;
for (int i = sprites.Count - 1; i >= 0; i--)
{
Sprite sprite = sprites[i];
if (sprite.HitBounds.Contains(touchPoint))
{
selectedSprite = sprite;
break;
}
}
if (selectedSprite != null)
{
// make sure we stop selected sprites
selectedSprite.Velocity = Vector2.Zero;
// we also move the sprite to the end of the list so it
// draws on top of the other sprites
sprites.Remove(selectedSprite);
sprites.Add(selectedSprite);
}
}
// next we handle all of the gestures. since we may have multiple gestures available,
// we use a loop to read in all of the gestures. this is important to make sure the
// TouchPanel's queue doesn't get backed up with old data
while (TouchPanel.IsGestureAvailable)
{
// read the next gesture from the queue
GestureSample gesture = TouchPanel.ReadGesture();
// we can use the type of gesture to determine our behavior
switch (gesture.GestureType)
{
// on taps, we change the color of the selected sprite
case GestureType.Tap:
case GestureType.DoubleTap:
if (selectedSprite != null)
{
selectedSprite.ChangeColor();
}
break;
// on holds, if no sprite is selected, we add a new sprite at the
// hold position and make it our selected sprite. otherwise we
// remove our selected sprite.
case GestureType.Hold:
if (selectedSprite == null)
{
// create the new sprite
selectedSprite = new Sprite(cat);
selectedSprite.Center = gesture.Position;
// add it to our list
sprites.Add(selectedSprite);
}
else
{
sprites.Remove(selectedSprite);
selectedSprite = null;
}
break;
// on drags, we just want to move the selected sprite with the drag
case GestureType.FreeDrag:
if (selectedSprite != null)
{
selectedSprite.Center += gesture.Delta;
}
break;
// on flicks, we want to update the selected sprite's velocity with
// the flick velocity, which is in pixels per second.
case GestureType.Flick:
if (selectedSprite != null)
{
selectedSprite.Velocity = gesture.Delta;
}
break;
// on pinches, we want to scale the selected sprite
case GestureType.Pinch:
if (selectedSprite != null)
{
// get the current and previous locations of the two fingers
Vector2 a = gesture.Position;
Vector2 aOld = gesture.Position - gesture.Delta;
Vector2 b = gesture.Position2;
Vector2 bOld = gesture.Position2 - gesture.Delta2;
// figure out the distance between the current and previous locations
float d = Vector2.Distance(a, b);
float dOld = Vector2.Distance(aOld, bOld);
// calculate the difference between the two and use that to alter the scale
float scaleChange = (d - dOld) * .01f;
selectedSprite.Scale += scaleChange;
}
break;
}
}
// lastly, if there are no raw touch points, we make sure no sprites are selected.
// this happens after we handle gestures because some gestures like taps and flicks
// will come in on the same frame as our raw touch points report no touches and we
// still want to use the selected sprite for those gestures.
if (touches.Count == 0)
{
selectedSprite = null;
}
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
// draw all sprites first
foreach (Sprite sprite in sprites)
{
sprite.Draw(spriteBatch);
}
// draw our helper text so users know what they're doing.
spriteBatch.DrawString(font, helpText, new Vector2(10f, 32f), Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using Xunit;
namespace System.Linq.Tests
{
public class GroupByTests : EnumerableBasedTests
{
public static void AssertGroupingCorrect<TKey, TElement>(IQueryable<TKey> keys, IQueryable<TElement> elements, IQueryable<IGrouping<TKey, TElement>> grouping)
{
AssertGroupingCorrect<TKey, TElement>(keys, elements, grouping, EqualityComparer<TKey>.Default);
}
public static void AssertGroupingCorrect<TKey, TElement>(IQueryable<TKey> keys, IQueryable<TElement> elements, IQueryable<IGrouping<TKey, TElement>> grouping, IEqualityComparer<TKey> keyComparer)
{
if (grouping == null)
{
Assert.Null(elements);
Assert.Null(keys);
return;
}
Assert.NotNull(elements);
Assert.NotNull(keys);
Dictionary<TKey, List<TElement>> dict = new Dictionary<TKey, List<TElement>>(keyComparer);
List<TElement> groupingForNullKeys = new List<TElement>();
using (IEnumerator<TElement> elEn = elements.GetEnumerator())
using (IEnumerator<TKey> keyEn = keys.GetEnumerator())
{
while (keyEn.MoveNext())
{
Assert.True(elEn.MoveNext());
TKey key = keyEn.Current;
if (key == null)
{
groupingForNullKeys.Add(elEn.Current);
}
else
{
List<TElement> list;
if (!dict.TryGetValue(key, out list))
dict.Add(key, list = new List<TElement>());
list.Add(elEn.Current);
}
}
Assert.False(elEn.MoveNext());
}
foreach (IGrouping<TKey, TElement> group in grouping)
{
Assert.NotEmpty(group);
TKey key = group.Key;
List<TElement> list;
if (key == null)
{
Assert.Equal(groupingForNullKeys, group);
groupingForNullKeys.Clear();
}
else
{
Assert.True(dict.TryGetValue(key, out list));
Assert.Equal(list, group);
dict.Remove(key);
}
}
Assert.Empty(dict);
Assert.Empty(groupingForNullKeys);
}
public struct Record
{
public string Name;
public int Score;
}
[Fact]
public void SingleNullKeySingleNullElement()
{
string[] key = { null };
string[] element = { null };
AssertGroupingCorrect(key.AsQueryable(), element.AsQueryable(), new string[] { null }.AsQueryable().GroupBy(e => e, e => e, EqualityComparer<string>.Default), EqualityComparer<string>.Default);
}
[Fact]
public void EmptySource()
{
Assert.Empty(new Record[] { }.AsQueryable().GroupBy(e => e.Name, e => e.Score, new AnagramEqualityComparer()));
}
[Fact]
public void SourceIsNull()
{
IQueryable<Record> source = null;
Assert.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, e => e.Score, new AnagramEqualityComparer()));
Assert.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, new AnagramEqualityComparer()));
Assert.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, e => e.Score));
Assert.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name));
Assert.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, e => e.Score, (k, es) => es.Sum(), new AnagramEqualityComparer()));
Assert.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, e => e.Score, (k, es) => es.Sum()));
Assert.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, (k, es) => es.Sum(e => e.Score)));
Assert.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, (k, es) => es.Sum(e => e.Score), new AnagramEqualityComparer()));
}
[Fact]
public void KeySelectorNull()
{
Record[] source = new[]
{
new Record { Name = "Tim", Score = 55 },
new Record { Name = "Chris", Score = 49 },
new Record { Name = "Robert", Score = -100 },
new Record { Name = "Chris", Score = 24 },
new Record { Name = "Prakash", Score = 9 },
new Record { Name = "Tim", Score = 25 }
};
Expression<Func<Record, string>> keySelector = null;
Assert.Throws<ArgumentNullException>("keySelector", () => source.AsQueryable().GroupBy(null, e => e.Score, new AnagramEqualityComparer()));
Assert.Throws<ArgumentNullException>("keySelector", () => source.AsQueryable().GroupBy(null, e => e.Score, (k, es) => es.Sum(), new AnagramEqualityComparer()));
Assert.Throws<ArgumentNullException>("keySelector", () => source.AsQueryable().GroupBy(keySelector, e => e.Score, (k, es) => es.Sum()));
Assert.Throws<ArgumentNullException>("keySelector", () => source.AsQueryable().GroupBy(keySelector, e => e.Score));
Assert.Throws<ArgumentNullException>("keySelector", () => source.AsQueryable().GroupBy(keySelector, e => e.Score, (k, es) => es.Sum()));
Assert.Throws<ArgumentNullException>("keySelector", () => source.AsQueryable().GroupBy(null, (k, es) => es.Sum(e => e.Score), new AnagramEqualityComparer()));
Assert.Throws<ArgumentNullException>("keySelector", () => source.AsQueryable().GroupBy(keySelector, (k, es) => es.Sum(e => e.Score)));
Assert.Throws<ArgumentNullException>("keySelector", () => source.AsQueryable().GroupBy(null, new AnagramEqualityComparer()));
Assert.Throws<ArgumentNullException>("keySelector", () => source.AsQueryable().GroupBy(keySelector));
}
[Fact]
public void ElementSelectorNull()
{
Record[] source = new[]
{
new Record { Name = "Tim", Score = 55 },
new Record { Name = "Chris", Score = 49 },
new Record { Name = "Robert", Score = -100 },
new Record { Name = "Chris", Score = 24 },
new Record { Name = "Prakash", Score = 9 },
new Record { Name = "Tim", Score = 25 }
};
Expression<Func<Record, int>> elementSelector = null;
Assert.Throws<ArgumentNullException>("elementSelector", () => source.AsQueryable().GroupBy(e => e.Name, elementSelector));
Assert.Throws<ArgumentNullException>("elementSelector", () => source.AsQueryable().GroupBy(e => e.Name, elementSelector, new AnagramEqualityComparer()));
Assert.Throws<ArgumentNullException>("elementSelector", () => source.AsQueryable().GroupBy(e => e.Name, elementSelector, (k, es) => es.Sum()));
Assert.Throws<ArgumentNullException>("elementSelector", () => source.AsQueryable().GroupBy(e => e.Name, elementSelector, (k, es) => es.Sum(), new AnagramEqualityComparer()));
}
[Fact]
public void ResultSelectorNull()
{
Record[] source = {
new Record { Name = "Tim", Score = 55 },
new Record { Name = "Chris", Score = 49 },
new Record { Name = "Robert", Score = -100 },
new Record { Name = "Chris", Score = 24 },
new Record { Name = "Prakash", Score = 9 },
new Record { Name = "Tim", Score = 25 }
};
Expression<Func<string, IEnumerable<int>, long>> resultSelector = null;
Assert.Throws<ArgumentNullException>("resultSelector", () => source.AsQueryable().GroupBy(e => e.Name, e => e.Score, resultSelector, new AnagramEqualityComparer()));
}
[Fact]
public void ResultSelectorNullNoComparer()
{
Record[] source = {
new Record { Name = "Tim", Score = 55 },
new Record { Name = "Chris", Score = 49 },
new Record { Name = "Robert", Score = -100 },
new Record { Name = "Chris", Score = 24 },
new Record { Name = "Prakash", Score = 9 },
new Record { Name = "Tim", Score = 25 }
};
Expression<Func<string, IEnumerable<int>, long>> resultSelector = null;
Assert.Throws<ArgumentNullException>("resultSelector", () => source.AsQueryable().GroupBy(e => e.Name, e => e.Score, resultSelector));
}
[Fact]
public void ResultSelectorNullNoElementSelector()
{
Record[] source = {
new Record { Name = "Tim", Score = 55 },
new Record { Name = "Chris", Score = 49 },
new Record { Name = "Robert", Score = -100 },
new Record { Name = "Chris", Score = 24 },
new Record { Name = "Prakash", Score = 9 },
new Record { Name = "Tim", Score = 25 }
};
Expression<Func<string, IEnumerable<Record>, long>> resultSelector = null;
Assert.Throws<ArgumentNullException>("resultSelector", () => source.AsQueryable().GroupBy(e => e.Name, resultSelector));
}
[Fact]
public void ResultSelectorNullNoElementSelectorCustomComparer()
{
string[] key = { "Tim", "Tim", "Tim", "Tim" };
int[] element = { 60, -10, 40, 100 };
var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e });
Expression<Func<string, IEnumerable<Record>, long>> resultSelector = null;
Assert.Throws<ArgumentNullException>("resultSelector", () => source.AsQueryable().GroupBy(e => e.Name, resultSelector, new AnagramEqualityComparer()));
}
[Fact]
public void EmptySourceWithResultSelector()
{
Assert.Empty(new Record[] { }.AsQueryable().GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum(), new AnagramEqualityComparer()));
}
[Fact]
public void DuplicateKeysCustomComparer()
{
string[] key = { "Tim", "Tim", "Chris", "Chris", "Robert", "Prakash" };
int[] element = { 55, 25, 49, 24, -100, 9 };
Record[] source = {
new Record { Name = "Tim", Score = 55 },
new Record { Name = "Chris", Score = 49 },
new Record { Name = "Robert", Score = -100 },
new Record { Name = "Chris", Score = 24 },
new Record { Name = "Prakash", Score = 9 },
new Record { Name = "miT", Score = 25 }
};
long[] expected = { 240, 365, -600, 63 };
Assert.Equal(expected, source.AsQueryable().GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum(), new AnagramEqualityComparer()));
}
[Fact]
public void NullComparer()
{
string[] key = { "Tim", null, null, "Robert", "Chris", "miT" };
int[] element = { 55, 49, 9, -100, 24, 25 };
Record[] source = {
new Record { Name = "Tim", Score = 55 },
new Record { Name = null, Score = 49 },
new Record { Name = "Robert", Score = -100 },
new Record { Name = "Chris", Score = 24 },
new Record { Name = null, Score = 9 },
new Record { Name = "miT", Score = 25 }
};
long[] expected = { 165, 58, -600, 120, 75 };
Assert.Equal(expected, source.AsQueryable().GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum(), null));
}
[Fact]
public void SingleNonNullElement()
{
string[] key = { "Tim" };
Record[] source = { new Record { Name = key[0], Score = 60 } };
AssertGroupingCorrect(key.AsQueryable(), source.AsQueryable(), source.AsQueryable().GroupBy(e => e.Name));
}
[Fact]
public void AllElementsSameKey()
{
string[] key = { "Tim", "Tim", "Tim", "Tim" };
int[] scores = { 60, -10, 40, 100 };
var source = key.Zip(scores, (k, e) => new Record { Name = k, Score = e });
AssertGroupingCorrect(key.AsQueryable(), source.AsQueryable(), source.AsQueryable().GroupBy(e => e.Name, new AnagramEqualityComparer()), new AnagramEqualityComparer());
}
[Fact]
public void AllElementsSameKeyResultSelectorUsed()
{
int[] element = { 60, -10, 40, 100 };
long[] expected = { 570 };
Record[] source = {
new Record { Name = "Tim", Score = element[0] },
new Record { Name = "Tim", Score = element[1] },
new Record { Name = "miT", Score = element[2] },
new Record { Name = "miT", Score = element[3] }
};
Assert.Equal(expected, source.AsQueryable().GroupBy(e => e.Name, (k, es) => k.Length * es.Sum(e => (long)e.Score), new AnagramEqualityComparer()));
}
[Fact]
public void NullComparerResultSelectorUsed()
{
int[] element = { 60, -10, 40, 100 };
Record[] source = {
new Record { Name = "Tim", Score = element[0] },
new Record { Name = "Tim", Score = element[1] },
new Record { Name = "miT", Score = element[2] },
new Record { Name = "miT", Score = element[3] },
};
long[] expected = { 150, 420 };
Assert.Equal(expected, source.AsQueryable().GroupBy(e => e.Name, (k, es) => k.Length * es.Sum(e => (long)e.Score), null));
}
[Fact]
public void GroupBy1()
{
var count = (new int[] { 0, 1, 2, 2, 0 }).AsQueryable().GroupBy(n => n).Count();
Assert.Equal(3, count);
}
[Fact]
public void GroupBy2()
{
var count = (new int[] { 0, 1, 2, 2, 0 }).AsQueryable().GroupBy(n => n, EqualityComparer<int>.Default).Count();
Assert.Equal(3, count);
}
[Fact]
public void GroupBy3()
{
var count = (new int[] { 0, 1, 2, 2, 0 }).AsQueryable().GroupBy(n => n, n => n).Count();
Assert.Equal(3, count);
}
[Fact]
public void GroupBy4()
{
var count = (new int[] { 0, 1, 2, 2, 0 }).AsQueryable().GroupBy(n => n, n => n, EqualityComparer<int>.Default).Count();
Assert.Equal(3, count);
}
[Fact]
public void GroupBy5()
{
var count = (new int[] { 0, 1, 2, 2, 0 }).AsQueryable().GroupBy(n => n, n => n, (k, g) => k).Count();
Assert.Equal(3, count);
}
[Fact]
public void GroupBy6()
{
var count = (new int[] { 0, 1, 2, 2, 0 }).AsQueryable().GroupBy(n => n, (k, g) => k).Count();
Assert.Equal(3, count);
}
[Fact]
public void GroupBy7()
{
var count = (new int[] { 0, 1, 2, 2, 0 }).AsQueryable().GroupBy(n => n, n => n, (k, g) => k, EqualityComparer<int>.Default).Count();
Assert.Equal(3, count);
}
[Fact]
public void GroupBy8()
{
var count = (new int[] { 0, 1, 2, 2, 0 }).AsQueryable().GroupBy(n => n, (k, g) => k, EqualityComparer<int>.Default).Count();
Assert.Equal(3, count);
}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System.Text;
namespace System.Globalization
{
/// <summary>
/// CultureInfoExtensions
/// </summary>
public static class CultureInfoExtensions
{
public static readonly string[] Vowels = new string[] { "left", "e", "i", "o", "u" };
/// <summary>
/// Gets the join grammer.
/// </summary>
/// <param name="cultureInfo">The culture info.</param>
/// <returns></returns>
public static string GetJoinGrammer(this CultureInfo cultureInfo)
{
switch (cultureInfo.TwoLetterISOLanguageName)
{
case "en":
return "y";
default:
return "&";
}
}
/// <summary>
/// Returns a string representation of the common grammatical equivalent to the ordinal position of the value provided.
/// </summary>
/// <param name="cultureInfo">The culture info.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public static string GetInstanceGrammer(this CultureInfo cultureInfo, int value)
{
if (value < 1)
throw new ArgumentOutOfRangeException("value");
switch (cultureInfo.TwoLetterISOLanguageName)
{
default:
int modValue = (value % 100);
if ((modValue >= 11) && (modValue <= 13))
return value.ToString(CultureInfo.InvariantCulture) + "th";
switch (value % 10)
{
case 1:
return value.ToString(CultureInfo.InvariantCulture) + "st";
case 2:
return value.ToString(CultureInfo.InvariantCulture) + "nd";
case 3:
return value.ToString(CultureInfo.InvariantCulture) + "rd";
}
return value.ToString(CultureInfo.InvariantCulture) + "th";
}
}
/// <summary>
/// Returns a string representation of the common grammatical list equivalent of the provided array.
/// </summary>
/// <param name="cultureInfo">The culture info.</param>
/// <param name="array">The array.</param>
/// <returns></returns>
public static string GetListGrammer(this CultureInfo cultureInfo, string[] array)
{
if (array == null)
throw new ArgumentNullException("array");
switch (cultureInfo.TwoLetterISOLanguageName)
{
default:
switch (array.Length)
{
case 0:
return string.Empty;
case 1:
return array[1];
case 2:
return StringEx.Axb(array[0], " and ", array[1]);
}
StringBuilder b = new StringBuilder();
int maxArrayIndex = (array.Length - 1);
for (int index = 0; index < array.Length; index++)
{
b.Append(array[index]);
b.Append(index != maxArrayIndex ? ", " : ", and ");
}
return b.ToString();
}
}
/// <summary>
/// Grammers the word.
/// </summary>
/// <param name="cultureInfo">The culture info.</param>
/// <param name="word">The word.</param>
/// <param name="args">The args.</param>
/// <returns></returns>
public static string Word(this CultureInfo cultureInfo, string word, params string[] args)
{
if (word == null)
throw new ArgumentNullException("word");
switch (cultureInfo.TwoLetterISOLanguageName)
{
default:
switch (word.ToLowerInvariant())
{
case "left":
string objectWord;
if ((args == null) || (args.Length != 1) || ((objectWord = args[0]).Length == 0))
throw new Exception();
return word + (!Vowels.ExistsIgnoreCase(objectWord[0].ToString()) ? string.Empty : "n");
default:
throw new InvalidOperationException();
}
}
}
/// <summary>
/// Dates to short relative.
/// </summary>
/// <param name="cultureInfo">The culture info.</param>
/// <param name="dateTime">The date time.</param>
/// <param name="hasTime">if set to <c>true</c> [has time].</param>
/// <returns></returns>
/// http://tiredblogger.wordpress.com/2008/08/21/creating-twitter-esque-relative-dates-in-c/
/// http://refactormycode.com/codes/493-twitter-esque-relative-dates
public static string DateToShortRelative(this CultureInfo cultureInfo, DateTime dateTime, bool hasTime)
{
TimeSpan timeSpan = DateTime.Now - dateTime;
switch (cultureInfo.TwoLetterISOLanguageName)
{
default:
// span is less than or equal to 60 seconds, measure in seconds.
if (timeSpan <= TimeSpan.FromSeconds(60))
return timeSpan.Seconds + " seconds ago";
// span is less than or equal to 60 minutes, measure in minutes.
if (timeSpan <= TimeSpan.FromMinutes(60))
return (timeSpan.Minutes > 1 ? timeSpan.Minutes.ToString() + " minutes ago" : "about a minute ago");
// span is less than or equal to 24 hours, measure in hours.
if (timeSpan <= TimeSpan.FromHours(24))
return (timeSpan.Hours > 1 ? timeSpan.Hours + " hours ago" : "about an hour ago");
// span is less than or equal to 30 days (1 month), measure in days.
if (timeSpan <= TimeSpan.FromDays(30))
return (timeSpan.Days > 1 ? timeSpan.Days + " days ago" : "about a day ago");
// span is less than or equal to 365 days (1 year), measure in months.
if (timeSpan <= TimeSpan.FromDays(365))
return (timeSpan.Days > 30 ? timeSpan.Days / 30 + " months ago" : "about a month ago");
// span is greater than 365 days (1 year), measure in years.
return (timeSpan.Days > 365 ? timeSpan.Days / 365 + " years ago" : "about a year ago");
}
}
///// <summary>
///// Dates to long relative.
///// </summary>
///// <param name="cultureInfo">The culture info.</param>
///// <param name="dateTime">The date time.</param>
///// <param name="isHasTime">if set to <c>true</c> [is has time].</param>
///// <returns></returns>
///// http://simplepie.org/wiki/tutorial/use_relative_dates
//public static string DateToLongRelative(this CultureInfo cultureInfo, DateTime dateTime, bool isHasTime)
//{
// switch (cultureInfo.TwoLetterISOLanguageName)
// {
// default:
// //function doRelativeDate($posted_date) {
// // /**
// // This function returns either a relative date or a formatted date depending
// // on the difference between the current datetime and the datetime passed.
// // $posted_date should be in the following format: YYYYMMDDHHMMSS
// // Relative dates look something like this:
// // 3 weeks, 4 days ago
// // Formatted dates look like this:
// // on 02/18/2004
// // The function includes 'ago' or 'on' and assumes you'll properly add a word
// // like 'Posted ' before the function output.
// // By Garrett Murray, http://graveyard.maniacalrage.net/etc/relative/
// // **/
// // $in_seconds = strtotime(substr($posted_date,0,8).' '.
// // substr($posted_date,8,2).':'.
// // substr($posted_date,10,2).':'.
// // substr($posted_date,12,2));
// // $diff = time()-$in_seconds;
// // $months = floor($diff/2592000);
// // $diff -= $months*2419200;
// // $weeks = floor($diff/604800);
// // $diff -= $weeks*604800;
// // $days = floor($diff/86400);
// // $diff -= $days*86400;
// // $hours = floor($diff/3600);
// // $diff -= $hours*3600;
// // $minutes = floor($diff/60);
// // $diff -= $minutes*60;
// // $seconds = $diff;
// // if ($months>0) {
// // // over a month old, just show date (mm/dd/yyyy format)
// // return 'on '.substr($posted_date,4,2).'/'.substr($posted_date,6,2).'/'.substr($posted_date,0,4);
// // } else {
// // if ($weeks>0) {
// // // weeks and days
// // $relative_date .= ($relative_date?', ':'').$weeks.' week'.($weeks>1?'s':'');
// // $relative_date .= $days>0?($relative_date?', ':'').$days.' day'.($days>1?'s':''):'';
// // } elseif ($days>0) {
// // // days and hours
// // $relative_date .= ($relative_date?', ':'').$days.' day'.($days>1?'s':'');
// // $relative_date .= $hours>0?($relative_date?', ':'').$hours.' hour'.($hours>1?'s':''):'';
// // } elseif ($hours>0) {
// // // hours and minutes
// // $relative_date .= ($relative_date?', ':'').$hours.' hour'.($hours>1?'s':'');
// // $relative_date .= $minutes>0?($relative_date?', ':'').$minutes.' minute'.($minutes>1?'s':''):'';
// // } elseif ($minutes>0) {
// // // minutes only
// // $relative_date .= ($relative_date?', ':'').$minutes.' minute'.($minutes>1?'s':'');
// // } else {
// // // seconds only
// // $relative_date .= ($relative_date?', ':'').$seconds.' second'.($seconds>1?'s':'');
// // }
// // }
// // // show relative date and add proper verbiage
// // return $relative_date.' ago';
// return "";
// }
//}
/// <summary>
/// Formats the range.
/// </summary>
/// <param name="cultureInfo">The culture info.</param>
/// <param name="startDate">The start date.</param>
/// <param name="endDate">The end date.</param>
/// <returns></returns>
public static string FormatRange(this CultureInfo cultureInfo, DateTime startDate, DateTime endDate)
{
switch (cultureInfo.TwoLetterISOLanguageName)
{
default:
if ((startDate != DateTime.MinValue) && (endDate != DateTime.MinValue))
{
if ((startDate.Year == endDate.Year) && (startDate.Month == endDate.Month) && (startDate.Day == endDate.Day))
return startDate.ToString("MMMM d, yyyy", CultureInfo.InvariantCulture);
if ((startDate.Year == endDate.Year) && (startDate.Month == endDate.Month))
return string.Format(startDate.ToString("MMMM d-{0}, yyyy", CultureInfo.InvariantCulture), endDate.Day);
if (startDate.Year == endDate.Year)
return string.Format(startDate.ToString("MMMM d - {0}, yyyy", CultureInfo.InvariantCulture), endDate.ToString("MMMM d", CultureInfo.InvariantCulture));
return startDate.ToString("MMMM d, yyyy", CultureInfo.InvariantCulture) + " - " + endDate.ToString("MMMM d, yyyy", CultureInfo.InvariantCulture);
}
else if (startDate != DateTime.MinValue)
return startDate.ToString("MMMM d, yyyy", CultureInfo.InvariantCulture);
return endDate.ToString("MMMM d, yyyy", CultureInfo.InvariantCulture);
}
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.IO.DirectoryInfo.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.IO
{
sealed public partial class DirectoryInfo : FileSystemInfo
{
#region Methods and constructors
public void Create(System.Security.AccessControl.DirectorySecurity directorySecurity)
{
}
public void Create()
{
}
public System.IO.DirectoryInfo CreateSubdirectory(string path, System.Security.AccessControl.DirectorySecurity directorySecurity)
{
Contract.Ensures(Contract.Result<System.IO.DirectoryInfo>() != null);
Contract.Ensures(this.FullPath != null);
return default(System.IO.DirectoryInfo);
}
public System.IO.DirectoryInfo CreateSubdirectory(string path)
{
Contract.Ensures(Contract.Result<System.IO.DirectoryInfo>() != null);
Contract.Ensures(this.FullPath != null);
return default(System.IO.DirectoryInfo);
}
public void Delete(bool recursive)
{
}
public override void Delete()
{
}
public DirectoryInfo(string path)
{
Contract.Ensures((this.OriginalPath.Length - path.Length) <= 0);
Contract.Ensures(this.OriginalPath != null);
}
public IEnumerable<System.IO.DirectoryInfo> EnumerateDirectories(string searchPattern, SearchOption searchOption)
{
return default(IEnumerable<System.IO.DirectoryInfo>);
}
public IEnumerable<System.IO.DirectoryInfo> EnumerateDirectories()
{
return default(IEnumerable<System.IO.DirectoryInfo>);
}
public IEnumerable<System.IO.DirectoryInfo> EnumerateDirectories(string searchPattern)
{
return default(IEnumerable<System.IO.DirectoryInfo>);
}
public IEnumerable<FileInfo> EnumerateFiles(string searchPattern, SearchOption searchOption)
{
return default(IEnumerable<FileInfo>);
}
public IEnumerable<FileInfo> EnumerateFiles(string searchPattern)
{
return default(IEnumerable<FileInfo>);
}
public IEnumerable<FileInfo> EnumerateFiles()
{
return default(IEnumerable<FileInfo>);
}
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string searchPattern, SearchOption searchOption)
{
return default(IEnumerable<FileSystemInfo>);
}
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string searchPattern)
{
return default(IEnumerable<FileSystemInfo>);
}
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos()
{
return default(IEnumerable<FileSystemInfo>);
}
public System.Security.AccessControl.DirectorySecurity GetAccessControl()
{
return default(System.Security.AccessControl.DirectorySecurity);
}
public System.Security.AccessControl.DirectorySecurity GetAccessControl(System.Security.AccessControl.AccessControlSections includeSections)
{
return default(System.Security.AccessControl.DirectorySecurity);
}
public System.IO.DirectoryInfo[] GetDirectories()
{
Contract.Ensures(Contract.Result<System.IO.DirectoryInfo[]>() != null);
return default(System.IO.DirectoryInfo[]);
}
public System.IO.DirectoryInfo[] GetDirectories(string searchPattern)
{
Contract.Ensures(Contract.Result<System.IO.DirectoryInfo[]>() != null);
return default(System.IO.DirectoryInfo[]);
}
public System.IO.DirectoryInfo[] GetDirectories(string searchPattern, SearchOption searchOption)
{
Contract.Ensures(Contract.Result<System.IO.DirectoryInfo[]>() != null);
return default(System.IO.DirectoryInfo[]);
}
public FileInfo[] GetFiles(string searchPattern)
{
Contract.Ensures(Contract.Result<System.IO.FileInfo[]>() != null);
return default(FileInfo[]);
}
public FileInfo[] GetFiles()
{
Contract.Ensures(Contract.Result<System.IO.FileInfo[]>() != null);
return default(FileInfo[]);
}
public FileInfo[] GetFiles(string searchPattern, SearchOption searchOption)
{
Contract.Ensures(Contract.Result<System.IO.FileInfo[]>() != null);
return default(FileInfo[]);
}
public FileSystemInfo[] GetFileSystemInfos(string searchPattern)
{
Contract.Ensures(Contract.Result<System.IO.FileSystemInfo[]>() != null);
return default(FileSystemInfo[]);
}
public FileSystemInfo[] GetFileSystemInfos()
{
Contract.Ensures(Contract.Result<System.IO.FileSystemInfo[]>() != null);
return default(FileSystemInfo[]);
}
public FileSystemInfo[] GetFileSystemInfos(string searchPattern, SearchOption searchOption)
{
Contract.Ensures(Contract.Result<System.IO.FileSystemInfo[]>() != null);
return default(FileSystemInfo[]);
}
public void MoveTo(string destDirName)
{
Contract.Ensures(destDirName == this.OriginalPath);
Contract.Ensures(this.OriginalPath != null);
}
public void SetAccessControl(System.Security.AccessControl.DirectorySecurity directorySecurity)
{
}
public override string ToString()
{
return default(string);
}
#endregion
#region Properties and indexers
public override bool Exists
{
get
{
return default(bool);
}
}
public override string Name
{
get
{
return default(string);
}
}
public System.IO.DirectoryInfo Parent
{
get
{
Contract.Ensures(this.FullPath != null);
return default(System.IO.DirectoryInfo);
}
}
public System.IO.DirectoryInfo Root
{
get
{
Contract.Ensures(0 <= this.FullPath.Length);
Contract.Ensures(Contract.Result<System.IO.DirectoryInfo>() != null);
Contract.Ensures(this.FullPath != null);
return default(System.IO.DirectoryInfo);
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Sql
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
/// <summary>
/// The Azure SQL Database management API provides a RESTful set of web
/// services that interact with Azure SQL Database services to manage your
/// databases. The API enables you to create, retrieve, update, and delete
/// databases.
/// </summary>
public partial class SqlManagementClient : ServiceClient<SqlManagementClient>, ISqlManagementClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// The subscription ID that identifies an Azure subscription.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IBackupLongTermRetentionPoliciesOperations.
/// </summary>
public virtual IBackupLongTermRetentionPoliciesOperations BackupLongTermRetentionPolicies { get; private set; }
/// <summary>
/// Gets the IBackupLongTermRetentionVaultsOperations.
/// </summary>
public virtual IBackupLongTermRetentionVaultsOperations BackupLongTermRetentionVaults { get; private set; }
/// <summary>
/// Gets the IRestorePointsOperations.
/// </summary>
public virtual IRestorePointsOperations RestorePoints { get; private set; }
/// <summary>
/// Gets the IRecoverableDatabasesOperations.
/// </summary>
public virtual IRecoverableDatabasesOperations RecoverableDatabases { get; private set; }
/// <summary>
/// Gets the IRestorableDroppedDatabasesOperations.
/// </summary>
public virtual IRestorableDroppedDatabasesOperations RestorableDroppedDatabases { get; private set; }
/// <summary>
/// Gets the ICapabilitiesOperations.
/// </summary>
public virtual ICapabilitiesOperations Capabilities { get; private set; }
/// <summary>
/// Gets the IServerConnectionPoliciesOperations.
/// </summary>
public virtual IServerConnectionPoliciesOperations ServerConnectionPolicies { get; private set; }
/// <summary>
/// Gets the IDatabaseThreatDetectionPoliciesOperations.
/// </summary>
public virtual IDatabaseThreatDetectionPoliciesOperations DatabaseThreatDetectionPolicies { get; private set; }
/// <summary>
/// Gets the IDataMaskingPoliciesOperations.
/// </summary>
public virtual IDataMaskingPoliciesOperations DataMaskingPolicies { get; private set; }
/// <summary>
/// Gets the IDataMaskingRulesOperations.
/// </summary>
public virtual IDataMaskingRulesOperations DataMaskingRules { get; private set; }
/// <summary>
/// Gets the IFirewallRulesOperations.
/// </summary>
public virtual IFirewallRulesOperations FirewallRules { get; private set; }
/// <summary>
/// Gets the IGeoBackupPoliciesOperations.
/// </summary>
public virtual IGeoBackupPoliciesOperations GeoBackupPolicies { get; private set; }
/// <summary>
/// Gets the IDatabasesOperations.
/// </summary>
public virtual IDatabasesOperations Databases { get; private set; }
/// <summary>
/// Gets the IElasticPoolsOperations.
/// </summary>
public virtual IElasticPoolsOperations ElasticPools { get; private set; }
/// <summary>
/// Gets the IOperations.
/// </summary>
public virtual IOperations Operations { get; private set; }
/// <summary>
/// Gets the IReplicationLinksOperations.
/// </summary>
public virtual IReplicationLinksOperations ReplicationLinks { get; private set; }
/// <summary>
/// Gets the IServerAzureADAdministratorsOperations.
/// </summary>
public virtual IServerAzureADAdministratorsOperations ServerAzureADAdministrators { get; private set; }
/// <summary>
/// Gets the IServerCommunicationLinksOperations.
/// </summary>
public virtual IServerCommunicationLinksOperations ServerCommunicationLinks { get; private set; }
/// <summary>
/// Gets the IServiceObjectivesOperations.
/// </summary>
public virtual IServiceObjectivesOperations ServiceObjectives { get; private set; }
/// <summary>
/// Gets the IServersOperations.
/// </summary>
public virtual IServersOperations Servers { get; private set; }
/// <summary>
/// Gets the IElasticPoolActivitiesOperations.
/// </summary>
public virtual IElasticPoolActivitiesOperations ElasticPoolActivities { get; private set; }
/// <summary>
/// Gets the IElasticPoolDatabaseActivitiesOperations.
/// </summary>
public virtual IElasticPoolDatabaseActivitiesOperations ElasticPoolDatabaseActivities { get; private set; }
/// <summary>
/// Gets the IRecommendedElasticPoolsOperations.
/// </summary>
public virtual IRecommendedElasticPoolsOperations RecommendedElasticPools { get; private set; }
/// <summary>
/// Gets the IServiceTierAdvisorsOperations.
/// </summary>
public virtual IServiceTierAdvisorsOperations ServiceTierAdvisors { get; private set; }
/// <summary>
/// Gets the ITransparentDataEncryptionsOperations.
/// </summary>
public virtual ITransparentDataEncryptionsOperations TransparentDataEncryptions { get; private set; }
/// <summary>
/// Gets the ITransparentDataEncryptionActivitiesOperations.
/// </summary>
public virtual ITransparentDataEncryptionActivitiesOperations TransparentDataEncryptionActivities { get; private set; }
/// <summary>
/// Gets the IServerUsagesOperations.
/// </summary>
public virtual IServerUsagesOperations ServerUsages { get; private set; }
/// <summary>
/// Gets the IDatabaseUsagesOperations.
/// </summary>
public virtual IDatabaseUsagesOperations DatabaseUsages { get; private set; }
/// <summary>
/// Gets the IDatabaseBlobAuditingPoliciesOperations.
/// </summary>
public virtual IDatabaseBlobAuditingPoliciesOperations DatabaseBlobAuditingPolicies { get; private set; }
/// <summary>
/// Gets the IEncryptionProtectorsOperations.
/// </summary>
public virtual IEncryptionProtectorsOperations EncryptionProtectors { get; private set; }
/// <summary>
/// Gets the IFailoverGroupsOperations.
/// </summary>
public virtual IFailoverGroupsOperations FailoverGroups { get; private set; }
/// <summary>
/// Gets the IServerKeysOperations.
/// </summary>
public virtual IServerKeysOperations ServerKeys { get; private set; }
/// <summary>
/// Gets the ISyncAgentsOperations.
/// </summary>
public virtual ISyncAgentsOperations SyncAgents { get; private set; }
/// <summary>
/// Gets the ISyncGroupsOperations.
/// </summary>
public virtual ISyncGroupsOperations SyncGroups { get; private set; }
/// <summary>
/// Gets the ISyncMembersOperations.
/// </summary>
public virtual ISyncMembersOperations SyncMembers { get; private set; }
/// <summary>
/// Gets the IVirtualNetworkRulesOperations.
/// </summary>
public virtual IVirtualNetworkRulesOperations VirtualNetworkRules { get; private set; }
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected SqlManagementClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected SqlManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected SqlManagementClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected SqlManagementClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SqlManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SqlManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SqlManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SqlManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
BackupLongTermRetentionPolicies = new BackupLongTermRetentionPoliciesOperations(this);
BackupLongTermRetentionVaults = new BackupLongTermRetentionVaultsOperations(this);
RestorePoints = new RestorePointsOperations(this);
RecoverableDatabases = new RecoverableDatabasesOperations(this);
RestorableDroppedDatabases = new RestorableDroppedDatabasesOperations(this);
Capabilities = new CapabilitiesOperations(this);
ServerConnectionPolicies = new ServerConnectionPoliciesOperations(this);
DatabaseThreatDetectionPolicies = new DatabaseThreatDetectionPoliciesOperations(this);
DataMaskingPolicies = new DataMaskingPoliciesOperations(this);
DataMaskingRules = new DataMaskingRulesOperations(this);
FirewallRules = new FirewallRulesOperations(this);
GeoBackupPolicies = new GeoBackupPoliciesOperations(this);
Databases = new DatabasesOperations(this);
ElasticPools = new ElasticPoolsOperations(this);
Operations = new Operations(this);
ReplicationLinks = new ReplicationLinksOperations(this);
ServerAzureADAdministrators = new ServerAzureADAdministratorsOperations(this);
ServerCommunicationLinks = new ServerCommunicationLinksOperations(this);
ServiceObjectives = new ServiceObjectivesOperations(this);
Servers = new ServersOperations(this);
ElasticPoolActivities = new ElasticPoolActivitiesOperations(this);
ElasticPoolDatabaseActivities = new ElasticPoolDatabaseActivitiesOperations(this);
RecommendedElasticPools = new RecommendedElasticPoolsOperations(this);
ServiceTierAdvisors = new ServiceTierAdvisorsOperations(this);
TransparentDataEncryptions = new TransparentDataEncryptionsOperations(this);
TransparentDataEncryptionActivities = new TransparentDataEncryptionActivitiesOperations(this);
ServerUsages = new ServerUsagesOperations(this);
DatabaseUsages = new DatabaseUsagesOperations(this);
DatabaseBlobAuditingPolicies = new DatabaseBlobAuditingPoliciesOperations(this);
EncryptionProtectors = new EncryptionProtectorsOperations(this);
FailoverGroups = new FailoverGroupsOperations(this);
ServerKeys = new ServerKeysOperations(this);
SyncAgents = new SyncAgentsOperations(this);
SyncGroups = new SyncGroupsOperations(this);
SyncMembers = new SyncMembersOperations(this);
VirtualNetworkRules = new VirtualNetworkRulesOperations(this);
BaseUri = new System.Uri("https://management.azure.com");
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
/*
* REST API Documentation for the MOTI School Bus Application
*
* The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus.
*
* OpenAPI spec version: v1
*
*
*/
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SchoolBusAPI.Authorization;
using SchoolBusAPI.Models;
using SchoolBusAPI.Services.Impl;
using SchoolBusCommon;
namespace SchoolBusAPI.Controllers
{
/// <summary>
/// Test Controller
/// </summary>
/// <remarks>
/// Provides examples of how to apply permission checks.
/// </remarks>
[Route("api/test")]
public class TestController : Controller
{
private readonly ITestService _service;
public TestController(ITestService service)
{
_service = service;
}
/// <summary>
/// Echoes headers for trouble shooting purposes.
/// </summary>
[HttpGet]
[Route("headers")]
[Produces("text/html")]
public virtual IActionResult EchoHeaders()
{
return _service.EchoHeaders();
}
/// <summary>
/// An example of applying claims based permissions using <see cref="RequiresPermissionAttribute"/>.
/// </summary>
/// <remarks>
/// The user requires the Login permission in order to call this endpoint. The attribute is applied at the controller level.
/// </remarks>
[HttpGet]
[Route("login/permission/attribute")]
[RequiresPermission(Permission.LOGIN)]
public virtual IActionResult GetLoginPermissionAttributeMessage()
{
return _service.GetLoginPermissionAttributeMessage();
}
/// <summary>
/// An example of applying claims based permissions using the <see cref="ClaimsPrincipalExtensions.HasPermissions(ClaimsPrincipal, string[])"/> extension method.
/// </summary>
/// <remarks>
/// The user requires the Login permission in order to call this endpoint. The extension method is called inside the service implementation.
/// </remarks>
[HttpGet]
[Route("login/permission/service")]
public virtual IActionResult GetLoginPermissionServiceMessage()
{
return _service.GetLoginPermissionServiceMessage();
}
[HttpGet]
[Route("authenticated")]
[Authorize]
public virtual IActionResult GetAuthenticatedMessage()
{
return _service.GetAuthenticatedMessage();
}
/// <summary>
/// An example of applying claims based permissions using <see cref="RequiresPermissionAttribute"/>.
/// </summary>
/// <remarks>
/// The user requires the Admin permission in order to call this endpoint. The attribute is applied at the controller level.
/// </remarks>
[HttpGet]
[Route("admin/permission/attribute")]
[RequiresPermission(Permission.ADMIN)]
public virtual IActionResult GetAdminPermissionAttributeMessage()
{
return _service.GetAdminPermissionAttributeMessage();
}
/// <summary>
/// An example of applying claims based permissions using <see cref="RequiresPermissionAttribute"/> at the service implementation level.
/// </summary>
/// <remarks>
/// The attribute is applied at the service implementation level. This currently does not work. Refer to the documentation on <see cref="RequiresPermissionAttribute"/> for details.
/// As a workaround use the <see cref="ClaimsPrincipalExtensions.HasPermissions(ClaimsPrincipal, string[])"/> extension method when applying permissions inside the service implementation.
/// </remarks>
[HttpGet]
[Route("admin/permission/service/attribute")]
public virtual IActionResult GetAdminPermissionServiceAttributeMessage()
{
return _service.GetAdminPermissionServiceAttributeMessage();
}
/// <summary>
/// An example of applying claims based permissions using the <see cref="ClaimsPrincipalExtensions.HasPermissions(ClaimsPrincipal, string[])"/> extension method.
/// </summary>
/// <remarks>
/// The user requires the Admin permission in order to call this endpoint. The extension method is called inside the service implementation.
/// </remarks>
[HttpGet]
[Route("admin/permission/service")]
public virtual IActionResult GetAdminPermissionServiceMessage()
{
return _service.GetAdminPermissionServiceMessage();
}
/// <summary>
/// An example of applying claims based access using the <see cref="ClaimsPrincipalExtensions.IsInGroup(this ClaimsPrincipal user, string group)"/> extension method.
/// </summary>
/// <remarks>
/// The user must be a member of the "Other" group in order to call this endpoint. The extension method is called inside the service implementation.
/// </remarks>
[HttpGet]
[Route("other/group/service")]
public virtual IActionResult GetOtherGroupServiceMessage()
{
return _service.GetOtherGroupServiceMessage();
}
}
public interface ITestService
{
IActionResult EchoHeaders();
IActionResult GetLoginPermissionAttributeMessage();
IActionResult GetLoginPermissionServiceMessage();
IActionResult GetAuthenticatedMessage();
IActionResult GetAdminPermissionAttributeMessage();
IActionResult GetAdminPermissionServiceAttributeMessage();
IActionResult GetAdminPermissionServiceMessage();
IActionResult GetOtherGroupServiceMessage();
}
/// <summary>
/// TestService, the service implementation for <see cref="TestController"/>
/// </summary>
/// <remarks>
/// Provides an example of how to split up the controller and service implementation while still being able to apply permissions
/// checks to the authenticated user.
/// </remarks>
public class TestService : ServiceBase, ITestService
{
public TestService(IHttpContextAccessor httpContextAccessor, DbAppContext context) : base(httpContextAccessor, context)
{
// Just pass things along to the base class.
}
/// <summary>
/// Echoes headers for trouble shooting purposes.
/// </summary>
public IActionResult EchoHeaders()
{
return Ok(Request.Headers.ToHtml());
}
/// <summary>
/// An example of relying on the controller level to apply permissions.
/// </summary>
public IActionResult GetAuthenticatedMessage()
{
return Ok("You have been authenticated and authorized.");
}
/// <summary>
/// An example of relying on the controller level to apply permissions.
/// </summary>
public IActionResult GetLoginPermissionAttributeMessage()
{
return Ok("You have permission to login to the application. Permissions (permission based authorization) were checked using the RequiresPermission attribute set on the controller method.");
}
/// <summary>
/// An example of using the <see cref="ClaimsPrincipalExtensions.HasPermissions(ClaimsPrincipal, string[])"/> extension method at the service implementation level.
/// </summary>
public IActionResult GetLoginPermissionServiceMessage()
{
if (User.HasPermissions(Permission.LOGIN))
{
return Ok("You have permission to login to the application. Permissions (permission based authorization) were checked inside the service implementation using the HasPermissions extension method.");
}
else
{
return new ChallengeResult();
}
}
/// <summary>
/// An example of relying on the controller level to apply permissions.
/// </summary>
public IActionResult GetAdminPermissionAttributeMessage()
{
return Ok("You have Admin permission to the application. Permissions (permission based authorization) were checked using the RequiresPermission attribute set on the controller method.");
}
/// <summary>
/// An example of applying the <see cref="RequiresPermissionAttribute"/> at the service level.
/// </summary>
/// <remarks>
/// This currently does not work. Refer to the documentation on <see cref="RequiresPermissionAttribute"/> for details.
/// As a workaround use the <see cref="ClaimsPrincipalExtensions.HasPermissions(ClaimsPrincipal, string[])"/> extension method when applying permissions inside the service implementation.
/// </remarks>
[RequiresPermission(Permission.ADMIN)]
public IActionResult GetAdminPermissionServiceAttributeMessage()
{
return Ok("You have Admin permission to the application. Permissions (permission based authorization) were checked using the RequiresPermission attribute set on the service method.");
}
/// <summary>
/// An example of using the <see cref="ClaimsPrincipalExtensions.HasPermissions(ClaimsPrincipal, string[])"/> extension method at the service implementation level.
/// </summary>
public IActionResult GetAdminPermissionServiceMessage()
{
if (User.HasPermissions(Permission.ADMIN))
{
return Ok("You have Admin permission to the application. Permissions (permission based authorization) were checked inside the service implementation using the HasPermissions extension method.");
}
else
{
return new ChallengeResult();
}
}
/// <summary>
/// An example of using the <see cref="ClaimsPrincipalExtensions.IsInGroup(this ClaimsPrincipal user, string group)"/> extension method at the service implementation level.
/// </summary>
public IActionResult GetOtherGroupServiceMessage()
{
if (User.IsInGroup("Other"))
{
return Ok("You are a member of the \"Other\" group. Group membership was checked (via claims based authorization) inside the service implementation using the IsInGroup extension method.");
}
else
{
return new ChallengeResult();
}
}
}
}
| |
using Aspose.Email;
using Aspose.Email.Mapi;
using Aspose.Email.Storage.Mbox;
using Aspose.Email.Storage.Pst;
using Aspose.Slides;
using System;
using System.IO;
namespace Aspose.Email.Live.Demos.UI.Services.Email
{
public partial class EmailService
{
public void ConvertPst(Stream input, string shortResourceNameWithExtension, IOutputHandler handler, string outputType)
{
PrepareOutputType(ref outputType);
switch (outputType)
{
case "eml": ConvertPstToEml(input, shortResourceNameWithExtension, handler); break;
case "msg": ConvertPstToMsg(input, shortResourceNameWithExtension, handler); break;
case "mbox": ConvertPstToMbox(input, shortResourceNameWithExtension, handler); break;
case "pst": ReturnSame(input, shortResourceNameWithExtension, handler); break;
case "mht": ConvertPstToMht(input, shortResourceNameWithExtension, handler); break;
case "html": ConvertPstToHtml(input, shortResourceNameWithExtension, handler); break;
case "svg": ConvertPstToSvg(input, shortResourceNameWithExtension, handler); break;
case "tiff": ConvertPstToTiff(input, shortResourceNameWithExtension, handler); break;
case "jpg": ConvertPstToJpg(input, shortResourceNameWithExtension, handler); break;
case "bmp": ConvertPstToBmp(input, shortResourceNameWithExtension, handler); break;
case "png": ConvertPstToPng(input, shortResourceNameWithExtension, handler); break;
case "pdf": ConvertPstToPdf(input, shortResourceNameWithExtension, handler); break;
case "doc": ConvertPstToDoc(input, shortResourceNameWithExtension, handler); break;
case "ppt": ConvertPstToPpt(input, shortResourceNameWithExtension, handler); break;
case "rtf": ConvertPstToRtf(input, shortResourceNameWithExtension, handler); break;
case "docx": ConvertPstToDocx(input, shortResourceNameWithExtension, handler); break;
case "docm": ConvertPstToDocm(input, shortResourceNameWithExtension, handler); break;
case "dotx": ConvertPstToDotx(input, shortResourceNameWithExtension, handler); break;
case "dotm": ConvertPstToDotm(input, shortResourceNameWithExtension, handler); break;
case "odt": ConvertPstToOdt(input, shortResourceNameWithExtension, handler); break;
case "ott": ConvertPstToOtt(input, shortResourceNameWithExtension, handler); break;
case "epub": ConvertPstToEpub(input, shortResourceNameWithExtension, handler); break;
case "txt": ConvertPstToTxt(input, shortResourceNameWithExtension, handler); break;
case "emf": ConvertPstToEmf(input, shortResourceNameWithExtension, handler); break;
case "xps": ConvertPstToXps(input, shortResourceNameWithExtension, handler); break;
case "pcl": ConvertPstToPcl(input, shortResourceNameWithExtension, handler); break;
case "ps": ConvertPstToPs(input, shortResourceNameWithExtension, handler); break;
case "mhtml": ConvertPstToMhtml(input, shortResourceNameWithExtension, handler); break;
default:
throw new NotSupportedException($"Output type not supported {outputType.ToUpperInvariant()}");
}
}
public void ConvertPstToMsg(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
using (var personalStorage = PersonalStorage.FromStream(input))
{
int i = 0;
HandleFolderAndSubfolders(mapiMessage =>
{
using (var output = handler.CreateOutputStream(shortResourceNameWithExtension + "_Message" + i++ + ".msg"))
mapiMessage.Save(output, SaveOptions.DefaultMsgUnicode);
}, personalStorage.RootFolder);
}
}
public void ConvertPstToMht(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
// Save as mht with header
var mhtSaveOptions = new MhtSaveOptions
{
//Specify formatting options required
//Here we are specifying to write header informations to output without writing extra print header
//and the output headers should display as the original headers in message
MhtFormatOptions = MhtFormatOptions.WriteHeader | MhtFormatOptions.HideExtraPrintHeader | MhtFormatOptions.DisplayAsOutlook,
// Check the body encoding for validity.
CheckBodyContentEncoding = true
};
using (var personalStorage = PersonalStorage.FromStream(input))
{
int i = 0;
HandleFolderAndSubfolders(mapiMessage =>
{
using (var output = handler.CreateOutputStream(shortResourceNameWithExtension + "_Message" + i++ + ".mht"))
mapiMessage.Save(output, mhtSaveOptions);
}, personalStorage.RootFolder);
}
}
public void ConvertPstToHtml(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Html);
}
public void ConvertPstToSvg(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Svg);
}
public void ConvertPstToTiff(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Tiff);
}
public void ConvertPstToJpg(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Jpeg);
}
public void ConvertPstToBmp(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Bmp);
}
public void ConvertPstToPng(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Png);
}
public void ConvertPstToEml(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
using (var personalStorage = PersonalStorage.FromStream(input))
{
int i = 0;
HandleFolderAndSubfolders(mapiMessage =>
{
using (var output = handler.CreateOutputStream(shortResourceNameWithExtension + "_Message" + i++ + ".eml"))
mapiMessage.Save(output, SaveOptions.DefaultEml);
}, personalStorage.RootFolder);
}
}
///<Summary>
/// ConvertPstToMbox method to convert pst to mbox file
///</Summary>
public void ConvertPstToMbox(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
using (var output = handler.CreateOutputStream(Path.ChangeExtension(shortResourceNameWithExtension, ".mbox")))
{
var options = new MailConversionOptions();
using (var writer = new MboxrdStorageWriter(output, false))
{
using (var pst = PersonalStorage.FromStream(input))
{
HandleFolderAndSubfolders(mapiMessage =>
{
var msg = mapiMessage.ToMailMessage(options);
writer.WriteMessage(msg);
}, pst.RootFolder);
}
}
}
}
public void ConvertPstToPdf(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Pdf);
}
public void ConvertPstToDoc(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Doc);
}
public void ConvertPstToPpt(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
using (var personalStorage = PersonalStorage.FromStream(input))
{
using (var presentation = new Presentation())
{
var firstSlide = presentation.Slides[0];
var renameCallback = new ImageSavingCallback(handler);
HandleFolderAndSubfolders(mapiMessage =>
{
var newSlide = presentation.Slides.AddClone(firstSlide);
AddMessageInSlide(presentation, newSlide, mapiMessage, renameCallback);
}, personalStorage.RootFolder);
presentation.Slides.Remove(firstSlide);
using (var output = handler.CreateOutputStream(Path.ChangeExtension(shortResourceNameWithExtension, ".ppt")))
presentation.Save(output, Aspose.Slides.Export.SaveFormat.Ppt);
}
}
}
public void ConvertPstToRtf(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Rtf);
}
public void ConvertPstToDocx(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Docx);
}
public void ConvertPstToDocm(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Docm);
}
public void ConvertPstToDotx(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Dotx);
}
public void ConvertPstToDotm(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Dotm);
}
public void ConvertPstToOdt(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Odt);
}
public void ConvertPstToOtt(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Ott);
}
public void ConvertPstToEpub(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Epub);
}
public void ConvertPstToTxt(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Text);
}
public void ConvertPstToEmf(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Emf);
}
public void ConvertPstToXps(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Xps);
}
public void ConvertPstToPcl(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Pcl);
}
public void ConvertPstToPs(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Ps);
}
public void ConvertPstToMhtml(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Mhtml);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
namespace NntpClientLib
{
public delegate void ReceiveLine(string line);
public class Rfc977NntpClientWithExtensions : Rfc977NntpClient
{
private List<string> m_supportedCommands = new List<string>();
private bool m_supportsXover;
/// <summary>
/// Gets a value indicating whether [supports xover].
/// </summary>
/// <value><c>true</c> if [supports xover]; otherwise, <c>false</c>.</value>
public bool SupportsXover
{
get { return m_supportsXover; }
}
private bool m_supportsListActive;
/// <summary>
/// Gets a value indicating whether [supports list active].
/// </summary>
/// <value><c>true</c> if [supports list active]; otherwise, <c>false</c>.</value>
public bool SupportsListActive
{
get { return m_supportsListActive; }
}
private bool m_supportsXhdr;
/// <summary>
/// Gets a value indicating whether [supports XHDR].
/// </summary>
/// <value><c>true</c> if [supports XHDR]; otherwise, <c>false</c>.</value>
public bool SupportsXhdr
{
get { return m_supportsXhdr; }
}
private bool m_supportsXgtitle;
/// <summary>
/// Gets a value indicating whether [supports xgtitle].
/// </summary>
/// <value><c>true</c> if [supports xgtitle]; otherwise, <c>false</c>.</value>
public bool SupportsXgtitle
{
get { return m_supportsXgtitle; }
}
private bool m_supportsXpat;
public bool SupportsXpat
{
get { return m_supportsXpat; }
}
/// <summary>
/// Connects using the specified host name and port number.
/// </summary>
/// <param name="hostName">Name of the host.</param>
/// <param name="port">The port.</param>
public override void Connect(string hostName, int port)
{
Connect(hostName,port,false);
}
/// <summary>
/// Connects using the specified host name and port number.
/// </summary>
/// <param name="hostName">Name of the host.</param>
/// <param name="port">The port.</param>
/// <param name="useSsl">Connect with SSL</param>
public override void Connect(string hostName, int port, bool useSsl)
{
base.Connect(hostName, port, useSsl);
CheckToSupportedExtensions();
}
/// <summary>
/// Connects the specified host name.
/// </summary>
/// <param name="hostName">Name of the host.</param>
/// <param name="port">The port.</param>
/// <param name="userName">Name of the user.</param>
/// <param name="password">The password.</param>
public virtual void Connect(string hostName, int port, string userName, string password)
{
Connect(hostName,port,userName,password,true);
}
/// <summary>
/// Connects the specified host name.
/// </summary>
/// <param name="hostName">Name of the host.</param>
/// <param name="port">The port.</param>
/// <param name="userName">Name of the user.</param>
/// <param name="password">The password.</param>
/// <param name="useSsl">Connect with SSL</param>
public virtual void Connect(string hostName, int port, string userName, string password, bool useSsl)
{
base.Connect(hostName, port, useSsl);
AuthenticateUser(userName, password);
CheckToSupportedExtensions();
}
/// <summary>
/// Checks to supported extensions.
/// </summary>
private void CheckToSupportedExtensions()
{
foreach (string hs in RetrieveHelp())
{
string s = hs.ToLower(System.Globalization.CultureInfo.InvariantCulture);
if (s.IndexOf("xover") != -1)
{
m_supportsXover = true;
}
else if (s.IndexOf("list") != -1)
{
if (s.IndexOf("active") != -1)
{
m_supportsListActive = true;
}
}
else if (s.IndexOf("xhdr") != -1)
{
m_supportsXhdr = true;
}
else if (s.IndexOf("xgtitle") != -1)
{
m_supportsXgtitle = true;
}
m_supportedCommands.Add(s);
}
}
/// <summary>
/// Authenticates the user.
/// </summary>
/// <param name="userName">Name of the user.</param>
/// <param name="password">The password.</param>
public virtual void AuthenticateUser(string userName, string password)
{
NntpReaderWriter.WriteCommand("AUTHINFO USER " + userName);
NntpReaderWriter.ReadResponse();
if (NntpReaderWriter.LastResponseCode == Rfc4643ResponseCodes.PasswordRequired)
{
NntpReaderWriter.WriteCommand("AUTHINFO PASS " + password);
NntpReaderWriter.ReadResponse();
if (NntpReaderWriter.LastResponseCode != Rfc4643ResponseCodes.AuthenticationAccepted)
{
throw new NntpNotAuthorizedException(Resource.ErrorMessage30);
}
}
else
{
throw new NntpNotAuthorizedException(Resource.ErrorMessage31);
}
}
/// <summary>
/// Sends the mode reader.
/// </summary>
public void SendModeReader()
{
NntpReaderWriter.WriteCommand("MODE READER");
NntpReaderWriter.ReadResponse();
if (NntpReaderWriter.LastResponseCode == Rfc977ResponseCodes.ServerReadyPostingAllowed)
{
PostingAllowed = true;
}
else if (NntpReaderWriter.LastResponseCode == Rfc977ResponseCodes.ServerReadyNoPostingAllowed)
{
PostingAllowed = false;
}
else if (NntpReaderWriter.LastResponseCode == Rfc977ResponseCodes.CommandUnavailable)
{
throw new NntpException();
}
}
/// <summary>
/// Retrieves the newsgroups.
/// </summary>
/// <returns></returns>
public override IEnumerable<NewsgroupHeader> RetrieveNewsgroups()
{
if (m_supportsListActive)
{
foreach (string s in DoBasicCommand("LIST ACTIVE", Rfc977ResponseCodes.NewsgroupsFollow))
{
yield return NewsgroupHeader.Parse(s);
}
}
else
{
// I can't use the base class to do this.
foreach (string s in DoBasicCommand("LIST", Rfc977ResponseCodes.NewsgroupsFollow))
{
yield return NewsgroupHeader.Parse(s);
}
}
}
/// <summary>
/// Retrieves the newsgroups.
/// </summary>
/// <param name="wildcardMatch">The wildcard match.</param>
/// <returns></returns>
public virtual IEnumerable<NewsgroupHeader> RetrieveNewsgroups(string wildcardMatch)
{
if (m_supportsListActive)
{
foreach (string s in DoBasicCommand("LIST ACTIVE " + wildcardMatch, Rfc977ResponseCodes.NewsgroupsFollow))
{
yield return NewsgroupHeader.Parse(s);
}
}
else
{
throw new NotImplementedException();
}
}
/// <summary>
/// Retrieves the article headers for the specified range.
/// </summary>
/// <param name="firstArticleId">The first article id.</param>
/// <param name="lastArticleId">The last article id.</param>
/// <returns></returns>
public override IEnumerable<ArticleHeadersDictionary> RetrieveArticleHeaders(int firstArticleId, int lastArticleId)
{
if (!CurrentGroupSelected)
{
throw new NntpGroupNotSelectedException();
}
if (m_supportsXover)
{
string[] headerNames = new string[] { "Article-ID", "Subject", "From", "Date", "Message-ID", "Xref", "Bytes", "Lines"};
foreach (string s in DoArticleCommand("XOVER " + firstArticleId + "-" + lastArticleId, 224))
{
ArticleHeadersDictionary headers = new ArticleHeadersDictionary();
string[] fields = s.Split('\t');
for (int i = 0; i < headerNames.Length; i++)
{
headers.AddHeader(headerNames[i], fields[i]);
}
yield return headers;
}
}
else
{
// I can't use the base class to do this.
for (; firstArticleId < lastArticleId; firstArticleId++)
{
yield return RetrieveArticleHeader(firstArticleId);
}
}
}
/// <summary>
/// Gets the abbreviated article headers.
/// </summary>
/// <param name="firstArticleId">The first article id.</param>
/// <param name="lastArticleId">The last article id.</param>
/// <param name="receiveLine">The receive line.</param>
public void GetAbbreviatedArticleHeaders(int firstArticleId, int lastArticleId, ReceiveLine receiveLine)
{
if (!CurrentGroupSelected)
{
throw new NntpGroupNotSelectedException();
}
if (m_supportsXover)
{
foreach (string s in DoArticleCommand("XOVER " + firstArticleId + "-" + lastArticleId, 224))
{
receiveLine(s);
}
}
}
/// <summary>
/// Retrieves the specific header.
/// </summary>
/// <param name="headerLine">The header line.</param>
/// <param name="messageId">The message id.</param>
/// <returns></returns>
public IEnumerable<string> RetrieveSpecificArticleHeader(string headerLine, string messageId)
{
return RetrieveSpecificArticleHeaderCore("XHDR " + headerLine + " " + messageId);
}
/// <summary>
/// Retrieves the specific header.
/// </summary>
/// <param name="headerLine">The header line.</param>
/// <param name="articleId">The article id.</param>
/// <returns></returns>
public IEnumerable<string> RetrieveSpecificArticleHeader(string headerLine, int articleId)
{
return RetrieveSpecificArticleHeaderCore("XHDR " + headerLine + " " + articleId);
}
/// <summary>
/// Retrieves the specific header.
/// </summary>
/// <param name="headerLine">The header line.</param>
/// <param name="firstArticleId">The first article id.</param>
/// <param name="lastArticleId">The last article id.</param>
/// <returns></returns>
public IEnumerable<string> RetrieveSpecificArticleHeaders(string headerLine, int firstArticleId, int lastArticleId)
{
return RetrieveSpecificArticleHeaderCore("XHDR " + headerLine + " " + firstArticleId + "-" + lastArticleId);
}
/// <summary>
/// Retrieves the specific header. This core method implements the iteration of the XHDR command.
/// </summary>
/// <param name="command">The command.</param>
/// <returns></returns>
protected virtual IEnumerable<string> RetrieveSpecificArticleHeaderCore(string command)
{
if (!m_supportsXhdr)
{
throw new NotImplementedException();
}
foreach (string s in DoArticleCommand(command, Rfc977ResponseCodes.ArticleRetrievedHeadFollows))
{
if (!s.StartsWith("(none)"))
{
yield return s;
}
}
}
/// <summary>
/// Retrieves the specific article header using pattern. This method implements the XPAT NNTP extension
/// command.
/// </summary>
/// <param name="header">The header.</param>
/// <param name="messageId">The message id.</param>
/// <param name="patterns">The patterns.</param>
/// <returns></returns>
public IEnumerable<string> RetrieveSpecificArticleHeaderUsingPattern(string header, string messageId, string[] patterns)
{
if (!SupportsXpat)
{
throw new NotImplementedException();
}
ValidateMessageIdArgument(messageId);
return DoBasicCommand("XPAT " + header + " " + messageId + " " + string.Join(" ", patterns), 221);
}
/// <summary>
/// Retrieves the specific article header using pattern. This method implements the XPAT NNTP extension
/// command.
/// </summary>
/// <param name="header">The header.</param>
/// <param name="articleId">The article id.</param>
/// <param name="patterns">The patterns.</param>
/// <returns></returns>
public IEnumerable<string> RetrieveSpecificArticleHeaderUsingPattern(string header, int articleId, string[] patterns)
{
if (!SupportsXpat)
{
throw new NotImplementedException();
}
return DoBasicCommand("XPAT " + header + " " + articleId + " " + string.Join(" ", patterns), 221);
}
/// <summary>
/// Retrieves the specific article header using pattern. This method implements the XPAT NNTP extension
/// command.
/// </summary>
/// <param name="header">The header.</param>
/// <param name="firstArticleId">The first article id.</param>
/// <param name="lastArticleId">The last article id.</param>
/// <param name="patterns">The patterns.</param>
/// <returns></returns>
public IEnumerable<string> RetrieveSpecificArticleHeadersUsingPattern(string header, int firstArticleId, int lastArticleId, string[] patterns)
{
if (!SupportsXpat)
{
throw new NotImplementedException();
}
if (lastArticleId == -1)
{
return DoBasicCommand("XPAT " + header + " " + firstArticleId + "- " + string.Join(" ", patterns), 221);
}
else
{
return DoBasicCommand("XPAT " + header + " " + firstArticleId + "-" + lastArticleId + " " + string.Join(" ", patterns), 221);
}
}
/// <summary>
/// Retrieves the group descriptions.
/// </summary>
/// <returns></returns>
public IEnumerable<string> RetrieveGroupDescriptions()
{
if (!SupportsXgtitle)
{
throw new NotImplementedException();
}
return DoBasicCommand("XGTITLE", 282);
}
/// <summary>
/// Retrieves the group descriptions.
/// </summary>
/// <param name="wildcardMatch">The wildcard match.</param>
/// <returns></returns>
public IEnumerable<string> RetrieveGroupDescriptions(string wildcardMatch)
{
if (!SupportsXgtitle)
{
throw new NotImplementedException();
}
return DoBasicCommand("XGTITLE " + wildcardMatch, 282);
}
}
}
| |
// (c) Copyright 2012 Hewlett-Packard Development Company, L.P.
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;
namespace HpToolsLauncher
{
/// <summary>
/// This class is a direct port to C# of the java properties class
/// </summary>
public class JavaProperties : Dictionary<string, string>
{
protected JavaProperties defaults;
/// <summary>
/// Creates an empty property list with no default values.
/// </summary>
public JavaProperties()
: this(null)
{
}
/// <summary>
/// Creates an empty property list with the specified defaults.
/// </summary>
/// <param name="defaults"></param>
public JavaProperties(JavaProperties defaults)
{
this.defaults = defaults;
}
/// <summary>
/// loads properties
/// </summary>
/// <param name="reader"></param>
public void Load(TextReader reader)
{
LoadInternal(new LineReader(reader));
}
/// <summary>
/// loads properties from a file
/// </summary>
/// <param name="fullpath"></param>
public void Load(string fullpath)
{
using (FileStream s = File.OpenRead(fullpath))
{
LoadInternal(new LineReader(s));
}
}
/// <summary>
/// loads properties from stream
/// </summary>
/// <param name="inStream"></param>
public void Load(Stream inStream)
{
LoadInternal(new LineReader(inStream));
}
private void LoadInternal(LineReader lr)
{
char[] convtBuf = new char[1024];
int limit;
int keyLen;
int valueStart;
char c;
bool hasSep;
bool precedingBackslash;
while ((limit = lr.readLine()) >= 0)
{
c = '\0';
keyLen = 0;
valueStart = limit;
hasSep = false;
//System.out.println("line=<" + new String(lineBuf, 0, limit) + ">");
precedingBackslash = false;
while (keyLen < limit)
{
c = lr.lineBuf[keyLen];
//need check if escaped.
if ((c == '=' || c == ':') && !precedingBackslash)
{
valueStart = keyLen + 1;
hasSep = true;
break;
}
else if ((c == ' ' || c == '\t' || c == '\f') && !precedingBackslash)
{
valueStart = keyLen + 1;
break;
}
if (c == '\\')
{
precedingBackslash = !precedingBackslash;
}
else
{
precedingBackslash = false;
}
keyLen++;
}
while (valueStart < limit)
{
c = lr.lineBuf[valueStart];
if (c != ' ' && c != '\t' && c != '\f')
{
if (!hasSep && (c == '=' || c == ':'))
{
hasSep = true;
}
else
{
break;
}
}
valueStart++;
}
String key = LoadConvert(lr.lineBuf, 0, keyLen, convtBuf);
String value = LoadConvert(lr.lineBuf, valueStart, limit - valueStart, convtBuf);
this[key] = value;
}
}
class LineReader
{
public LineReader(Stream inStream)
{
this.inStream = inStream;
inByteBuf = new byte[8192];
}
public LineReader(TextReader reader)
{
this.reader = reader;
inCharBuf = new char[8192];
}
byte[] inByteBuf;
char[] inCharBuf;
internal char[] lineBuf = new char[1024];
int inLimit = 0;
int inOff = 0;
Stream inStream;
TextReader reader;
public int readLine()
{
int len = 0;
char c = '\0';
bool skipWhiteSpace = true;
bool isCommentLine = false;
bool isNewLine = true;
bool appendedLineBegin = false;
bool precedingBackslash = false;
bool skipLF = false;
while (true)
{
if (inOff >= inLimit)
{
inLimit = (inStream == null) ? reader.Read(inCharBuf, 0, inCharBuf.Length)
: inStream.Read(inByteBuf, 0, inByteBuf.Length);
inOff = 0;
if (inLimit <= 0)
{
if (len == 0 || isCommentLine)
{
return -1;
}
return len;
}
}
if (inStream != null)
{
//The line below is equivalent to calling a
//ISO8859-1 decoder.
c = (char)(0xff & inByteBuf[inOff++]);
}
else
{
c = inCharBuf[inOff++];
}
if (skipLF)
{
skipLF = false;
if (c == '\n')
{
continue;
}
}
if (skipWhiteSpace)
{
if (c == ' ' || c == '\t' || c == '\f')
{
continue;
}
if (!appendedLineBegin && (c == '\r' || c == '\n'))
{
continue;
}
skipWhiteSpace = false;
appendedLineBegin = false;
}
if (isNewLine)
{
isNewLine = false;
if (c == '#' || c == '!')
{
isCommentLine = true;
continue;
}
}
if (c != '\n' && c != '\r')
{
lineBuf[len++] = c;
if (len == lineBuf.Length)
{
int newLength = lineBuf.Length * 2;
if (newLength < 0)
{
newLength = Int32.MaxValue;
}
char[] buf = new char[newLength];
Array.Copy(lineBuf, 0, buf, 0, lineBuf.Length);
lineBuf = buf;
}
//flip the preceding backslash flag
if (c == '\\')
{
precedingBackslash = !precedingBackslash;
}
else
{
precedingBackslash = false;
}
}
else
{
// reached EOL
if (isCommentLine || len == 0)
{
isCommentLine = false;
isNewLine = true;
skipWhiteSpace = true;
len = 0;
continue;
}
if (inOff >= inLimit)
{
inLimit = (inStream == null)
? reader.Read(inCharBuf, 0, inCharBuf.Length)
: inStream.Read(inByteBuf, 0, inByteBuf.Length);
inOff = 0;
if (inLimit <= 0)
{
return len;
}
}
if (precedingBackslash)
{
len -= 1;
//skip the leading whitespace characters in following line
skipWhiteSpace = true;
appendedLineBegin = true;
precedingBackslash = false;
if (c == '\r')
{
skipLF = true;
}
}
else
{
return len;
}
}
}
}
}
/// <summary>
/// Converts encoded \uxxxx to unicode chars and changes special saved chars to their original forms
/// </summary>
/// <param name="in1"></param>
/// <param name="off"></param>
/// <param name="len"></param>
/// <param name="convtBuf"></param>
/// <returns></returns>
private String LoadConvert(char[] in1, int off, int len, char[] convtBuf)
{
if (convtBuf.Length < len)
{
int newLen = len * 2;
if (newLen < 0)
{
newLen = Int32.MaxValue;
}
convtBuf = new char[newLen];
}
char aChar;
char[] out1 = convtBuf;
int outLen = 0;
int end = off + len;
while (off < end)
{
aChar = in1[off++];
if (aChar == '\\')
{
aChar = in1[off++];
if (aChar == 'u')
{
// Read the xxxx
int value = 0;
for (int i = 0; i < 4; i++)
{
aChar = in1[off++];
switch (aChar)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
value = (value << 4) + aChar - '0';
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
value = (value << 4) + 10 + aChar - 'a';
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
value = (value << 4) + 10 + aChar - 'A';
break;
default:
throw new ArgumentException(
"Malformed \\uxxxx encoding.");
}
}
out1[outLen++] = (char)value;
}
else
{
if (aChar == 't') aChar = '\t';
else if (aChar == 'r') aChar = '\r';
else if (aChar == 'n') aChar = '\n';
else if (aChar == 'f') aChar = '\f';
out1[outLen++] = aChar;
}
}
else
{
out1[outLen++] = aChar;
}
}
return new String(out1, 0, outLen);
}
/// <summary>
/// Converts unicodes to encoded \uxxxx and escapes special characters with a preceding slash
/// </summary>
/// <param name="theString"></param>
/// <param name="escapeSpace"></param>
/// <param name="escapeUnicode"></param>
/// <returns></returns>
private String SaveConvert(String theString,
bool escapeSpace,
bool escapeUnicode)
{
int len = theString.Length;
int bufLen = len * 2;
if (bufLen < 0)
{
bufLen = Int32.MaxValue;
}
StringBuilder outBuffer = new StringBuilder(bufLen);
for (int x = 0; x < len; x++)
{
char aChar = theString[x];
// Handle common case first, selecting largest block that
// avoids the specials below
if ((aChar > 61) && (aChar < 127))
{
if (aChar == '\\')
{
outBuffer.Append('\\'); outBuffer.Append('\\');
continue;
}
outBuffer.Append(aChar);
continue;
}
switch (aChar)
{
case ' ':
if (x == 0 || escapeSpace)
outBuffer.Append('\\');
outBuffer.Append(' ');
break;
case '\t': outBuffer.Append('\\'); outBuffer.Append('t');
break;
case '\n': outBuffer.Append('\\'); outBuffer.Append('n');
break;
case '\r': outBuffer.Append('\\'); outBuffer.Append('r');
break;
case '\f': outBuffer.Append('\\'); outBuffer.Append('f');
break;
case '=': // Fall through
case ':': // Fall through
case '#': // Fall through
case '!':
outBuffer.Append('\\'); outBuffer.Append(aChar);
break;
default:
if (((aChar < 0x0020) || (aChar > 0x007e)) & escapeUnicode)
{
outBuffer.Append('\\');
outBuffer.Append('u');
outBuffer.Append(ToHex((aChar >> 12) & 0xF));
outBuffer.Append(ToHex((aChar >> 8) & 0xF));
outBuffer.Append(ToHex((aChar >> 4) & 0xF));
outBuffer.Append(ToHex(aChar & 0xF));
}
else
{
outBuffer.Append(aChar);
}
break;
}
}
return outBuffer.ToString();
}
private static void WriteComments(System.IO.TextWriter bw, String comments)
{
bw.Write("#");
int len = comments.Length;
int current = 0;
int last = 0;
char[] uu = new char[6];
uu[0] = '\\';
uu[1] = 'u';
while (current < len)
{
char c = comments[current];
if (c > '\u00ff' || c == '\n' || c == '\r')
{
if (last != current)
bw.Write(comments.Substring(last, current));
if (c > '\u00ff')
{
uu[2] = ToHex((c >> 12) & 0xf);
uu[3] = ToHex((c >> 8) & 0xf);
uu[4] = ToHex((c >> 4) & 0xf);
uu[5] = ToHex(c & 0xf);
bw.Write(new String(uu));
}
else
{
bw.Write(bw.NewLine);
if (c == '\r' &&
current != len - 1 &&
comments[current + 1] == '\n')
{
current++;
}
if (current == len - 1 ||
(comments[current + 1] != '#' &&
comments[current + 1] != '!'))
bw.Write("#");
}
last = current + 1;
}
current++;
}
if (last != current)
bw.Write(comments.Substring(last, current) + bw.NewLine);
}
//@Deprecated
public void Save(Stream out1, String comments)
{
try
{
Store(out1, comments);
}
catch (IOException e)
{
}
}
public void Save(String fileName, String comments)
{
Store(fileName, comments);
}
/// <summary>
/// saves the properties
/// </summary>
/// <param name="writer"></param>
/// <param name="comments"></param>
public void Store(TextWriter writer, String comments)
{
StoreInternal(writer, comments, false);
}
/// <summary>
/// saves the properties to stream
/// </summary>
/// <param name="writer"></param>
/// <param name="comments"></param>
public void Store(Stream out1, String comments)
{
TextWriter t = new StreamWriter(out1, Encoding.GetEncoding("ISO-8859-1"));
StoreInternal(t, comments, true);
}
/// <summary>
/// saves the properties to file
/// </summary>
/// <param name="writer"></param>
/// <param name="comments"></param>
public void Store(string fullpath, String comments)
{
using (StreamWriter wr = new StreamWriter(fullpath, false, Encoding.GetEncoding("ISO-8859-1")))
{
StoreInternal(wr, comments, true);
}
}
private void StoreInternal(TextWriter bw, String comments, bool escUnicode)
{
if (comments != null)
{
WriteComments(bw, comments);
}
bw.Write("#" + DateTime.Now.ToString() + bw.NewLine);
{
foreach (string key in Keys)
{
String val = (string)this[key];
string key1 = SaveConvert(key, true, escUnicode);
/* No need to escape embedded and trailing spaces for value, hence
* pass false to flag.
*/
val = SaveConvert(val, false, escUnicode);
bw.Write(key1 + "=" + val + bw.NewLine);
}
}
bw.Flush();
}
/// <summary>
/// Convert a nibble to a hex character
/// </summary>
/// <param name="nibble">nibble to convert</param>
/// <returns></returns>
private static char ToHex(int nibble)
{
return hexDigit[(nibble & 0xF)];
}
private static char[] hexDigit = {
'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
};
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Bindables;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Colour;
using osu.Framework.Graphics.Containers;
using osu.Framework.Platform;
using osu.Framework.Utils;
using osu.Game.Audio;
using osu.Game.Graphics;
using osu.Game.Rulesets.Mods;
using osu.Game.Scoring;
using osu.Game.Skinning;
using osuTK;
namespace osu.Game.Screens.Ranking.Expanded.Accuracy
{
/// <summary>
/// The component that displays the player's accuracy on the results screen.
/// </summary>
public class AccuracyCircle : CompositeDrawable
{
/// <summary>
/// Duration for the transforms causing this component to appear.
/// </summary>
public const double APPEAR_DURATION = 200;
/// <summary>
/// Delay before the accuracy circle starts filling.
/// </summary>
public const double ACCURACY_TRANSFORM_DELAY = 450;
/// <summary>
/// Duration for the accuracy circle fill.
/// </summary>
public const double ACCURACY_TRANSFORM_DURATION = 3000;
/// <summary>
/// Delay after <see cref="ACCURACY_TRANSFORM_DURATION"/> for the rank text (A/B/C/D/S/SS) to appear.
/// </summary>
public const double TEXT_APPEAR_DELAY = ACCURACY_TRANSFORM_DURATION / 2;
/// <summary>
/// Delay before the rank circles start filling.
/// </summary>
public const double RANK_CIRCLE_TRANSFORM_DELAY = 150;
/// <summary>
/// Duration for the rank circle fills.
/// </summary>
public const double RANK_CIRCLE_TRANSFORM_DURATION = 800;
/// <summary>
/// Relative width of the rank circles.
/// </summary>
public const float RANK_CIRCLE_RADIUS = 0.06f;
/// <summary>
/// Relative width of the circle showing the accuracy.
/// </summary>
private const float accuracy_circle_radius = 0.2f;
/// <summary>
/// SS is displayed as a 1% region, otherwise it would be invisible.
/// </summary>
private const double virtual_ss_percentage = 0.01;
/// <summary>
/// The easing for the circle filling transforms.
/// </summary>
public static readonly Easing ACCURACY_TRANSFORM_EASING = Easing.OutPow10;
private readonly ScoreInfo score;
private SmoothCircularProgress accuracyCircle;
private SmoothCircularProgress innerMask;
private Container<RankBadge> badges;
private RankText rankText;
private PoolableSkinnableSample scoreTickSound;
private PoolableSkinnableSample badgeTickSound;
private PoolableSkinnableSample badgeMaxSound;
private PoolableSkinnableSample swooshUpSound;
private PoolableSkinnableSample rankImpactSound;
private PoolableSkinnableSample rankApplauseSound;
private readonly Bindable<double> tickPlaybackRate = new Bindable<double>();
private double lastTickPlaybackTime;
private bool isTicking;
private readonly bool withFlair;
public AccuracyCircle(ScoreInfo score, bool withFlair = false)
{
this.score = score;
this.withFlair = withFlair;
}
[BackgroundDependencyLoader]
private void load(GameHost host)
{
InternalChildren = new Drawable[]
{
new SmoothCircularProgress
{
Name = "Background circle",
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
Colour = OsuColour.Gray(47),
Alpha = 0.5f,
InnerRadius = accuracy_circle_radius + 0.01f, // Extends a little bit into the circle
Current = { Value = 1 },
},
accuracyCircle = new SmoothCircularProgress
{
Name = "Accuracy circle",
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
Colour = ColourInfo.GradientVertical(Color4Extensions.FromHex("#7CF6FF"), Color4Extensions.FromHex("#BAFFA9")),
InnerRadius = accuracy_circle_radius,
},
new BufferedContainer
{
Name = "Graded circles",
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
Size = new Vector2(0.8f),
Padding = new MarginPadding(2),
Children = new Drawable[]
{
new SmoothCircularProgress
{
RelativeSizeAxes = Axes.Both,
Colour = OsuColour.ForRank(ScoreRank.X),
InnerRadius = RANK_CIRCLE_RADIUS,
Current = { Value = 1 }
},
new SmoothCircularProgress
{
RelativeSizeAxes = Axes.Both,
Colour = OsuColour.ForRank(ScoreRank.S),
InnerRadius = RANK_CIRCLE_RADIUS,
Current = { Value = 1 - virtual_ss_percentage }
},
new SmoothCircularProgress
{
RelativeSizeAxes = Axes.Both,
Colour = OsuColour.ForRank(ScoreRank.A),
InnerRadius = RANK_CIRCLE_RADIUS,
Current = { Value = 0.95f }
},
new SmoothCircularProgress
{
RelativeSizeAxes = Axes.Both,
Colour = OsuColour.ForRank(ScoreRank.B),
InnerRadius = RANK_CIRCLE_RADIUS,
Current = { Value = 0.9f }
},
new SmoothCircularProgress
{
RelativeSizeAxes = Axes.Both,
Colour = OsuColour.ForRank(ScoreRank.C),
InnerRadius = RANK_CIRCLE_RADIUS,
Current = { Value = 0.8f }
},
new SmoothCircularProgress
{
RelativeSizeAxes = Axes.Both,
Colour = OsuColour.ForRank(ScoreRank.D),
InnerRadius = RANK_CIRCLE_RADIUS,
Current = { Value = 0.7f }
},
new RankNotch(0),
new RankNotch((float)(1 - virtual_ss_percentage)),
new RankNotch(0.95f),
new RankNotch(0.9f),
new RankNotch(0.8f),
new RankNotch(0.7f),
new BufferedContainer
{
Name = "Graded circle mask",
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding(1),
Blending = new BlendingParameters
{
Source = BlendingType.DstColor,
Destination = BlendingType.OneMinusSrcAlpha,
SourceAlpha = BlendingType.One,
DestinationAlpha = BlendingType.SrcAlpha
},
Child = innerMask = new SmoothCircularProgress
{
RelativeSizeAxes = Axes.Both,
InnerRadius = RANK_CIRCLE_RADIUS - 0.01f,
}
}
}
},
badges = new Container<RankBadge>
{
Name = "Rank badges",
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Vertical = -15, Horizontal = -20 },
Children = new[]
{
new RankBadge(1f, getRank(ScoreRank.X)),
new RankBadge(0.95f, getRank(ScoreRank.S)),
new RankBadge(0.9f, getRank(ScoreRank.A)),
new RankBadge(0.8f, getRank(ScoreRank.B)),
new RankBadge(0.7f, getRank(ScoreRank.C)),
new RankBadge(0.35f, getRank(ScoreRank.D)),
}
},
rankText = new RankText(score.Rank)
};
if (withFlair)
{
AddRangeInternal(new Drawable[]
{
rankImpactSound = new PoolableSkinnableSample(new SampleInfo(impactSampleName)),
rankApplauseSound = new PoolableSkinnableSample(new SampleInfo(@"applause", applauseSampleName)),
scoreTickSound = new PoolableSkinnableSample(new SampleInfo(@"Results/score-tick")),
badgeTickSound = new PoolableSkinnableSample(new SampleInfo(@"Results/badge-dink")),
badgeMaxSound = new PoolableSkinnableSample(new SampleInfo(@"Results/badge-dink-max")),
swooshUpSound = new PoolableSkinnableSample(new SampleInfo(@"Results/swoosh-up")),
});
}
}
protected override void LoadComplete()
{
base.LoadComplete();
this.ScaleTo(0).Then().ScaleTo(1, APPEAR_DURATION, Easing.OutQuint);
if (withFlair)
{
const double swoosh_pre_delay = 443f;
const double swoosh_volume = 0.4f;
this.Delay(swoosh_pre_delay).Schedule(() =>
{
swooshUpSound.VolumeTo(swoosh_volume);
swooshUpSound.Play();
});
}
using (BeginDelayedSequence(RANK_CIRCLE_TRANSFORM_DELAY))
innerMask.FillTo(1f, RANK_CIRCLE_TRANSFORM_DURATION, ACCURACY_TRANSFORM_EASING);
using (BeginDelayedSequence(ACCURACY_TRANSFORM_DELAY))
{
double targetAccuracy = score.Rank == ScoreRank.X || score.Rank == ScoreRank.XH ? 1 : Math.Min(1 - virtual_ss_percentage, score.Accuracy);
accuracyCircle.FillTo(targetAccuracy, ACCURACY_TRANSFORM_DURATION, ACCURACY_TRANSFORM_EASING);
if (withFlair)
{
Schedule(() =>
{
const double score_tick_debounce_rate_start = 18f;
const double score_tick_debounce_rate_end = 300f;
const double score_tick_volume_start = 0.6f;
const double score_tick_volume_end = 1.0f;
this.TransformBindableTo(tickPlaybackRate, score_tick_debounce_rate_start);
this.TransformBindableTo(tickPlaybackRate, score_tick_debounce_rate_end, ACCURACY_TRANSFORM_DURATION, Easing.OutSine);
scoreTickSound.FrequencyTo(1 + targetAccuracy, ACCURACY_TRANSFORM_DURATION, Easing.OutSine);
scoreTickSound.VolumeTo(score_tick_volume_start).Then().VolumeTo(score_tick_volume_end, ACCURACY_TRANSFORM_DURATION, Easing.OutSine);
isTicking = true;
});
}
int badgeNum = 0;
foreach (var badge in badges)
{
if (badge.Accuracy > score.Accuracy)
continue;
using (BeginDelayedSequence(inverseEasing(ACCURACY_TRANSFORM_EASING, Math.Min(1 - virtual_ss_percentage, badge.Accuracy) / targetAccuracy) * ACCURACY_TRANSFORM_DURATION))
{
badge.Appear();
if (withFlair)
{
Schedule(() =>
{
var dink = badgeNum < badges.Count - 1 ? badgeTickSound : badgeMaxSound;
dink.FrequencyTo(1 + badgeNum++ * 0.05);
dink.Play();
});
}
}
}
using (BeginDelayedSequence(TEXT_APPEAR_DELAY))
{
rankText.Appear();
if (!withFlair) return;
Schedule(() =>
{
isTicking = false;
rankImpactSound.Play();
});
const double applause_pre_delay = 545f;
const double applause_volume = 0.8f;
using (BeginDelayedSequence(applause_pre_delay))
{
Schedule(() =>
{
rankApplauseSound.VolumeTo(applause_volume);
rankApplauseSound.Play();
});
}
}
}
}
protected override void Update()
{
base.Update();
if (isTicking && Clock.CurrentTime - lastTickPlaybackTime >= tickPlaybackRate.Value)
{
scoreTickSound?.Play();
lastTickPlaybackTime = Clock.CurrentTime;
}
}
private string applauseSampleName
{
get
{
switch (score.Rank)
{
default:
case ScoreRank.D:
return @"Results/applause-d";
case ScoreRank.C:
return @"Results/applause-c";
case ScoreRank.B:
return @"Results/applause-b";
case ScoreRank.A:
return @"Results/applause-a";
case ScoreRank.S:
case ScoreRank.SH:
case ScoreRank.X:
case ScoreRank.XH:
return @"Results/applause-s";
}
}
}
private string impactSampleName
{
get
{
switch (score.Rank)
{
default:
case ScoreRank.D:
return @"Results/rank-impact-fail-d";
case ScoreRank.C:
case ScoreRank.B:
return @"Results/rank-impact-fail";
case ScoreRank.A:
case ScoreRank.S:
case ScoreRank.SH:
return @"Results/rank-impact-pass";
case ScoreRank.X:
case ScoreRank.XH:
return @"Results/rank-impact-pass-ss";
}
}
}
private ScoreRank getRank(ScoreRank rank)
{
foreach (var mod in score.Mods.OfType<IApplicableToScoreProcessor>())
rank = mod.AdjustRank(rank, score.Accuracy);
return rank;
}
private double inverseEasing(Easing easing, double targetValue)
{
double test = 0;
double result = 0;
int count = 2;
while (Math.Abs(result - targetValue) > 0.005)
{
int dir = Math.Sign(targetValue - result);
test += dir * 1.0 / count;
result = Interpolation.ApplyEasing(easing, test);
count++;
}
return test;
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ecs-2014-11-13.normal.json service model.
*/
using System;
using Amazon.Runtime;
namespace Amazon.ECS
{
/// <summary>
/// Constants used for properties of type AgentUpdateStatus.
/// </summary>
public class AgentUpdateStatus : ConstantClass
{
/// <summary>
/// Constant FAILED for AgentUpdateStatus
/// </summary>
public static readonly AgentUpdateStatus FAILED = new AgentUpdateStatus("FAILED");
/// <summary>
/// Constant PENDING for AgentUpdateStatus
/// </summary>
public static readonly AgentUpdateStatus PENDING = new AgentUpdateStatus("PENDING");
/// <summary>
/// Constant STAGED for AgentUpdateStatus
/// </summary>
public static readonly AgentUpdateStatus STAGED = new AgentUpdateStatus("STAGED");
/// <summary>
/// Constant STAGING for AgentUpdateStatus
/// </summary>
public static readonly AgentUpdateStatus STAGING = new AgentUpdateStatus("STAGING");
/// <summary>
/// Constant UPDATED for AgentUpdateStatus
/// </summary>
public static readonly AgentUpdateStatus UPDATED = new AgentUpdateStatus("UPDATED");
/// <summary>
/// Constant UPDATING for AgentUpdateStatus
/// </summary>
public static readonly AgentUpdateStatus UPDATING = new AgentUpdateStatus("UPDATING");
/// <summary>
/// Default Constructor
/// </summary>
public AgentUpdateStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static AgentUpdateStatus FindValue(string value)
{
return FindValue<AgentUpdateStatus>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator AgentUpdateStatus(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type DesiredStatus.
/// </summary>
public class DesiredStatus : ConstantClass
{
/// <summary>
/// Constant PENDING for DesiredStatus
/// </summary>
public static readonly DesiredStatus PENDING = new DesiredStatus("PENDING");
/// <summary>
/// Constant RUNNING for DesiredStatus
/// </summary>
public static readonly DesiredStatus RUNNING = new DesiredStatus("RUNNING");
/// <summary>
/// Constant STOPPED for DesiredStatus
/// </summary>
public static readonly DesiredStatus STOPPED = new DesiredStatus("STOPPED");
/// <summary>
/// Default Constructor
/// </summary>
public DesiredStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static DesiredStatus FindValue(string value)
{
return FindValue<DesiredStatus>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator DesiredStatus(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type SortOrder.
/// </summary>
public class SortOrder : ConstantClass
{
/// <summary>
/// Constant ASC for SortOrder
/// </summary>
public static readonly SortOrder ASC = new SortOrder("ASC");
/// <summary>
/// Constant DESC for SortOrder
/// </summary>
public static readonly SortOrder DESC = new SortOrder("DESC");
/// <summary>
/// Default Constructor
/// </summary>
public SortOrder(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static SortOrder FindValue(string value)
{
return FindValue<SortOrder>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator SortOrder(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type TaskDefinitionStatus.
/// </summary>
public class TaskDefinitionStatus : ConstantClass
{
/// <summary>
/// Constant ACTIVE for TaskDefinitionStatus
/// </summary>
public static readonly TaskDefinitionStatus ACTIVE = new TaskDefinitionStatus("ACTIVE");
/// <summary>
/// Constant INACTIVE for TaskDefinitionStatus
/// </summary>
public static readonly TaskDefinitionStatus INACTIVE = new TaskDefinitionStatus("INACTIVE");
/// <summary>
/// Default Constructor
/// </summary>
public TaskDefinitionStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static TaskDefinitionStatus FindValue(string value)
{
return FindValue<TaskDefinitionStatus>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator TaskDefinitionStatus(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type TransportProtocol.
/// </summary>
public class TransportProtocol : ConstantClass
{
/// <summary>
/// Constant Tcp for TransportProtocol
/// </summary>
public static readonly TransportProtocol Tcp = new TransportProtocol("tcp");
/// <summary>
/// Constant Udp for TransportProtocol
/// </summary>
public static readonly TransportProtocol Udp = new TransportProtocol("udp");
/// <summary>
/// Default Constructor
/// </summary>
public TransportProtocol(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static TransportProtocol FindValue(string value)
{
return FindValue<TransportProtocol>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator TransportProtocol(string value)
{
return FindValue(value);
}
}
}
| |
// ByteFX.Data data access components for .Net
// Copyright (C) 2002-2003 ByteFX, Inc.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.ComponentModel;
using System.Data;
using System.Text;
namespace ByteFX.Data.MySqlClient
{
/// <summary>
/// Automatically generates single-table commands used to reconcile changes made to a DataSet with the associated MySQL database. This class cannot be inherited.
/// </summary>
/// <include file='docs/MySqlCommandBuilder.xml' path='MyDocs/MyMembers[@name="Class"]/*'/>
[ToolboxItem(false)]
[System.ComponentModel.DesignerCategory("Code")]
public sealed class MySqlCommandBuilder : Component
{
private MySqlDataAdapter _adapter;
private string _QuotePrefix;
private string _QuoteSuffix;
private DataTable _schema;
private string _tableName;
private MySqlCommand _updateCmd;
private MySqlCommand _insertCmd;
private MySqlCommand _deleteCmd;
#region Constructors
/// <summary>
/// Overloaded. Initializes a new instance of the SqlCommandBuilder class.
/// </summary>
public MySqlCommandBuilder()
{
}
/// <summary>
/// Overloaded. Initializes a new instance of the SqlCommandBuilder class.
/// </summary>
public MySqlCommandBuilder( MySqlDataAdapter adapter )
{
_adapter = adapter;
_adapter.RowUpdating += new MySqlRowUpdatingEventHandler( OnRowUpdating );
}
#endregion
#region Properties
/// <summary>
/// Gets or sets a MySqlDataAdapter object for which SQL statements are automatically generated.
/// </summary>
public MySqlDataAdapter DataAdapter
{
get { return _adapter; }
set
{
if (_adapter != null)
{
_adapter.RowUpdating -= new MySqlRowUpdatingEventHandler( OnRowUpdating );
}
_adapter = value;
}
}
/// <summary>
/// Gets or sets the beginning character or characters to use when specifying MySql database objects (for example, tables or columns) whose names contain characters such as spaces or reserved tokens.
/// </summary>
public string QuotePrefix
{
get { return _QuotePrefix; }
set { _QuotePrefix = value; }
}
/// <summary>
/// Gets or sets the ending character or characters to use when specifying MySql database objects (for example, tables or columns) whose names contain characters such as spaces or reserved tokens.
/// </summary>
public string QuoteSuffix
{
get { return _QuoteSuffix; }
set { _QuoteSuffix = value; }
}
#endregion
#region Public Methods
/// <summary>
/// Retrieves parameter information from the stored procedure specified in the MySqlCommand and populates the Parameters collection of the specified MySqlCommand object.
/// This method is not currently supported since stored procedures are not available in MySql.
/// </summary>
/// <param name="command">The MySqlCommand referencing the stored procedure from which the parameter information is to be derived. The derived parameters are added to the Parameters collection of the MySqlCommand.</param>
/// <exception cref="InvalidOperationException">The command text is not a valid stored procedure name.</exception>
public static void DeriveParameters(MySqlCommand command)
{
throw new MySqlException("DeriveParameters is not supported (due to MySql not supporting SP)");
}
/// <summary>
/// Gets the automatically generated MySqlCommand object required to perform deletions on the database.
/// </summary>
/// <returns></returns>
public MySqlCommand GetDeleteCommand()
{
if (_schema == null)
GenerateSchema();
return CreateDeleteCommand();
}
/// <summary>
/// Gets the automatically generated MySqlCommand object required to perform insertions on the database.
/// </summary>
/// <returns></returns>
public MySqlCommand GetInsertCommand()
{
if (_schema == null)
GenerateSchema();
return CreateInsertCommand();
}
/// <summary>
/// Gets the automatically generated MySqlCommand object required to perform updates on the database.
/// </summary>
/// <returns></returns>
public MySqlCommand GetUpdateCommand()
{
if (_schema == null)
GenerateSchema();
return CreateUpdateCommand();
}
/// <summary>
/// Refreshes the database schema information used to generate INSERT, UPDATE, or DELETE statements.
/// </summary>
public void RefreshSchema()
{
_schema = null;
_insertCmd = null;
_deleteCmd = null;
_updateCmd = null;
}
#endregion
#region Private Methods
private void GenerateSchema()
{
if (_adapter == null)
throw new MySqlException("Improper MySqlCommandBuilder state: adapter is null");
if (_adapter.SelectCommand == null)
throw new MySqlException("Improper MySqlCommandBuilder state: adapter's SelectCommand is null");
MySqlDataReader dr = _adapter.SelectCommand.ExecuteReader(CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo);
_schema = dr.GetSchemaTable();
dr.Close();
// make sure we got at least one unique or key field and count base table names
bool hasKeyOrUnique=false;
foreach (DataRow row in _schema.Rows)
{
if (true == (bool)row["IsKey"] || true == (bool)row["IsUnique"])
hasKeyOrUnique=true;
if (_tableName == null)
_tableName = (string)row["BaseTableName"];
else if (_tableName != (string)row["BaseTableName"])
throw new InvalidOperationException("MySqlCommandBuilder does not support multi-table statements");
}
if (! hasKeyOrUnique)
throw new InvalidOperationException("MySqlCommandBuilder cannot operate on tables with no unique or key columns");
}
private string Quote(string table_or_column)
{
if (_QuotePrefix == null || _QuoteSuffix == null)
return table_or_column;
return _QuotePrefix + table_or_column + _QuoteSuffix;
}
private MySqlParameter CreateParameter(DataRow row, bool Original)
{
MySqlParameter p;
if (Original)
p = new MySqlParameter( "@Original_" + (string)row["ColumnName"], (MySqlDbType)row["ProviderType"],
ParameterDirection.Input, (string)row["ColumnName"], DataRowVersion.Original, DBNull.Value );
else
p = new MySqlParameter( "@" + (string)row["ColumnName"], (MySqlDbType)row["ProviderType"],
ParameterDirection.Input, (string)row["ColumnName"], DataRowVersion.Current, DBNull.Value );
return p;
}
private MySqlCommand CreateBaseCommand()
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = _adapter.SelectCommand.Connection;
cmd.CommandTimeout = _adapter.SelectCommand.CommandTimeout;
cmd.Transaction = _adapter.SelectCommand.Transaction;
return cmd;
}
private MySqlCommand CreateDeleteCommand()
{
if (_deleteCmd != null) return _deleteCmd;
MySqlCommand cmd = CreateBaseCommand();
cmd.CommandText = "DELETE FROM " + Quote(_tableName) +
" WHERE " + CreateOriginalWhere(cmd);
_deleteCmd = cmd;
return cmd;
}
private string CreateFinalSelect(bool forinsert)
{
StringBuilder sel = new StringBuilder();
StringBuilder where = new StringBuilder();
foreach (DataRow row in _schema.Rows)
{
string colname = (string)row["ColumnName"];
if (sel.Length > 0)
sel.Append(", ");
sel.Append( colname );
if ((bool)row["IsKey"] == false) continue;
if (where.Length > 0)
where.Append(" AND ");
where.Append( "(" + colname + "=" );
if (forinsert)
{
if ((bool)row["IsAutoIncrement"])
where.Append("last_insert_id()");
else if ((bool)row["IsKey"])
where.Append("@" + colname);
}
else
{
where.Append("@Original_" + colname);
}
where.Append(")");
}
return "SELECT " + sel.ToString() + " FROM " + Quote(_tableName) +
" WHERE " + where.ToString();
}
private string CreateOriginalWhere(MySqlCommand cmd)
{
StringBuilder wherestr = new StringBuilder();
foreach (DataRow row in _schema.Rows)
{
if (! IncludedInWhereClause(row)) continue;
// first update the where clause since it will contain all parameters
if (wherestr.Length > 0)
wherestr.Append(" AND ");
string colname = Quote((string)row["ColumnName"]);
MySqlParameter op = CreateParameter(row, true);
cmd.Parameters.Add(op);
wherestr.Append( "(" + colname + "=@" + op.ParameterName);
if ((bool)row["AllowDBNull"] == true)
wherestr.Append( " or (" + colname + " IS NULL and @" + op.ParameterName + " IS NULL)");
wherestr.Append(")");
}
return wherestr.ToString();
}
private MySqlCommand CreateUpdateCommand()
{
if (_updateCmd != null) return _updateCmd;
MySqlCommand cmd = CreateBaseCommand();
StringBuilder setstr = new StringBuilder();
foreach (DataRow schemaRow in _schema.Rows)
{
string colname = Quote((string)schemaRow["ColumnName"]);
if (! IncludedInUpdate(schemaRow)) continue;
if (setstr.Length > 0)
setstr.Append(", ");
MySqlParameter p = CreateParameter(schemaRow, false);
cmd.Parameters.Add(p);
setstr.Append( colname + "=@" + p.ParameterName );
}
cmd.CommandText = "UPDATE " + Quote(_tableName) + " SET " + setstr.ToString() +
" WHERE " + CreateOriginalWhere(cmd);
cmd.CommandText += "; " + CreateFinalSelect(false);
_updateCmd = cmd;
return cmd;
}
private MySqlCommand CreateInsertCommand()
{
if (_insertCmd != null) return _insertCmd;
MySqlCommand cmd = CreateBaseCommand();
StringBuilder setstr = new StringBuilder();
StringBuilder valstr = new StringBuilder();
foreach (DataRow schemaRow in _schema.Rows)
{
string colname = Quote((string)schemaRow["ColumnName"]);
if (!IncludedInInsert(schemaRow)) continue;
if (setstr.Length > 0)
{
setstr.Append(", ");
valstr.Append(", ");
}
MySqlParameter p = CreateParameter(schemaRow, false);
cmd.Parameters.Add(p);
setstr.Append( colname );
valstr.Append( "@" + p.ParameterName );
}
cmd.CommandText = "INSERT INTO " + Quote(_tableName) + " (" + setstr.ToString() + ") " +
" VALUES (" + valstr.ToString() + ")";
cmd.CommandText += "; " + CreateFinalSelect(true);
_insertCmd = cmd;
return cmd;
}
private bool IncludedInInsert (DataRow schemaRow)
{
// If the parameter has one of these properties, then we don't include it in the insert:
// AutoIncrement, Hidden, Expression, RowVersion, ReadOnly
if ((bool) schemaRow ["IsAutoIncrement"])
return false;
/* if ((bool) schemaRow ["IsHidden"])
return false;
if ((bool) schemaRow ["IsExpression"])
return false;*/
if ((bool) schemaRow ["IsRowVersion"])
return false;
if ((bool) schemaRow ["IsReadOnly"])
return false;
return true;
}
private bool IncludedInUpdate (DataRow schemaRow)
{
// If the parameter has one of these properties, then we don't include it in the insert:
// AutoIncrement, Hidden, RowVersion
if ((bool) schemaRow ["IsAutoIncrement"])
return false;
// if ((bool) schemaRow ["IsHidden"])
// return false;
if ((bool) schemaRow ["IsRowVersion"])
return false;
return true;
}
private bool IncludedInWhereClause (DataRow schemaRow)
{
// if ((bool) schemaRow ["IsLong"])
// return false;
return true;
}
private void SetParameterValues(MySqlCommand cmd, DataRow dataRow)
{
foreach (MySqlParameter p in cmd.Parameters)
{
if (p.ParameterName.Length >= 8 && p.ParameterName.Substring(0, 8).Equals("Original"))
p.Value = dataRow[ p.SourceColumn, DataRowVersion.Original ];
else
p.Value = dataRow[ p.SourceColumn, DataRowVersion.Current ];
}
}
private void OnRowUpdating(object sender, MySqlRowUpdatingEventArgs args)
{
// make sure we are still to proceed
if (args.Status != UpdateStatus.Continue) return;
if (_schema == null)
GenerateSchema();
if (StatementType.Delete == args.StatementType)
args.Command = CreateDeleteCommand();
else if (StatementType.Update == args.StatementType)
args.Command = CreateUpdateCommand();
else if (StatementType.Insert == args.StatementType)
args.Command = CreateInsertCommand();
else if (StatementType.Select == args.StatementType)
return;
SetParameterValues(args.Command, args.Row);
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ResourceManager
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// DeploymentsOperations operations.
/// </summary>
public partial interface IDeploymentsOperations
{
/// <summary>
/// Delete deployment.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment to be deleted.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete deployment.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment to be deleted.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Checks whether deployment exists.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to check. The name is case
/// insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<bool?>> CheckExistenceWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create a named template deployment using a template.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Additional parameters supplied to the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<DeploymentExtended>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Deployment parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create a named template deployment using a template.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Additional parameters supplied to the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<DeploymentExtended>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Deployment parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get a deployment.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to get. The name is case
/// insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<DeploymentExtended>> GetWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Cancel a currently running template deployment.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> CancelWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Validate a deployment template.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Deployment to validate.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<DeploymentValidateResult>> ValidateWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Deployment parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Exports a deployment template.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<DeploymentExportResult>> ExportTemplateWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get a list of deployments.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to filter by. The name is case
/// insensitive.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<DeploymentExtended>>> ListWithHttpMessagesAsync(string resourceGroupName, ODataQuery<DeploymentExtendedFilter> odataQuery = default(ODataQuery<DeploymentExtendedFilter>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get a list of deployments.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<DeploymentExtended>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
/**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
// @Generated by gentest/gentest.rb from gentest/fixtures/YGJustifyContentTest.html
using System;
using NUnit.Framework;
namespace Facebook.Yoga
{
[TestFixture]
public class YGJustifyContentTest
{
[Test]
public void Test_justify_content_row_flex_start()
{
YogaNode root = new YogaNode();
root.FlexDirection = YogaFlexDirection.Row;
root.Width = 102;
root.Height = 102;
YogaNode root_child0 = new YogaNode();
root_child0.Width = 10;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode();
root_child1.Width = 10;
root.Insert(1, root_child1);
YogaNode root_child2 = new YogaNode();
root_child2.Width = 10;
root.Insert(2, root_child2);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(102f, root.LayoutWidth);
Assert.AreEqual(102f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(10f, root_child0.LayoutWidth);
Assert.AreEqual(102f, root_child0.LayoutHeight);
Assert.AreEqual(10f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(10f, root_child1.LayoutWidth);
Assert.AreEqual(102f, root_child1.LayoutHeight);
Assert.AreEqual(20f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(10f, root_child2.LayoutWidth);
Assert.AreEqual(102f, root_child2.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(102f, root.LayoutWidth);
Assert.AreEqual(102f, root.LayoutHeight);
Assert.AreEqual(92f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(10f, root_child0.LayoutWidth);
Assert.AreEqual(102f, root_child0.LayoutHeight);
Assert.AreEqual(82f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(10f, root_child1.LayoutWidth);
Assert.AreEqual(102f, root_child1.LayoutHeight);
Assert.AreEqual(72f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(10f, root_child2.LayoutWidth);
Assert.AreEqual(102f, root_child2.LayoutHeight);
}
[Test]
public void Test_justify_content_row_flex_end()
{
YogaNode root = new YogaNode();
root.FlexDirection = YogaFlexDirection.Row;
root.JustifyContent = YogaJustify.FlexEnd;
root.Width = 102;
root.Height = 102;
YogaNode root_child0 = new YogaNode();
root_child0.Width = 10;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode();
root_child1.Width = 10;
root.Insert(1, root_child1);
YogaNode root_child2 = new YogaNode();
root_child2.Width = 10;
root.Insert(2, root_child2);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(102f, root.LayoutWidth);
Assert.AreEqual(102f, root.LayoutHeight);
Assert.AreEqual(72f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(10f, root_child0.LayoutWidth);
Assert.AreEqual(102f, root_child0.LayoutHeight);
Assert.AreEqual(82f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(10f, root_child1.LayoutWidth);
Assert.AreEqual(102f, root_child1.LayoutHeight);
Assert.AreEqual(92f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(10f, root_child2.LayoutWidth);
Assert.AreEqual(102f, root_child2.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(102f, root.LayoutWidth);
Assert.AreEqual(102f, root.LayoutHeight);
Assert.AreEqual(20f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(10f, root_child0.LayoutWidth);
Assert.AreEqual(102f, root_child0.LayoutHeight);
Assert.AreEqual(10f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(10f, root_child1.LayoutWidth);
Assert.AreEqual(102f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(10f, root_child2.LayoutWidth);
Assert.AreEqual(102f, root_child2.LayoutHeight);
}
[Test]
public void Test_justify_content_row_center()
{
YogaNode root = new YogaNode();
root.FlexDirection = YogaFlexDirection.Row;
root.JustifyContent = YogaJustify.Center;
root.Width = 102;
root.Height = 102;
YogaNode root_child0 = new YogaNode();
root_child0.Width = 10;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode();
root_child1.Width = 10;
root.Insert(1, root_child1);
YogaNode root_child2 = new YogaNode();
root_child2.Width = 10;
root.Insert(2, root_child2);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(102f, root.LayoutWidth);
Assert.AreEqual(102f, root.LayoutHeight);
Assert.AreEqual(36f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(10f, root_child0.LayoutWidth);
Assert.AreEqual(102f, root_child0.LayoutHeight);
Assert.AreEqual(46f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(10f, root_child1.LayoutWidth);
Assert.AreEqual(102f, root_child1.LayoutHeight);
Assert.AreEqual(56f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(10f, root_child2.LayoutWidth);
Assert.AreEqual(102f, root_child2.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(102f, root.LayoutWidth);
Assert.AreEqual(102f, root.LayoutHeight);
Assert.AreEqual(56f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(10f, root_child0.LayoutWidth);
Assert.AreEqual(102f, root_child0.LayoutHeight);
Assert.AreEqual(46f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(10f, root_child1.LayoutWidth);
Assert.AreEqual(102f, root_child1.LayoutHeight);
Assert.AreEqual(36f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(10f, root_child2.LayoutWidth);
Assert.AreEqual(102f, root_child2.LayoutHeight);
}
[Test]
public void Test_justify_content_row_space_between()
{
YogaNode root = new YogaNode();
root.FlexDirection = YogaFlexDirection.Row;
root.JustifyContent = YogaJustify.SpaceBetween;
root.Width = 102;
root.Height = 102;
YogaNode root_child0 = new YogaNode();
root_child0.Width = 10;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode();
root_child1.Width = 10;
root.Insert(1, root_child1);
YogaNode root_child2 = new YogaNode();
root_child2.Width = 10;
root.Insert(2, root_child2);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(102f, root.LayoutWidth);
Assert.AreEqual(102f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(10f, root_child0.LayoutWidth);
Assert.AreEqual(102f, root_child0.LayoutHeight);
Assert.AreEqual(46f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(10f, root_child1.LayoutWidth);
Assert.AreEqual(102f, root_child1.LayoutHeight);
Assert.AreEqual(92f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(10f, root_child2.LayoutWidth);
Assert.AreEqual(102f, root_child2.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(102f, root.LayoutWidth);
Assert.AreEqual(102f, root.LayoutHeight);
Assert.AreEqual(92f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(10f, root_child0.LayoutWidth);
Assert.AreEqual(102f, root_child0.LayoutHeight);
Assert.AreEqual(46f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(10f, root_child1.LayoutWidth);
Assert.AreEqual(102f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(10f, root_child2.LayoutWidth);
Assert.AreEqual(102f, root_child2.LayoutHeight);
}
[Test]
public void Test_justify_content_row_space_around()
{
YogaNode root = new YogaNode();
root.FlexDirection = YogaFlexDirection.Row;
root.JustifyContent = YogaJustify.SpaceAround;
root.Width = 102;
root.Height = 102;
YogaNode root_child0 = new YogaNode();
root_child0.Width = 10;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode();
root_child1.Width = 10;
root.Insert(1, root_child1);
YogaNode root_child2 = new YogaNode();
root_child2.Width = 10;
root.Insert(2, root_child2);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(102f, root.LayoutWidth);
Assert.AreEqual(102f, root.LayoutHeight);
Assert.AreEqual(12f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(10f, root_child0.LayoutWidth);
Assert.AreEqual(102f, root_child0.LayoutHeight);
Assert.AreEqual(46f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(10f, root_child1.LayoutWidth);
Assert.AreEqual(102f, root_child1.LayoutHeight);
Assert.AreEqual(80f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(10f, root_child2.LayoutWidth);
Assert.AreEqual(102f, root_child2.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(102f, root.LayoutWidth);
Assert.AreEqual(102f, root.LayoutHeight);
Assert.AreEqual(80f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(10f, root_child0.LayoutWidth);
Assert.AreEqual(102f, root_child0.LayoutHeight);
Assert.AreEqual(46f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(10f, root_child1.LayoutWidth);
Assert.AreEqual(102f, root_child1.LayoutHeight);
Assert.AreEqual(12f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(10f, root_child2.LayoutWidth);
Assert.AreEqual(102f, root_child2.LayoutHeight);
}
[Test]
public void Test_justify_content_column_flex_start()
{
YogaNode root = new YogaNode();
root.Width = 102;
root.Height = 102;
YogaNode root_child0 = new YogaNode();
root_child0.Height = 10;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode();
root.Insert(1, root_child1);
YogaNode root_child2 = new YogaNode();
root_child2.Height = 10;
root.Insert(2, root_child2);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(102f, root.LayoutWidth);
Assert.AreEqual(102f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(102f, root_child0.LayoutWidth);
Assert.AreEqual(10f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(10f, root_child1.LayoutY);
Assert.AreEqual(102f, root_child1.LayoutWidth);
Assert.AreEqual(0f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child2.LayoutX);
Assert.AreEqual(10f, root_child2.LayoutY);
Assert.AreEqual(102f, root_child2.LayoutWidth);
Assert.AreEqual(10f, root_child2.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(102f, root.LayoutWidth);
Assert.AreEqual(102f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(102f, root_child0.LayoutWidth);
Assert.AreEqual(10f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(10f, root_child1.LayoutY);
Assert.AreEqual(102f, root_child1.LayoutWidth);
Assert.AreEqual(0f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child2.LayoutX);
Assert.AreEqual(10f, root_child2.LayoutY);
Assert.AreEqual(102f, root_child2.LayoutWidth);
Assert.AreEqual(10f, root_child2.LayoutHeight);
}
[Test]
public void Test_justify_content_column_flex_end()
{
YogaNode root = new YogaNode();
root.JustifyContent = YogaJustify.FlexEnd;
root.Width = 102;
root.Height = 102;
YogaNode root_child0 = new YogaNode();
root_child0.Height = 10;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode();
root_child1.Height = 10;
root.Insert(1, root_child1);
YogaNode root_child2 = new YogaNode();
root_child2.Height = 10;
root.Insert(2, root_child2);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(102f, root.LayoutWidth);
Assert.AreEqual(102f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(72f, root_child0.LayoutY);
Assert.AreEqual(102f, root_child0.LayoutWidth);
Assert.AreEqual(10f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(82f, root_child1.LayoutY);
Assert.AreEqual(102f, root_child1.LayoutWidth);
Assert.AreEqual(10f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child2.LayoutX);
Assert.AreEqual(92f, root_child2.LayoutY);
Assert.AreEqual(102f, root_child2.LayoutWidth);
Assert.AreEqual(10f, root_child2.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(102f, root.LayoutWidth);
Assert.AreEqual(102f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(72f, root_child0.LayoutY);
Assert.AreEqual(102f, root_child0.LayoutWidth);
Assert.AreEqual(10f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(82f, root_child1.LayoutY);
Assert.AreEqual(102f, root_child1.LayoutWidth);
Assert.AreEqual(10f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child2.LayoutX);
Assert.AreEqual(92f, root_child2.LayoutY);
Assert.AreEqual(102f, root_child2.LayoutWidth);
Assert.AreEqual(10f, root_child2.LayoutHeight);
}
[Test]
public void Test_justify_content_column_center()
{
YogaNode root = new YogaNode();
root.JustifyContent = YogaJustify.Center;
root.Width = 102;
root.Height = 102;
YogaNode root_child0 = new YogaNode();
root_child0.Height = 10;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode();
root_child1.Height = 10;
root.Insert(1, root_child1);
YogaNode root_child2 = new YogaNode();
root_child2.Height = 10;
root.Insert(2, root_child2);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(102f, root.LayoutWidth);
Assert.AreEqual(102f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(36f, root_child0.LayoutY);
Assert.AreEqual(102f, root_child0.LayoutWidth);
Assert.AreEqual(10f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(46f, root_child1.LayoutY);
Assert.AreEqual(102f, root_child1.LayoutWidth);
Assert.AreEqual(10f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child2.LayoutX);
Assert.AreEqual(56f, root_child2.LayoutY);
Assert.AreEqual(102f, root_child2.LayoutWidth);
Assert.AreEqual(10f, root_child2.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(102f, root.LayoutWidth);
Assert.AreEqual(102f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(36f, root_child0.LayoutY);
Assert.AreEqual(102f, root_child0.LayoutWidth);
Assert.AreEqual(10f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(46f, root_child1.LayoutY);
Assert.AreEqual(102f, root_child1.LayoutWidth);
Assert.AreEqual(10f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child2.LayoutX);
Assert.AreEqual(56f, root_child2.LayoutY);
Assert.AreEqual(102f, root_child2.LayoutWidth);
Assert.AreEqual(10f, root_child2.LayoutHeight);
}
[Test]
public void Test_justify_content_column_space_between()
{
YogaNode root = new YogaNode();
root.JustifyContent = YogaJustify.SpaceBetween;
root.Width = 102;
root.Height = 102;
YogaNode root_child0 = new YogaNode();
root_child0.Height = 10;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode();
root_child1.Height = 10;
root.Insert(1, root_child1);
YogaNode root_child2 = new YogaNode();
root_child2.Height = 10;
root.Insert(2, root_child2);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(102f, root.LayoutWidth);
Assert.AreEqual(102f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(102f, root_child0.LayoutWidth);
Assert.AreEqual(10f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(46f, root_child1.LayoutY);
Assert.AreEqual(102f, root_child1.LayoutWidth);
Assert.AreEqual(10f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child2.LayoutX);
Assert.AreEqual(92f, root_child2.LayoutY);
Assert.AreEqual(102f, root_child2.LayoutWidth);
Assert.AreEqual(10f, root_child2.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(102f, root.LayoutWidth);
Assert.AreEqual(102f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(102f, root_child0.LayoutWidth);
Assert.AreEqual(10f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(46f, root_child1.LayoutY);
Assert.AreEqual(102f, root_child1.LayoutWidth);
Assert.AreEqual(10f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child2.LayoutX);
Assert.AreEqual(92f, root_child2.LayoutY);
Assert.AreEqual(102f, root_child2.LayoutWidth);
Assert.AreEqual(10f, root_child2.LayoutHeight);
}
[Test]
public void Test_justify_content_column_space_around()
{
YogaNode root = new YogaNode();
root.JustifyContent = YogaJustify.SpaceAround;
root.Width = 102;
root.Height = 102;
YogaNode root_child0 = new YogaNode();
root_child0.Height = 10;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode();
root_child1.Height = 10;
root.Insert(1, root_child1);
YogaNode root_child2 = new YogaNode();
root_child2.Height = 10;
root.Insert(2, root_child2);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(102f, root.LayoutWidth);
Assert.AreEqual(102f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(12f, root_child0.LayoutY);
Assert.AreEqual(102f, root_child0.LayoutWidth);
Assert.AreEqual(10f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(46f, root_child1.LayoutY);
Assert.AreEqual(102f, root_child1.LayoutWidth);
Assert.AreEqual(10f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child2.LayoutX);
Assert.AreEqual(80f, root_child2.LayoutY);
Assert.AreEqual(102f, root_child2.LayoutWidth);
Assert.AreEqual(10f, root_child2.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(102f, root.LayoutWidth);
Assert.AreEqual(102f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(12f, root_child0.LayoutY);
Assert.AreEqual(102f, root_child0.LayoutWidth);
Assert.AreEqual(10f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(46f, root_child1.LayoutY);
Assert.AreEqual(102f, root_child1.LayoutWidth);
Assert.AreEqual(10f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child2.LayoutX);
Assert.AreEqual(80f, root_child2.LayoutY);
Assert.AreEqual(102f, root_child2.LayoutWidth);
Assert.AreEqual(10f, root_child2.LayoutHeight);
}
}
}
| |
// Copyright (C) 2014 - 2015 Stephan Bouchard - All Rights Reserved
// This code can only be used under the standard Unity Asset Store End User License Agreement
// A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.IO;
namespace TMPro.EditorUtilities
{
public class TMPro_FontAssetCreatorWindow : EditorWindow
{
[MenuItem("Window/TextMeshPro - Font Asset Creator")]
public static void ShowFontAtlasCreatorWindow()
{
var window = GetWindow<TMPro_FontAssetCreatorWindow>();
window.titleContent = new GUIContent("Asset Creator");
window.Focus();
}
private string[] FontSizingOptions = { "Auto Sizing", "Custom Size" };
private int FontSizingOption_Selection = 0;
private string[] FontResolutionLabels = { "16","32", "64", "128", "256", "512", "1024", "2048", "4096", "8192" };
private int[] FontAtlasResolutions = { 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192 };
private string[] FontCharacterSets = { "ASCII", "Extended ASCII", "ASCII Lowercase", "ASCII Uppercase", "Numbers + Symbols", "Custom Range", "Unicode Range (Hex)", "Custom Characters", "Characters from File" };
private enum FontPackingModes { Fast = 0, Optimum = 4 };
private FontPackingModes m_fontPackingSelection = 0;
private int font_CharacterSet_Selection = 0;
private enum PreviewSelectionTypes { PreviewFont, PreviewTexture, PreviewDistanceField };
private PreviewSelectionTypes previewSelection;
private string characterSequence = "";
private string output_feedback = "";
private string output_name_label = "Font: ";
private string output_size_label = "Pt. Size: ";
private string output_count_label = "Characters packed: ";
private int m_character_Count;
private Vector2 output_ScrollPosition;
//private GUISkin TMP_GUISkin;
//private GUIStyle TextureAreaBox;
//private GUIStyle TextAreaBox;
//private GUIStyle Section_Label;
//private Thread MainThread;
private Color[] Output;
private bool isDistanceMapReady = false;
private bool isRepaintNeeded = false;
private Rect progressRect;
public static float ProgressPercentage;
private float m_renderingProgress;
private bool isRenderingDone = false;
private bool isProcessing = false;
private Object font_TTF;
private TextAsset characterList;
private int font_size;
private int font_padding = 5;
private FaceStyles font_style = FaceStyles.Normal;
private float font_style_mod = 2;
private RenderModes font_renderMode = RenderModes.DistanceField16;
private int font_atlas_width = 512;
private int font_atlas_height = 512;
private int font_scaledownFactor = 1;
private int font_spread = 4;
private FT_FaceInfo m_font_faceInfo;
private FT_GlyphInfo[] m_font_glyphInfo;
private byte[] m_texture_buffer;
private Texture2D m_font_Atlas;
//private Texture2D m_texture_Atlas;
//private int m_packingMethod = 0;
private Texture2D m_destination_Atlas;
private bool includeKerningPairs = false;
private int[] m_kerningSet;
// Image Down Sampling Fields
//private Texture2D sdf_Atlas;
//private int downscale;
//private Object prev_Selection;
private EditorWindow m_editorWindow;
private Vector2 m_previewWindow_Size = new Vector2(768, 768);
private Rect m_UI_Panel_Size;
public void OnEnable()
{
m_editorWindow = this;
UpdateEditorWindowSize(768, 768);
// Get the UI Skin and Styles for the various Editors
TMP_UIStyleManager.GetUIStyles();
// Locate the plugin files & move them to root of project if that hasn't already been done.
#if !UNITY_5
// Find to location of the TextMesh Pro Asset Folder (as users may have moved it)
string tmproAssetFolderPath = TMPro_EditorUtility.GetAssetLocation();
string projectPath = Path.GetFullPath("Assets/..");
if (System.IO.File.Exists(projectPath + "/TMPro_Plugin.dll") == false)
{
FileUtil.ReplaceFile(tmproAssetFolderPath + "/Plugins/TMPro_Plugin.dll", projectPath + "/TMPro_Plugin.dll"); // Copy the .dll
FileUtil.ReplaceFile(tmproAssetFolderPath + "/Plugins/TMPro_Plugin.dylib", projectPath + "/TMPro_Plugin.dylib"); // Copy Mac .dylib
FileUtil.ReplaceFile(tmproAssetFolderPath + "/Plugins/vcomp120.dll", projectPath + "/vcomp120.dll"); // Copy OpemMP .dll
}
else // Check if we are using the latest versions
{
if (System.IO.File.GetLastWriteTime(tmproAssetFolderPath + "/Plugins/TMPro_Plugin.dylib") > System.IO.File.GetLastWriteTime(projectPath + "/TMPro_Plugin.dylib"))
FileUtil.ReplaceFile(tmproAssetFolderPath + "/Plugins/TMPro_Plugin.dylib", projectPath + "/TMPro_Plugin.dylib");
if (System.IO.File.GetLastWriteTime(tmproAssetFolderPath + "/Plugins/TMPro_Plugin.dll") > System.IO.File.GetLastWriteTime(projectPath + "/TMPro_Plugin.dll"))
FileUtil.ReplaceFile(tmproAssetFolderPath + "/Plugins/TMPro_Plugin.dll", projectPath + "/TMPro_Plugin.dll");
if (System.IO.File.GetLastWriteTime(tmproAssetFolderPath + "/Plugins/vcomp120.dll") > System.IO.File.GetLastWriteTime(projectPath + "/vcomp120.dll"))
FileUtil.ReplaceFile(tmproAssetFolderPath + "/Plugins/vcomp120.dll", projectPath + "/vcomp120.dll");
}
#endif
// Add Event Listener related to Distance Field Atlas Creation.
TMPro_EventManager.COMPUTE_DT_EVENT.Add(ON_COMPUTE_DT_EVENT);
// Debug Link to received message from Native Code
//TMPro_FontPlugin.LinkDebugLog(); // Link with C++ Plugin to get Debug output
}
public void OnDisable()
{
//Debug.Log("TextMeshPro Editor Window has been disabled.");
TMPro_EventManager.COMPUTE_DT_EVENT.Remove(ON_COMPUTE_DT_EVENT);
// Destroy Engine only if it has been initialized already
if (TMPro_FontPlugin.Initialize_FontEngine() == 99)
{
TMPro_FontPlugin.Destroy_FontEngine();
}
// Cleaning up allocated Texture2D
if (m_destination_Atlas != null && EditorUtility.IsPersistent(m_destination_Atlas) == false)
{
//Debug.Log("Destroying destination_Atlas!");
DestroyImmediate(m_destination_Atlas);
}
if (m_font_Atlas != null && EditorUtility.IsPersistent(m_font_Atlas) == false)
{
//Debug.Log("Destroying font_Atlas!");
DestroyImmediate(m_font_Atlas);
}
}
public void OnGUI()
{
GUILayout.BeginHorizontal(GUILayout.Width(310));
DrawControls();
DrawPreview();
GUILayout.EndHorizontal();
}
public void ON_COMPUTE_DT_EVENT(object Sender, Compute_DT_EventArgs e)
{
if (e.EventType == Compute_DistanceTransform_EventTypes.Completed)
{
Output = e.Colors;
isProcessing = false;
isDistanceMapReady = true;
}
else if (e.EventType == Compute_DistanceTransform_EventTypes.Processing)
{
ProgressPercentage = e.ProgressPercentage;
isRepaintNeeded = true;
}
}
public void Update()
{
if (isDistanceMapReady)
{
if (m_font_Atlas != null)
{
m_destination_Atlas = new Texture2D(m_font_Atlas.width / font_scaledownFactor, m_font_Atlas.height / font_scaledownFactor, TextureFormat.Alpha8, false, true);
m_destination_Atlas.SetPixels(Output);
m_destination_Atlas.Apply(false, true);
}
//else if (m_texture_Atlas != null)
//{
// m_destination_Atlas = new Texture2D(m_texture_Atlas.width / font_scaledownFactor, m_texture_Atlas.height / font_scaledownFactor, TextureFormat.Alpha8, false, true);
// m_destination_Atlas.SetPixels(Output);
// m_destination_Atlas.Apply(false, true);
//}
isDistanceMapReady = false;
Repaint();
// Saving File for Debug
//var pngData = destination_Atlas.EncodeToPNG();
//File.WriteAllBytes("Assets/Textures/Debug SDF.png", pngData);
}
if (isRepaintNeeded)
{
//Debug.Log("Repainting...");
isRepaintNeeded = false;
Repaint();
}
// Update Progress bar is we are Rendering a Font.
if (isProcessing)
{
m_renderingProgress = TMPro_FontPlugin.Check_RenderProgress();
isRepaintNeeded = true;
}
// Update Feedback Window & Create Font Texture once Rendering is done.
if (isRenderingDone)
{
isProcessing = false;
isRenderingDone = false;
UpdateRenderFeedbackWindow();
CreateFontTexture();
}
}
/// <summary>
/// Method which returns the character corresponding to a decimal value.
/// </summary>
/// <param name="sequence"></param>
/// <returns></returns>
int[] ParseNumberSequence(string sequence)
{
List<int> unicode_list = new List<int>();
string[] sequences = sequence.Split(',');
foreach (string seq in sequences)
{
string[] s1 = seq.Split('-');
if (s1.Length == 1)
try
{
unicode_list.Add(int.Parse(s1[0]));
}
catch
{
Debug.Log("No characters selected or invalid format.");
}
else
{
for (int j = int.Parse(s1[0]); j < int.Parse(s1[1]) + 1; j++)
{
unicode_list.Add(j);
}
}
}
return unicode_list.ToArray();
}
/// <summary>
/// Method which returns the character (decimal value) from a hex sequence.
/// </summary>
/// <param name="sequence"></param>
/// <returns></returns>
int[] ParseHexNumberSequence(string sequence)
{
List<int> unicode_list = new List<int>();
string[] sequences = sequence.Split(',');
foreach (string seq in sequences)
{
string[] s1 = seq.Split('-');
if (s1.Length == 1)
try
{
unicode_list.Add(int.Parse(s1[0], NumberStyles.AllowHexSpecifier));
}
catch
{
Debug.Log("No characters selected or invalid format.");
}
else
{
for (int j = int.Parse(s1[0], NumberStyles.AllowHexSpecifier); j < int.Parse(s1[1], NumberStyles.AllowHexSpecifier) + 1; j++)
{
unicode_list.Add(j);
}
}
}
return unicode_list.ToArray();
}
void DrawControls()
{
GUILayout.BeginVertical();
GUILayout.Label("<b>TextMeshPro - Font Asset Creator</b>", TMP_UIStyleManager.Section_Label, GUILayout.Width(300));
GUILayout.Label("Font Settings", TMP_UIStyleManager.Section_Label, GUILayout.Width(300));
GUILayout.BeginVertical(TMP_UIStyleManager.TextureAreaBox, GUILayout.Width(300));
EditorGUIUtility.LookLikeControls(120f, 160f);
// FONT TTF SELECTION
font_TTF = EditorGUILayout.ObjectField("Font Source", font_TTF, typeof(Font), false, GUILayout.Width(290)) as Font;
// FONT SIZING
if (FontSizingOption_Selection == 0)
{
FontSizingOption_Selection = EditorGUILayout.Popup("Font Size", FontSizingOption_Selection, FontSizingOptions, GUILayout.Width(290));
}
else
{
EditorGUIUtility.LookLikeControls(120f, 40f);
GUILayout.BeginHorizontal(GUILayout.Width(290));
FontSizingOption_Selection = EditorGUILayout.Popup("Font Size", FontSizingOption_Selection, FontSizingOptions, GUILayout.Width(225));
font_size = EditorGUILayout.IntField(font_size);
GUILayout.EndHorizontal();
}
EditorGUIUtility.LookLikeControls(120f, 160f);
// FONT PADDING
font_padding = EditorGUILayout.IntField("Font Padding", font_padding, GUILayout.Width(290));
font_padding = (int)Mathf.Clamp(font_padding, 0f, 64f);
// FONT PACKING METHOD SELECTION
m_fontPackingSelection = (FontPackingModes)EditorGUILayout.EnumPopup("Packing Method", m_fontPackingSelection, GUILayout.Width(225));
//font_renderingMode = (FontRenderingMode)EditorGUILayout.EnumPopup("Rendering Mode", font_renderingMode, GUILayout.Width(290));
// FONT ATLAS RESOLUTION SELECTION
GUILayout.BeginHorizontal(GUILayout.Width(290));
GUI.changed = false;
EditorGUIUtility.LookLikeControls(120f, 40f);
GUILayout.Label("Atlas Resolution:", GUILayout.Width(116));
font_atlas_width = EditorGUILayout.IntPopup(font_atlas_width, FontResolutionLabels, FontAtlasResolutions); //, GUILayout.Width(80));
font_atlas_height = EditorGUILayout.IntPopup(font_atlas_height, FontResolutionLabels, FontAtlasResolutions); //, GUILayout.Width(80));
GUILayout.EndHorizontal();
// FONT CHARACTER SET SELECTION
GUI.changed = false;
font_CharacterSet_Selection = EditorGUILayout.Popup("Character Set", font_CharacterSet_Selection, FontCharacterSets, GUILayout.Width(290));
if (GUI.changed)
{
characterSequence = "";
//Debug.Log("Resetting Sequence!");
}
switch (font_CharacterSet_Selection)
{
case 0: // ASCII
//characterSequence = "32 - 126, 130, 132 - 135, 139, 145 - 151, 153, 155, 161, 166 - 167, 169 - 174, 176, 181 - 183, 186 - 187, 191, 8210 - 8226, 8230, 8240, 8242 - 8244, 8249 - 8250, 8252 - 8254, 8260, 8286";
characterSequence = "32 - 126, 8230";
break;
case 1: // EXTENDED ASCII
characterSequence = "32 - 126, 160 - 255, 8210 - 8226, 8230, 8240, 8242 - 8244, 8249 - 8250, 8252, 8254, 8260, 8286, 8364";
break;
case 2: // Lowercase
characterSequence = "32 - 64, 91 - 126";
break;
case 3: // Uppercase
characterSequence = "32 - 96, 123 - 126";
break;
case 4: // Numbers & Symbols
characterSequence = "32 - 64, 91 - 96, 123 - 126";
break;
case 5: // Custom Range
GUILayout.BeginHorizontal(GUILayout.Width(290));
GUILayout.Label("Custom Range (Dec)", GUILayout.Width(116));
// Filter out unwanted characters.
char chr = Event.current.character;
if ((chr < '0' || chr > '9') && (chr < ',' || chr > '-'))
{
Event.current.character = '\0';
}
characterSequence = EditorGUILayout.TextArea(characterSequence, TMP_UIStyleManager.TextAreaBoxWindow, GUILayout.Height(32), GUILayout.MaxWidth(170));
GUILayout.EndHorizontal();
break;
case 6: // Unicode HEX Range
GUILayout.BeginHorizontal(GUILayout.Width(290));
GUILayout.Label("Unicode Range (Hex)", GUILayout.Width(116));
// Filter out unwanted characters.
chr = Event.current.character;
if ((chr < '0' || chr > '9') && (chr < 'a' || chr > 'f') && (chr < 'A' || chr > 'F') && (chr < ',' || chr > '-'))
{
Event.current.character = '\0';
}
characterSequence = EditorGUILayout.TextArea(characterSequence, TMP_UIStyleManager.TextAreaBoxWindow, GUILayout.Height(32), GUILayout.MaxWidth(170));
GUILayout.EndHorizontal();
break;
case 7: // Custom Characters
GUILayout.BeginHorizontal(GUILayout.Width(290));
GUILayout.Label("Custom Characters", GUILayout.Width(116));
characterSequence = EditorGUILayout.TextArea(characterSequence, TMP_UIStyleManager.TextAreaBoxWindow, GUILayout.Height(32), GUILayout.MaxWidth(170));
GUILayout.EndHorizontal();
break;
case 8: // Character List from File
characterList = EditorGUILayout.ObjectField("Character File", characterList, typeof(TextAsset), false, GUILayout.Width(290)) as TextAsset;
if (characterList != null)
{
characterSequence = characterList.text;
}
break;
}
EditorGUIUtility.LookLikeControls(120f, 40f);
// FONT STYLE SELECTION
GUILayout.BeginHorizontal(GUILayout.Width(290));
font_style = (FaceStyles)EditorGUILayout.EnumPopup("Font Style:", font_style, GUILayout.Width(225));
font_style_mod = EditorGUILayout.IntField((int)font_style_mod);
GUILayout.EndHorizontal();
// Render Mode Selection
font_renderMode = (RenderModes)EditorGUILayout.EnumPopup("Font Render Mode:", font_renderMode, GUILayout.Width(290));
includeKerningPairs = EditorGUILayout.Toggle("Get Kerning Pairs?", includeKerningPairs, GUILayout.MaxWidth(290));
EditorGUIUtility.LookLikeControls(120f, 160f);
GUILayout.Space(20);
GUI.enabled = font_TTF == null || isProcessing ? false : true; // Enable Preview if we are not already rendering a font.
if (GUILayout.Button("Generate Font Atlas", GUILayout.Width(290)) && characterSequence.Length != 0 && GUI.enabled)
{
if (font_TTF != null)
{
int error_Code;
error_Code = TMPro_FontPlugin.Initialize_FontEngine(); // Initialize Font Engine
if (error_Code != 0)
{
if (error_Code == 99)
{
//Debug.Log("Font Library was already initialized!");
error_Code = 0;
}
else
Debug.Log("Error Code: " + error_Code + " occurred while Initializing the FreeType Library.");
}
string fontPath = AssetDatabase.GetAssetPath(font_TTF); // Get file path of TTF Font.
if (error_Code == 0)
{
error_Code = TMPro_FontPlugin.Load_TrueType_Font(fontPath); // Load the selected font.
if (error_Code != 0)
{
if (error_Code == 99)
{
//Debug.Log("Font was already loaded!");
error_Code = 0;
}
else
Debug.Log("Error Code: " + error_Code + " occurred while Loading the font.");
}
}
if (error_Code == 0)
{
if (FontSizingOption_Selection == 0) font_size = 72; // If Auto set size to 72 pts.
error_Code = TMPro_FontPlugin.FT_Size_Font(font_size); // Load the selected font and size it accordingly.
if (error_Code != 0)
Debug.Log("Error Code: " + error_Code + " occurred while Sizing the font.");
}
// Define an array containing the characters we will render.
if (error_Code == 0)
{
int[] character_Set = null;
if (font_CharacterSet_Selection == 7 || font_CharacterSet_Selection == 8)
{
List<int> char_List = new List<int>();
for (int i = 0; i < characterSequence.Length; i++)
{
// Check to make sure we don't include duplicates
if (char_List.FindIndex(item => item == characterSequence[i]) == -1)
char_List.Add(characterSequence[i]);
else
{
//Debug.Log("Character [" + characterSequence[i] + "] is a duplicate.");
}
}
character_Set = char_List.ToArray();
}
else if (font_CharacterSet_Selection == 6)
{
character_Set = ParseHexNumberSequence(characterSequence);
}
else
{
character_Set = ParseNumberSequence(characterSequence);
}
m_character_Count = character_Set.Length;
m_texture_buffer = new byte[font_atlas_width * font_atlas_height];
m_font_faceInfo = new FT_FaceInfo();
m_font_glyphInfo = new FT_GlyphInfo[m_character_Count];
int padding = font_padding;
bool autoSizing = FontSizingOption_Selection == 0 ? true : false;
float strokeSize = font_style_mod;
if (font_renderMode == RenderModes.DistanceField16) strokeSize = font_style_mod * 16;
if (font_renderMode == RenderModes.DistanceField32) strokeSize = font_style_mod * 32;
isProcessing = true;
ThreadPool.QueueUserWorkItem(SomeTask =>
{
isRenderingDone = false;
error_Code = TMPro_FontPlugin.Render_Characters(m_texture_buffer, font_atlas_width, font_atlas_height, padding, character_Set, m_character_Count, font_style, strokeSize, autoSizing, font_renderMode,(int)m_fontPackingSelection, ref m_font_faceInfo, m_font_glyphInfo);
isRenderingDone = true;
//Debug.Log("Font Rendering is completed.");
});
previewSelection = PreviewSelectionTypes.PreviewFont;
}
}
}
// FONT RENDERING PROGRESS BAR
GUILayout.Space(1);
progressRect = GUILayoutUtility.GetRect(288, 20, TMP_UIStyleManager.TextAreaBoxWindow, GUILayout.Width(288), GUILayout.Height(20));
GUI.BeginGroup(progressRect);
GUI.DrawTextureWithTexCoords(new Rect(2, 0, 288, 20), TMP_UIStyleManager.progressTexture, new Rect(1 - m_renderingProgress, 0, 1, 1));
GUI.EndGroup();
// FONT STATUS & INFORMATION
GUISkin skin = GUI.skin;
GUI.skin = TMP_UIStyleManager.TMP_GUISkin;
GUILayout.Space(5);
GUILayout.BeginVertical(TMP_UIStyleManager.TextAreaBoxWindow);
output_ScrollPosition = EditorGUILayout.BeginScrollView(output_ScrollPosition, GUILayout.Height(145));
EditorGUILayout.LabelField(output_feedback, TMP_UIStyleManager.Label);
EditorGUILayout.EndScrollView();
GUILayout.EndVertical();
GUI.skin = skin;
GUILayout.Space(10);
// SAVE TEXTURE & CREATE and SAVE FONT XML FILE
GUI.enabled = m_font_Atlas != null ? true : false; // Enable Save Button if font_Atlas is not Null.
if (GUILayout.Button("Save TextMeshPro Font Asset", GUILayout.Width(290)) && GUI.enabled)
{
string filePath = string.Empty;
if (font_renderMode < RenderModes.DistanceField16) // == RenderModes.HintedSmooth || font_renderMode == RenderModes.RasterHinted)
{
filePath = EditorUtility.SaveFilePanel("Save TextMesh Pro! Font Asset File", new FileInfo(AssetDatabase.GetAssetPath(font_TTF)).DirectoryName, font_TTF.name, "asset");
if (filePath.Length == 0)
return;
Save_Normal_FontAsset(filePath);
}
else if (font_renderMode >= RenderModes.DistanceField16)
{
filePath = EditorUtility.SaveFilePanel("Save TextMesh Pro! Font Asset File", new FileInfo(AssetDatabase.GetAssetPath(font_TTF)).DirectoryName, font_TTF.name + " SDF", "asset");
if (filePath.Length == 0)
return;
Save_SDF_FontAsset(filePath);
}
}
GUI.enabled = true; // Re-enable GUI
GUILayout.Space(5);
GUILayout.EndVertical();
GUILayout.Space(25);
/*
// GENERATE DISTANCE FIELD TEXTURE
GUILayout.Label("Distance Field Options", SectionLabel, GUILayout.Width(300));
GUILayout.BeginVertical(textureAreaBox, GUILayout.Width(300));
GUILayout.Space(5);
font_spread = EditorGUILayout.IntField("Spread", font_spread, GUILayout.Width(280));
font_scaledownFactor = EditorGUILayout.IntField("Scale down factor", font_scaledownFactor, GUILayout.Width(280));
if (GUI.changed)
{
EditorPrefs.SetInt("Font_Spread", font_spread);
EditorPrefs.SetInt("Font_ScaleDownFactor", font_scaledownFactor);
}
GUILayout.Space(20);
GUI.enabled = m_font_Atlas != null ? true : false; // Enable Save Button if font_Atlas is not Null.
if (GUILayout.Button("Preview Distance Field Font Atlas", GUILayout.Width(290)))
{
if (m_font_Atlas != null && isProcessing == false)
{
// Generate Distance Field
int width = m_font_Atlas.width;
int height = m_font_Atlas.height;
Color[] colors = m_font_Atlas.GetPixels(); // Should modify this to use Color32 instead
isProcessing = true;
ThreadPool.QueueUserWorkItem(SomeTask => { TMPro_DistanceTransform.Generate(colors, width, height, font_spread, font_scaledownFactor); });
previewSelection = PreviewSelectionTypes.PreviewDistanceField;
}
}
GUILayout.Space(1);
progressRect = GUILayoutUtility.GetRect(290, 20, textAreaBox, GUILayout.Width(290), GUILayout.Height(20));
GUI.BeginGroup(progressRect);
GUI.DrawTextureWithTexCoords(new Rect(0, 0, 290, 20), progressTexture, new Rect(1 - ProgressPercentage, 0, 1, 1));
GUI.EndGroup();
//GUILayout.Space(5);
GUI.enabled = m_destination_Atlas != null ? true : false; // Enable Save Button if font_Atlas is not Null.
if (GUILayout.Button("Save TextMeshPro (SDF) Font Asset", GUILayout.Width(290)))
{
string filePath = EditorUtility.SaveFilePanel("Save TextMesh Pro! Font Asset File", new FileInfo(AssetDatabase.GetAssetPath(font_TTF)).DirectoryName, font_TTF.name + " SDF", "asset");
if (filePath.Length == 0)
return;
Save_SDF_FontAsset(filePath);
}
GUILayout.EndVertical();
*/
// Figure out the size of the current UI Panel
Rect rect = EditorGUILayout.GetControlRect(false, 5);
if (Event.current.type == EventType.Repaint)
m_UI_Panel_Size = rect;
GUILayout.EndVertical();
}
void UpdateRenderFeedbackWindow()
{
font_size = m_font_faceInfo.pointSize;
string colorTag = m_font_faceInfo.characterCount == m_character_Count ? "<color=#C0ffff>" : "<color=#ffff00>";
string colorTag2 = "<color=#C0ffff>";
output_feedback = output_name_label + "<b>" + colorTag2 + m_font_faceInfo.name + "</color></b>";
if (output_feedback.Length > 60)
output_feedback += "\n" + output_size_label + "<b>" + colorTag2 + m_font_faceInfo.pointSize + "</color></b>";
else
output_feedback += " " + output_size_label + "<b>" + colorTag2 + m_font_faceInfo.pointSize + "</color></b>";
output_feedback += "\n" + output_count_label + "<b>" + colorTag + m_font_faceInfo.characterCount + "/" + m_character_Count + "</color></b>";
// Report missing requested glyph
output_feedback += "\n\n<color=#ffff00><b>Missing Characters</b></color>";
output_feedback += "\n----------------------------------------";
for (int i = 0; i < m_character_Count; i++)
{
if (m_font_glyphInfo[i].x == -1)
output_feedback += "\nID: <color=#C0ffff>" + m_font_glyphInfo[i].id + "\t\t</color>Char [<color=#C0ffff>" + (char)m_font_glyphInfo[i].id + "</color>]";
}
}
void CreateFontTexture()
{
m_font_Atlas = new Texture2D(font_atlas_width, font_atlas_height, TextureFormat.Alpha8, false, true);
m_font_Atlas.hideFlags = HideFlags.DontSave;
Color32[] colors = new Color32[font_atlas_width * font_atlas_height];
for (int i = 0; i < (font_atlas_width * font_atlas_height); i++)
{
byte c = m_texture_buffer[i];
colors[i] = new Color32(c, c, c, c);
}
if (font_renderMode == RenderModes.RasterHinted)
m_font_Atlas.filterMode = FilterMode.Point;
m_font_Atlas.SetPixels32(colors, 0);
m_font_Atlas.Apply(false, false);
// Saving File for Debug
//var pngData = m_font_Atlas.EncodeToPNG();
//File.WriteAllBytes("Assets/Textures/Debug Font Texture.png", pngData);
UpdateEditorWindowSize(m_font_Atlas.width, m_font_Atlas.height);
//previewSelection = PreviewSelectionTypes.PreviewFont;
}
void Save_Normal_FontAsset(string filePath)
{
filePath = filePath.Substring(0, filePath.Length - 6); // Trim file extension from filePath.
string dataPath = Application.dataPath;
if (filePath.IndexOf(dataPath) == -1)
{
Debug.LogError("You're saving the font asset in a directory outside of this project folder. This is not supported. Please select a directory under \"" + dataPath + "\"");
return;
}
string relativeAssetPath = filePath.Substring(dataPath.Length - 6);
string tex_DirName = Path.GetDirectoryName(relativeAssetPath);
string tex_FileName = Path.GetFileNameWithoutExtension(relativeAssetPath);
string tex_Path_NoExt = tex_DirName + "/" + tex_FileName;
// Check if TextMeshPro font asset already exists. If not, create a new one. Otherwise update the existing one.
TextMeshProFont font_asset = AssetDatabase.LoadAssetAtPath(tex_Path_NoExt + ".asset", typeof(TextMeshProFont)) as TextMeshProFont;
if (font_asset == null)
{
//Debug.Log("Creating TextMeshPro font asset!");
font_asset = ScriptableObject.CreateInstance<TextMeshProFont>(); // Create new TextMeshPro Font Asset.
AssetDatabase.CreateAsset(font_asset, tex_Path_NoExt + ".asset");
//Set Font Asset Type
font_asset.fontAssetType = TextMeshProFont.FontAssetTypes.Bitmap;
// Add FaceInfo to Font Asset
FaceInfo face = GetFaceInfo(m_font_faceInfo, 1);
font_asset.AddFaceInfo(face);
// Add GlyphInfo[] to Font Asset
GlyphInfo[] glyphs = GetGlyphInfo(m_font_glyphInfo, 1);
font_asset.AddGlyphInfo(glyphs);
// Get and Add Kerning Pairs to Font Asset
if (includeKerningPairs)
{
string fontFilePath = AssetDatabase.GetAssetPath(font_TTF);
KerningTable kerningTable = GetKerningTable(fontFilePath, (int)face.PointSize);
font_asset.AddKerningInfo(kerningTable);
}
// Add Font Atlas as Sub-Asset
font_asset.atlas = m_font_Atlas;
m_font_Atlas.name = tex_FileName + " Atlas";
m_font_Atlas.hideFlags = HideFlags.HideInHierarchy;
AssetDatabase.AddObjectToAsset(m_font_Atlas, font_asset);
// Create new Material and Add it as Sub-Asset
Shader default_Shader = Shader.Find("TMPro/Bitmap");
Material tmp_material = new Material(default_Shader);
tmp_material.name = tex_FileName + " Material";
tmp_material.SetTexture(ShaderUtilities.ID_MainTex, m_font_Atlas);
font_asset.material = tmp_material;
tmp_material.hideFlags = HideFlags.HideInHierarchy;
AssetDatabase.AddObjectToAsset(tmp_material, font_asset);
}
else
{
// Find all Materials referencing this font atlas.
Material[] material_references = TMPro_EditorUtility.FindMaterialReferences(font_asset.material);
// Destroy Assets that will be replaced.
DestroyImmediate(font_asset.atlas, true);
//Set Font Asset Type
font_asset.fontAssetType = TextMeshProFont.FontAssetTypes.Bitmap;
// Add FaceInfo to Font Asset
FaceInfo face = GetFaceInfo(m_font_faceInfo, 1);
font_asset.AddFaceInfo(face);
// Add GlyphInfo[] to Font Asset
GlyphInfo[] glyphs = GetGlyphInfo(m_font_glyphInfo, 1);
font_asset.AddGlyphInfo(glyphs);
// Get and Add Kerning Pairs to Font Asset
if (includeKerningPairs)
{
string fontFilePath = AssetDatabase.GetAssetPath(font_TTF);
KerningTable kerningTable = GetKerningTable(fontFilePath, (int)face.PointSize);
font_asset.AddKerningInfo(kerningTable);
}
// Add Font Atlas as Sub-Asset
font_asset.atlas = m_font_Atlas;
m_font_Atlas.name = tex_FileName + " Atlas";
m_font_Atlas.hideFlags = HideFlags.HideInHierarchy;
AssetDatabase.AddObjectToAsset(m_font_Atlas, font_asset);
// Update the Texture reference on the Material
for (int i = 0; i < material_references.Length; i++)
{
material_references[i].SetTexture(ShaderUtilities.ID_MainTex, font_asset.atlas);
}
}
m_font_Atlas = null;
AssetDatabase.SaveAssets();
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(font_asset)); // Re-import font asset to get the new updated version.
//EditorUtility.SetDirty(font_asset);
font_asset.ReadFontDefinition();
AssetDatabase.Refresh();
// NEED TO GENERATE AN EVENT TO FORCE A REDRAW OF ANY TEXTMESHPRO INSTANCES THAT MIGHT BE USING THIS FONT ASSET
TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, font_asset);
}
void Save_SDF_FontAsset(string filePath)
{
filePath = filePath.Substring(0, filePath.Length - 6); // Trim file extension from filePath.
string dataPath = Application.dataPath;
if (filePath.IndexOf(dataPath) == -1)
{
Debug.LogError("You're saving the font asset in a directory outside of this project folder. This is not supported. Please select a directory under \"" + dataPath + "\"");
return;
}
string relativeAssetPath = filePath.Substring(dataPath.Length - 6);
string tex_DirName = Path.GetDirectoryName(relativeAssetPath);
string tex_FileName = Path.GetFileNameWithoutExtension(relativeAssetPath);
string tex_Path_NoExt = tex_DirName + "/" + tex_FileName;
// Check if TextMeshPro font asset already exists. If not, create a new one. Otherwise update the existing one.
TextMeshProFont font_asset = AssetDatabase.LoadAssetAtPath(tex_Path_NoExt + ".asset", typeof(TextMeshProFont)) as TextMeshProFont;
if (font_asset == null)
{
//Debug.Log("Creating TextMeshPro font asset!");
font_asset = ScriptableObject.CreateInstance<TextMeshProFont>(); // Create new TextMeshPro Font Asset.
AssetDatabase.CreateAsset(font_asset, tex_Path_NoExt + ".asset");
//Set Font Asset Type
font_asset.fontAssetType = TextMeshProFont.FontAssetTypes.SDF;
if (m_destination_Atlas != null)
m_font_Atlas = m_destination_Atlas;
// If using the C# SDF creation mode, we need the scale down factor.
int scaleDownFactor = font_renderMode >= RenderModes.DistanceField16 ? 1 : font_scaledownFactor;
// Add FaceInfo to Font Asset
FaceInfo face = GetFaceInfo(m_font_faceInfo, scaleDownFactor);
font_asset.AddFaceInfo(face);
// Add GlyphInfo[] to Font Asset
GlyphInfo[] glyphs = GetGlyphInfo(m_font_glyphInfo, scaleDownFactor);
font_asset.AddGlyphInfo(glyphs);
// Get and Add Kerning Pairs to Font Asset
if (includeKerningPairs)
{
string fontFilePath = AssetDatabase.GetAssetPath(font_TTF);
KerningTable kerningTable = GetKerningTable(fontFilePath, (int)face.PointSize);
font_asset.AddKerningInfo(kerningTable);
}
// Add Line Breaking Rules
//LineBreakingTable lineBreakingTable = new LineBreakingTable();
//
// Add Font Atlas as Sub-Asset
font_asset.atlas = m_font_Atlas;
m_font_Atlas.name = tex_FileName + " Atlas";
m_font_Atlas.hideFlags = HideFlags.HideInHierarchy;
AssetDatabase.AddObjectToAsset(m_font_Atlas, font_asset);
// Create new Material and Add it as Sub-Asset
Shader default_Shader = Shader.Find("TMPro/Distance Field");
Material tmp_material = new Material(default_Shader);
//tmp_material.shaderKeywords = new string[] { "BEVEL_OFF", "GLOW_OFF", "UNDERLAY_OFF" };
tmp_material.name = tex_FileName + " Material";
tmp_material.SetTexture(ShaderUtilities.ID_MainTex, m_font_Atlas);
tmp_material.SetFloat(ShaderUtilities.ID_TextureWidth, m_font_Atlas.width);
tmp_material.SetFloat(ShaderUtilities.ID_TextureHeight, m_font_Atlas.height);
tmp_material.SetFloat(ShaderUtilities.ID_WeightNormal, font_asset.NormalStyle);
tmp_material.SetFloat(ShaderUtilities.ID_WeightBold, font_asset.BoldStyle);
int spread = font_renderMode >= RenderModes.DistanceField16 ? font_padding + 1 : font_spread;
tmp_material.SetFloat(ShaderUtilities.ID_GradientScale, spread); // Spread = Padding for Brute Force SDF.
font_asset.material = tmp_material;
tmp_material.hideFlags = HideFlags.HideInHierarchy;
AssetDatabase.AddObjectToAsset(tmp_material, font_asset);
}
else
{
// Find all Materials referencing this font atlas.
Material[] material_references = TMPro_EditorUtility.FindMaterialReferences(font_asset.material);
// Destroy Assets that will be replaced.
DestroyImmediate(font_asset.atlas, true);
//Set Font Asset Type
font_asset.fontAssetType = TextMeshProFont.FontAssetTypes.SDF;
int scaleDownFactor = font_renderMode >= RenderModes.DistanceField16 ? 1 : font_scaledownFactor;
// Add FaceInfo to Font Asset
FaceInfo face = GetFaceInfo(m_font_faceInfo, scaleDownFactor);
font_asset.AddFaceInfo(face);
// Add GlyphInfo[] to Font Asset
GlyphInfo[] glyphs = GetGlyphInfo(m_font_glyphInfo, scaleDownFactor);
font_asset.AddGlyphInfo(glyphs);
// Get and Add Kerning Pairs to Font Asset
if (includeKerningPairs)
{
string fontFilePath = AssetDatabase.GetAssetPath(font_TTF);
KerningTable kerningTable = GetKerningTable(fontFilePath, (int)face.PointSize);
font_asset.AddKerningInfo(kerningTable);
}
// Add Font Atlas as Sub-Asset
font_asset.atlas = m_font_Atlas;
m_font_Atlas.name = tex_FileName + " Atlas";
m_font_Atlas.hideFlags = HideFlags.HideInHierarchy;
AssetDatabase.AddObjectToAsset(m_font_Atlas, font_asset);
// Update the Texture reference on the Material
for (int i = 0; i < material_references.Length; i++)
{
material_references[i].SetTexture(ShaderUtilities.ID_MainTex, font_asset.atlas);
material_references[i].SetFloat(ShaderUtilities.ID_TextureWidth, m_font_Atlas.width);
material_references[i].SetFloat(ShaderUtilities.ID_TextureHeight, m_font_Atlas.height);
material_references[i].SetFloat(ShaderUtilities.ID_WeightNormal, font_asset.NormalStyle);
material_references[i].SetFloat(ShaderUtilities.ID_WeightBold, font_asset.BoldStyle);
int spread = font_renderMode >= RenderModes.DistanceField16 ? font_padding + 1 : font_spread;
material_references[i].SetFloat(ShaderUtilities.ID_GradientScale, spread); // Spread = Padding for Brute Force SDF.
}
}
m_font_Atlas = null;
// Saving File for Debug
//var pngData = destination_Atlas.EncodeToPNG();
//File.WriteAllBytes("Assets/Textures/Debug Distance Field.png", pngData);
//font_asset.fontCreationSettings = SaveFontCreationSettings();
AssetDatabase.SaveAssets();
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(font_asset)); // Re-import font asset to get the new updated version.
font_asset.ReadFontDefinition();
AssetDatabase.Refresh();
// NEED TO GENERATE AN EVENT TO FORCE A REDRAW OF ANY TEXTMESHPRO INSTANCES THAT MIGHT BE USING THIS FONT ASSET
TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, font_asset);
}
FontCreationSetting SaveFontCreationSettings()
{
FontCreationSetting settings = new FontCreationSetting();
settings.fontSourcePath = AssetDatabase.GetAssetPath(font_TTF);
settings.fontSizingMode = FontSizingOption_Selection;
settings.fontSize = font_size;
settings.fontPadding = font_padding;
settings.fontPackingMode = (int)m_fontPackingSelection;
settings.fontAtlasWidth = font_atlas_width;
settings.fontAtlasHeight = font_atlas_height;
settings.fontCharacterSet = font_CharacterSet_Selection;
settings.fontStyle = (int)font_style;
settings.fontStlyeModifier = font_style_mod;
settings.fontRenderMode = (int)font_renderMode;
settings.fontKerning = includeKerningPairs;
return settings;
}
void UpdateEditorWindowSize(float width, float height)
{
m_previewWindow_Size = new Vector2(768, 768);
if (width > height)
{
m_previewWindow_Size = new Vector2(768, height / (width / 768));
}
else if (height > width)
{
m_previewWindow_Size = new Vector2(width / (height / 768), 768);
}
m_editorWindow.minSize = new Vector2(m_previewWindow_Size.x + 330, Mathf.Max(m_UI_Panel_Size.y + 20f, m_previewWindow_Size.y + 20f));
m_editorWindow.maxSize = m_editorWindow.minSize + new Vector2(.25f, 0);
}
void DrawPreview()
{
// Display Texture Area
GUILayout.BeginVertical(TMP_UIStyleManager.TextureAreaBox);
Rect pixelRect = GUILayoutUtility.GetRect(m_previewWindow_Size.x, m_previewWindow_Size.y, TMP_UIStyleManager.Section_Label);
if (m_destination_Atlas != null && previewSelection == PreviewSelectionTypes.PreviewDistanceField)
{
EditorGUI.DrawTextureAlpha(new Rect(pixelRect.x, pixelRect.y, m_previewWindow_Size.x, m_previewWindow_Size.y), m_destination_Atlas, ScaleMode.ScaleToFit);
}
//else if (m_texture_Atlas != null && previewSelection == PreviewSelectionTypes.PreviewTexture)
//{
// GUI.DrawTexture(new Rect(pixelRect.x, pixelRect.y, m_previewWindow_Size.x, m_previewWindow_Size.y), m_texture_Atlas, ScaleMode.ScaleToFit);
//}
else if (m_font_Atlas != null && previewSelection == PreviewSelectionTypes.PreviewFont)
{
EditorGUI.DrawTextureAlpha(new Rect(pixelRect.x, pixelRect.y, m_previewWindow_Size.x, m_previewWindow_Size.y), m_font_Atlas, ScaleMode.ScaleToFit);
}
GUILayout.EndVertical();
}
// Convert from FT_FaceInfo to FaceInfo
FaceInfo GetFaceInfo(FT_FaceInfo ft_face, int scaleFactor)
{
FaceInfo face = new FaceInfo();
face.Name = ft_face.name;
face.PointSize = (float)ft_face.pointSize / scaleFactor;
face.Padding = 0; // ft_face.padding / scaleFactor;
face.LineHeight = ft_face.lineHeight / scaleFactor;
face.Baseline = 0;
face.Ascender = ft_face.ascender / scaleFactor;
face.Descender = ft_face.descender / scaleFactor;
face.CenterLine = ft_face.centerLine / scaleFactor;
face.Underline = ft_face.underline / scaleFactor;
face.UnderlineThickness = ft_face.underlineThickness == 0 ? 5 : ft_face.underlineThickness / scaleFactor; // Set Thickness to 5 if TTF value is Zero.
face.SuperscriptOffset = face.Ascender;
face.SubscriptOffset = face.Underline;
face.SubSize = 0.5f;
//face.CharacterCount = ft_face.characterCount;
face.AtlasWidth = ft_face.atlasWidth / scaleFactor;
face.AtlasHeight = ft_face.atlasHeight / scaleFactor;
return face;
}
// Convert from FT_GlyphInfo[] to GlyphInfo[]
GlyphInfo[] GetGlyphInfo(FT_GlyphInfo[] ft_glyphs, int scaleFactor)
{
List<GlyphInfo> glyphs = new List<GlyphInfo>();
List<int> kerningSet = new List<int>();
for (int i = 0; i < ft_glyphs.Length; i++)
{
GlyphInfo g = new GlyphInfo();
g.id = ft_glyphs[i].id;
g.x = ft_glyphs[i].x / scaleFactor;
g.y = ft_glyphs[i].y / scaleFactor;
g.width = ft_glyphs[i].width / scaleFactor;
g.height = ft_glyphs[i].height / scaleFactor;
g.xOffset = ft_glyphs[i].xOffset / scaleFactor;
g.yOffset = ft_glyphs[i].yOffset / scaleFactor;
g.xAdvance = ft_glyphs[i].xAdvance / scaleFactor;
// Filter out characters with missing glyphs.
if (g.x == -1)
continue;
glyphs.Add(g);
kerningSet.Add(g.id);
}
m_kerningSet = kerningSet.ToArray();
return glyphs.ToArray();
}
// Get Kerning Pairs
public KerningTable GetKerningTable(string fontFilePath, int pointSize)
{
KerningTable kerningInfo = new KerningTable();
kerningInfo.kerningPairs = new List<KerningPair>();
// Temporary Array to hold the kerning pairs from the Native Plug-in.
FT_KerningPair[] kerningPairs = new FT_KerningPair[1000];
int kpCount = TMPro_FontPlugin.FT_GetKerningPairs(fontFilePath, m_kerningSet, m_kerningSet.Length, kerningPairs);
for (int i = 0; i < kpCount; i++)
{
// Proceed to add each kerning pairs.
KerningPair kp = new KerningPair(kerningPairs[i].ascII_Left, kerningPairs[i].ascII_Right, kerningPairs[i].xAdvanceOffset * pointSize);
kerningInfo.kerningPairs.Add(kp);
}
return kerningInfo;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gagr = Google.Api.Gax.ResourceNames;
using gciv = Google.Cloud.Ids.V1;
using sys = System;
namespace Google.Cloud.Ids.V1
{
/// <summary>Resource name for the <c>Endpoint</c> resource.</summary>
public sealed partial class EndpointName : gax::IResourceName, sys::IEquatable<EndpointName>
{
/// <summary>The possible contents of <see cref="EndpointName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/endpoints/{endpoint}</c>.
/// </summary>
ProjectLocationEndpoint = 1,
}
private static gax::PathTemplate s_projectLocationEndpoint = new gax::PathTemplate("projects/{project}/locations/{location}/endpoints/{endpoint}");
/// <summary>Creates a <see cref="EndpointName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="EndpointName"/> containing the provided <paramref name="unparsedResourceName"/>
/// .
/// </returns>
public static EndpointName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new EndpointName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="EndpointName"/> with the pattern
/// <c>projects/{project}/locations/{location}/endpoints/{endpoint}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="endpointId">The <c>Endpoint</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="EndpointName"/> constructed from the provided ids.</returns>
public static EndpointName FromProjectLocationEndpoint(string projectId, string locationId, string endpointId) =>
new EndpointName(ResourceNameType.ProjectLocationEndpoint, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), endpointId: gax::GaxPreconditions.CheckNotNullOrEmpty(endpointId, nameof(endpointId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="EndpointName"/> with pattern
/// <c>projects/{project}/locations/{location}/endpoints/{endpoint}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="endpointId">The <c>Endpoint</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="EndpointName"/> with pattern
/// <c>projects/{project}/locations/{location}/endpoints/{endpoint}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string endpointId) =>
FormatProjectLocationEndpoint(projectId, locationId, endpointId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="EndpointName"/> with pattern
/// <c>projects/{project}/locations/{location}/endpoints/{endpoint}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="endpointId">The <c>Endpoint</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="EndpointName"/> with pattern
/// <c>projects/{project}/locations/{location}/endpoints/{endpoint}</c>.
/// </returns>
public static string FormatProjectLocationEndpoint(string projectId, string locationId, string endpointId) =>
s_projectLocationEndpoint.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(endpointId, nameof(endpointId)));
/// <summary>Parses the given resource name string into a new <see cref="EndpointName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/endpoints/{endpoint}</c></description></item>
/// </list>
/// </remarks>
/// <param name="endpointName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="EndpointName"/> if successful.</returns>
public static EndpointName Parse(string endpointName) => Parse(endpointName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="EndpointName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/endpoints/{endpoint}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="endpointName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="EndpointName"/> if successful.</returns>
public static EndpointName Parse(string endpointName, bool allowUnparsed) =>
TryParse(endpointName, allowUnparsed, out EndpointName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="EndpointName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/endpoints/{endpoint}</c></description></item>
/// </list>
/// </remarks>
/// <param name="endpointName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="EndpointName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string endpointName, out EndpointName result) => TryParse(endpointName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="EndpointName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/endpoints/{endpoint}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="endpointName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="EndpointName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string endpointName, bool allowUnparsed, out EndpointName result)
{
gax::GaxPreconditions.CheckNotNull(endpointName, nameof(endpointName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationEndpoint.TryParseName(endpointName, out resourceName))
{
result = FromProjectLocationEndpoint(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(endpointName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private EndpointName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string endpointId = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
EndpointId = endpointId;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="EndpointName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/endpoints/{endpoint}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="endpointId">The <c>Endpoint</c> ID. Must not be <c>null</c> or empty.</param>
public EndpointName(string projectId, string locationId, string endpointId) : this(ResourceNameType.ProjectLocationEndpoint, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), endpointId: gax::GaxPreconditions.CheckNotNullOrEmpty(endpointId, nameof(endpointId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Endpoint</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string EndpointId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationEndpoint: return s_projectLocationEndpoint.Expand(ProjectId, LocationId, EndpointId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as EndpointName);
/// <inheritdoc/>
public bool Equals(EndpointName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(EndpointName a, EndpointName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(EndpointName a, EndpointName b) => !(a == b);
}
public partial class Endpoint
{
/// <summary>
/// <see cref="gciv::EndpointName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gciv::EndpointName EndpointName
{
get => string.IsNullOrEmpty(Name) ? null : gciv::EndpointName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListEndpointsRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetEndpointRequest
{
/// <summary>
/// <see cref="gciv::EndpointName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gciv::EndpointName EndpointName
{
get => string.IsNullOrEmpty(Name) ? null : gciv::EndpointName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CreateEndpointRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class DeleteEndpointRequest
{
/// <summary>
/// <see cref="gciv::EndpointName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gciv::EndpointName EndpointName
{
get => string.IsNullOrEmpty(Name) ? null : gciv::EndpointName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace Lucene.Net.Util
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// <see cref="Sorter"/> implementation based on the
/// <a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">TimSort</a>
/// algorithm.
/// <para/>This implementation is especially good at sorting partially-sorted
/// arrays and sorts small arrays with binary sort.
/// <para/><b>NOTE</b>:There are a few differences with the original implementation:
/// <list type="bullet">
/// <item><description><a name="maxTempSlots"/>The extra amount of memory to perform merges is
/// configurable. This allows small merges to be very fast while large merges
/// will be performed in-place (slightly slower). You can make sure that the
/// fast merge routine will always be used by having <c>maxTempSlots</c>
/// equal to half of the length of the slice of data to sort.</description></item>
/// <item><description>Only the fast merge routine can gallop (the one that doesn't run
/// in-place) and it only gallops on the longest slice.</description></item>
/// </list>
/// <para/>
/// @lucene.internal
/// </summary>
public abstract class TimSorter : Sorter
{
internal const int MINRUN = 32;
internal new const int THRESHOLD = 64;
internal const int STACKSIZE = 40; // depends on MINRUN
internal const int MIN_GALLOP = 7;
internal readonly int maxTempSlots;
internal int minRun;
internal int to;
internal int stackSize;
internal int[] runEnds;
/// <summary>
/// Create a new <see cref="TimSorter"/>. </summary>
/// <param name="maxTempSlots"> The <a href="#maxTempSlots">maximum amount of extra memory to run merges</a> </param>
protected TimSorter(int maxTempSlots)
: base()
{
runEnds = new int[1 + STACKSIZE];
this.maxTempSlots = maxTempSlots;
}
/// <summary>
/// Minimum run length for an array of length <paramref name="length"/>. </summary>
internal static int MinRun(int length)
{
Debug.Assert(length >= MINRUN);
int n = length;
int r = 0;
while (n >= 64)
{
r |= n & 1;
n = (int)((uint)n >> 1);
}
int minRun = n + r;
Debug.Assert(minRun >= MINRUN && minRun <= THRESHOLD);
return minRun;
}
internal virtual int RunLen(int i)
{
int off = stackSize - i;
return runEnds[off] - runEnds[off - 1];
}
internal virtual int RunBase(int i)
{
return runEnds[stackSize - i - 1];
}
internal virtual int RunEnd(int i)
{
return runEnds[stackSize - i];
}
internal virtual void SetRunEnd(int i, int runEnd)
{
runEnds[stackSize - i] = runEnd;
}
internal virtual void PushRunLen(int len)
{
runEnds[stackSize + 1] = runEnds[stackSize] + len;
++stackSize;
}
/// <summary>
/// Compute the length of the next run, make the run sorted and return its
/// length.
/// </summary>
internal virtual int NextRun()
{
int runBase = RunEnd(0);
Debug.Assert(runBase < to);
if (runBase == to - 1)
{
return 1;
}
int o = runBase + 2;
if (Compare(runBase, runBase + 1) > 0)
{
// run must be strictly descending
while (o < to && Compare(o - 1, o) > 0)
{
++o;
}
Reverse(runBase, o);
}
else
{
// run must be non-descending
while (o < to && Compare(o - 1, o) <= 0)
{
++o;
}
}
int runHi = Math.Max(o, Math.Min(to, runBase + minRun));
BinarySort(runBase, runHi, o);
return runHi - runBase;
}
internal virtual void EnsureInvariants()
{
while (stackSize > 1)
{
int runLen0 = RunLen(0);
int runLen1 = RunLen(1);
if (stackSize > 2)
{
int runLen2 = RunLen(2);
if (runLen2 <= runLen1 + runLen0)
{
// merge the smaller of 0 and 2 with 1
if (runLen2 < runLen0)
{
MergeAt(1);
}
else
{
MergeAt(0);
}
continue;
}
}
if (runLen1 <= runLen0)
{
MergeAt(0);
continue;
}
break;
}
}
internal virtual void ExhaustStack()
{
while (stackSize > 1)
{
MergeAt(0);
}
}
internal virtual void Reset(int from, int to)
{
stackSize = 0;
Array.Clear(runEnds, 0, runEnds.Length);
runEnds[0] = from;
this.to = to;
int length = to - from;
this.minRun = length <= THRESHOLD ? length : MinRun(length);
}
internal virtual void MergeAt(int n)
{
Debug.Assert(stackSize >= 2);
Merge(RunBase(n + 1), RunBase(n), RunEnd(n));
for (int j = n + 1; j > 0; --j)
{
SetRunEnd(j, RunEnd(j - 1));
}
--stackSize;
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal virtual void Merge(int lo, int mid, int hi)
{
if (Compare(mid - 1, mid) <= 0)
{
return;
}
lo = Upper2(lo, mid, mid);
hi = Lower2(mid, hi, mid - 1);
if (hi - mid <= mid - lo && hi - mid <= maxTempSlots)
{
MergeHi(lo, mid, hi);
}
else if (mid - lo <= maxTempSlots)
{
MergeLo(lo, mid, hi);
}
else
{
MergeInPlace(lo, mid, hi);
}
}
/// <summary>
/// Sort the slice which starts at <paramref name="from"/> (inclusive) and ends at
/// <paramref name="to"/> (exclusive).
/// </summary>
public override void Sort(int from, int to)
{
CheckRange(from, to);
if (to - from <= 1)
{
return;
}
Reset(from, to);
do
{
EnsureInvariants();
PushRunLen(NextRun());
} while (RunEnd(0) < to);
ExhaustStack();
Debug.Assert(RunEnd(0) == to);
}
internal override void DoRotate(int lo, int mid, int hi)
{
int len1 = mid - lo;
int len2 = hi - mid;
if (len1 == len2)
{
while (mid < hi)
{
Swap(lo++, mid++);
}
}
else if (len2 < len1 && len2 <= maxTempSlots)
{
Save(mid, len2);
for (int i = lo + len1 - 1, j = hi - 1; i >= lo; --i, --j)
{
Copy(i, j);
}
for (int i = 0, j = lo; i < len2; ++i, ++j)
{
Restore(i, j);
}
}
else if (len1 <= maxTempSlots)
{
Save(lo, len1);
for (int i = mid, j = lo; i < hi; ++i, ++j)
{
Copy(i, j);
}
for (int i = 0, j = lo + len2; j < hi; ++i, ++j)
{
Restore(i, j);
}
}
else
{
Reverse(lo, mid);
Reverse(mid, hi);
Reverse(lo, hi);
}
}
internal virtual void MergeLo(int lo, int mid, int hi)
{
Debug.Assert(Compare(lo, mid) > 0);
int len1 = mid - lo;
Save(lo, len1);
Copy(mid, lo);
int i = 0, j = mid + 1, dest = lo + 1;
for (; ; )
{
for (int count = 0; count < MIN_GALLOP; )
{
if (i >= len1 || j >= hi)
{
goto outerBreak;
}
else if (CompareSaved(i, j) <= 0)
{
Restore(i++, dest++);
count = 0;
}
else
{
Copy(j++, dest++);
++count;
}
}
// galloping...
int next = LowerSaved3(j, hi, i);
for (; j < next; ++dest)
{
Copy(j++, dest);
}
Restore(i++, dest++);
//outerContinue: ; // LUCENENET NOTE: Not referenced
}
outerBreak:
for (; i < len1; ++dest)
{
Restore(i++, dest);
}
Debug.Assert(j == dest);
}
internal virtual void MergeHi(int lo, int mid, int hi)
{
Debug.Assert(Compare(mid - 1, hi - 1) > 0);
int len2 = hi - mid;
Save(mid, len2);
Copy(mid - 1, hi - 1);
int i = mid - 2, j = len2 - 1, dest = hi - 2;
for (; ; )
{
for (int count = 0; count < MIN_GALLOP; )
{
if (i < lo || j < 0)
{
goto outerBreak;
}
else if (CompareSaved(j, i) >= 0)
{
Restore(j--, dest--);
count = 0;
}
else
{
Copy(i--, dest--);
++count;
}
}
// galloping
int next = UpperSaved3(lo, i + 1, j);
while (i >= next)
{
Copy(i--, dest--);
}
Restore(j--, dest--);
//outerContinue: ; // LUCENENET NOTE: Not referenced
}
outerBreak:
for (; j >= 0; --dest)
{
Restore(j--, dest);
}
Debug.Assert(i == dest);
}
internal virtual int LowerSaved(int from, int to, int val)
{
int len = to - from;
while (len > 0)
{
int half = (int)((uint)len >> 1);
int mid = from + half;
if (CompareSaved(val, mid) > 0)
{
from = mid + 1;
len = len - half - 1;
}
else
{
len = half;
}
}
return from;
}
internal virtual int UpperSaved(int from, int to, int val)
{
int len = to - from;
while (len > 0)
{
int half = (int)((uint)len >> 1);
int mid = from + half;
if (CompareSaved(val, mid) < 0)
{
len = half;
}
else
{
from = mid + 1;
len = len - half - 1;
}
}
return from;
}
// faster than lowerSaved when val is at the beginning of [from:to[
internal virtual int LowerSaved3(int from, int to, int val)
{
int f = from, t = f + 1;
while (t < to)
{
if (CompareSaved(val, t) <= 0)
{
return LowerSaved(f, t, val);
}
int delta = t - f;
f = t;
t += delta << 1;
}
return LowerSaved(f, to, val);
}
//faster than upperSaved when val is at the end of [from:to[
internal virtual int UpperSaved3(int from, int to, int val)
{
int f = to - 1, t = to;
while (f > from)
{
if (CompareSaved(val, f) >= 0)
{
return UpperSaved(f, t, val);
}
int delta = t - f;
t = f;
f -= delta << 1;
}
return UpperSaved(from, t, val);
}
/// <summary>
/// Copy data from slot <paramref name="src"/> to slot <paramref name="dest"/>>. </summary>
protected abstract void Copy(int src, int dest);
/// <summary>
/// Save all elements between slots <paramref name="i"/> and <paramref name="i"/>+<paramref name="len"/>
/// into the temporary storage.
/// </summary>
protected abstract void Save(int i, int len);
/// <summary>
/// Restore element <paramref name="j"/> from the temporary storage into slot <paramref name="i"/>. </summary>
protected abstract void Restore(int i, int j);
/// <summary>
/// Compare element <paramref name="i"/> from the temporary storage with element
/// <paramref name="j"/> from the slice to sort, similarly to
/// <see cref="Sorter.Compare(int, int)"/>.
/// </summary>
protected abstract int CompareSaved(int i, int j);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ShiftRightLogicalUInt6464()
{
var test = new SimpleUnaryOpTest__ShiftRightLogicalUInt6464();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__ShiftRightLogicalUInt6464
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(UInt64);
private const int RetElementCount = VectorSize / sizeof(UInt64);
private static UInt64[] _data = new UInt64[Op1ElementCount];
private static Vector128<UInt64> _clsVar;
private Vector128<UInt64> _fld;
private SimpleUnaryOpTest__DataTable<UInt64, UInt64> _dataTable;
static SimpleUnaryOpTest__ShiftRightLogicalUInt6464()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar), ref Unsafe.As<UInt64, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__ShiftRightLogicalUInt6464()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ulong)(random.Next(0, int.MaxValue)); }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt64, UInt64>(_data, new UInt64[RetElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.ShiftRightLogical(
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr),
64
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.ShiftRightLogical(
Sse2.LoadVector128((UInt64*)(_dataTable.inArrayPtr)),
64
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.ShiftRightLogical(
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArrayPtr)),
64
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr),
(byte)64
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt64*)(_dataTable.inArrayPtr)),
(byte)64
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArrayPtr)),
(byte)64
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.ShiftRightLogical(
_clsVar,
64
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr);
var result = Sse2.ShiftRightLogical(firstOp, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Sse2.LoadVector128((UInt64*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftRightLogical(firstOp, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftRightLogical(firstOp, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__ShiftRightLogicalUInt6464();
var result = Sse2.ShiftRightLogical(test._fld, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.ShiftRightLogical(_fld, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<UInt64> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray = new UInt64[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray = new UInt64[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt64[] firstOp, UInt64[] result, [CallerMemberName] string method = "")
{
if (0 != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (0 != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.ShiftRightLogical)}<UInt64>(Vector128<UInt64><9>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// Copyright (C) 2015-2021 The Neo Project.
//
// The neo is free software distributed under the MIT software license,
// see the accompanying file LICENSE in the main directory of the
// project or http://www.opensource.org/licenses/mit-license.php
// for more details.
//
// Redistribution and use in source and binary forms with or without
// modifications are permitted.
using Neo.IO;
using Neo.IO.Caching;
using Neo.IO.Json;
using Neo.Network.P2P.Payloads;
using Neo.Persistence;
using Neo.Plugins;
using Neo.SmartContract.Manifest;
using Neo.SmartContract.Native;
using Neo.VM;
using Neo.VM.Types;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Reflection;
using static System.Threading.Interlocked;
using Array = System.Array;
using VMArray = Neo.VM.Types.Array;
namespace Neo.SmartContract
{
/// <summary>
/// A virtual machine used to execute smart contracts in the NEO system.
/// </summary>
public partial class ApplicationEngine : ExecutionEngine
{
/// <summary>
/// The maximum cost that can be spent when a contract is executed in test mode.
/// </summary>
public const long TestModeGas = 20_00000000;
/// <summary>
/// Triggered when a contract calls System.Runtime.Notify.
/// </summary>
public static event EventHandler<NotifyEventArgs> Notify;
/// <summary>
/// Triggered when a contract calls System.Runtime.Log.
/// </summary>
public static event EventHandler<LogEventArgs> Log;
private static IApplicationEngineProvider applicationEngineProvider;
private static Dictionary<uint, InteropDescriptor> services;
private TreeNode<UInt160> currentNodeOfInvocationTree = null;
private readonly long gas_amount;
private Dictionary<Type, object> states;
private List<NotifyEventArgs> notifications;
private List<IDisposable> disposables;
private readonly Dictionary<UInt160, int> invocationCounter = new();
private readonly Dictionary<ExecutionContext, ContractTaskAwaiter> contractTasks = new();
private readonly uint exec_fee_factor;
internal readonly uint StoragePrice;
private byte[] nonceData;
/// <summary>
/// Gets the descriptors of all interoperable services available in NEO.
/// </summary>
public static IReadOnlyDictionary<uint, InteropDescriptor> Services => services;
/// <summary>
/// The diagnostic used by the engine. This property can be <see langword="null"/>.
/// </summary>
public Diagnostic Diagnostic { get; }
private List<IDisposable> Disposables => disposables ??= new List<IDisposable>();
/// <summary>
/// The trigger of the execution.
/// </summary>
public TriggerType Trigger { get; }
/// <summary>
/// The container that containing the executed script. This field could be <see langword="null"/> if the contract is invoked by system.
/// </summary>
public IVerifiable ScriptContainer { get; }
/// <summary>
/// The snapshot used to read or write data.
/// </summary>
public DataCache Snapshot { get; }
/// <summary>
/// The block being persisted. This field could be <see langword="null"/> if the <see cref="Trigger"/> is <see cref="TriggerType.Verification"/>.
/// </summary>
public Block PersistingBlock { get; }
/// <summary>
/// The <see cref="Neo.ProtocolSettings"/> used by the engine.
/// </summary>
public ProtocolSettings ProtocolSettings { get; }
/// <summary>
/// GAS spent to execute.
/// </summary>
public long GasConsumed { get; private set; } = 0;
/// <summary>
/// The remaining GAS that can be spent in order to complete the execution.
/// </summary>
public long GasLeft => gas_amount - GasConsumed;
/// <summary>
/// The exception that caused the execution to terminate abnormally. This field could be <see langword="null"/> if no exception is thrown.
/// </summary>
public Exception FaultException { get; private set; }
/// <summary>
/// The script hash of the current context. This field could be <see langword="null"/> if no context is loaded to the engine.
/// </summary>
public UInt160 CurrentScriptHash => CurrentContext?.GetScriptHash();
/// <summary>
/// The script hash of the calling contract. This field could be <see langword="null"/> if the current context is the entry context.
/// </summary>
public UInt160 CallingScriptHash => CurrentContext?.GetState<ExecutionContextState>().CallingScriptHash;
/// <summary>
/// The script hash of the entry context. This field could be <see langword="null"/> if no context is loaded to the engine.
/// </summary>
public UInt160 EntryScriptHash => EntryContext?.GetScriptHash();
/// <summary>
/// The notifications sent during the execution.
/// </summary>
public IReadOnlyList<NotifyEventArgs> Notifications => notifications ?? (IReadOnlyList<NotifyEventArgs>)Array.Empty<NotifyEventArgs>();
/// <summary>
/// Initializes a new instance of the <see cref="ApplicationEngine"/> class.
/// </summary>
/// <param name="trigger">The trigger of the execution.</param>
/// <param name="container">The container of the script.</param>
/// <param name="snapshot">The snapshot used by the engine during execution.</param>
/// <param name="persistingBlock">The block being persisted. It should be <see langword="null"/> if the <paramref name="trigger"/> is <see cref="TriggerType.Verification"/>.</param>
/// <param name="settings">The <see cref="Neo.ProtocolSettings"/> used by the engine.</param>
/// <param name="gas">The maximum gas used in this execution. The execution will fail when the gas is exhausted.</param>
/// <param name="diagnostic">The diagnostic to be used by the <see cref="ApplicationEngine"/>.</param>
protected unsafe ApplicationEngine(TriggerType trigger, IVerifiable container, DataCache snapshot, Block persistingBlock, ProtocolSettings settings, long gas, Diagnostic diagnostic)
{
this.Trigger = trigger;
this.ScriptContainer = container;
this.Snapshot = snapshot;
this.PersistingBlock = persistingBlock;
this.ProtocolSettings = settings;
this.gas_amount = gas;
this.Diagnostic = diagnostic;
this.exec_fee_factor = snapshot is null || persistingBlock?.Index == 0 ? PolicyContract.DefaultExecFeeFactor : NativeContract.Policy.GetExecFeeFactor(Snapshot);
this.StoragePrice = snapshot is null || persistingBlock?.Index == 0 ? PolicyContract.DefaultStoragePrice : NativeContract.Policy.GetStoragePrice(Snapshot);
this.nonceData = container is Transaction tx ? tx.Hash.ToArray()[..16] : new byte[16];
if (persistingBlock is not null)
{
fixed (byte* p = nonceData)
{
*(ulong*)p ^= persistingBlock.Nonce;
}
}
}
/// <summary>
/// Adds GAS to <see cref="GasConsumed"/> and checks if it has exceeded the maximum limit.
/// </summary>
/// <param name="gas">The amount of GAS to be added.</param>
protected internal void AddGas(long gas)
{
GasConsumed = checked(GasConsumed + gas);
if (GasConsumed > gas_amount)
throw new InvalidOperationException("Insufficient GAS.");
}
protected override void OnFault(Exception ex)
{
FaultException = ex;
base.OnFault(ex);
}
internal void Throw(Exception ex)
{
OnFault(ex);
}
private ExecutionContext CallContractInternal(UInt160 contractHash, string method, CallFlags flags, bool hasReturnValue, StackItem[] args)
{
ContractState contract = NativeContract.ContractManagement.GetContract(Snapshot, contractHash);
if (contract is null) throw new InvalidOperationException($"Called Contract Does Not Exist: {contractHash}");
ContractMethodDescriptor md = contract.Manifest.Abi.GetMethod(method, args.Length);
if (md is null) throw new InvalidOperationException($"Method \"{method}\" with {args.Length} parameter(s) doesn't exist in the contract {contractHash}.");
return CallContractInternal(contract, md, flags, hasReturnValue, args);
}
private ExecutionContext CallContractInternal(ContractState contract, ContractMethodDescriptor method, CallFlags flags, bool hasReturnValue, IReadOnlyList<StackItem> args)
{
if (NativeContract.Policy.IsBlocked(Snapshot, contract.Hash))
throw new InvalidOperationException($"The contract {contract.Hash} has been blocked.");
if (method.Safe)
{
flags &= ~(CallFlags.WriteStates | CallFlags.AllowNotify);
}
else
{
ContractState currentContract = NativeContract.ContractManagement.GetContract(Snapshot, CurrentScriptHash);
if (currentContract?.CanCall(contract, method.Name) == false)
throw new InvalidOperationException($"Cannot Call Method {method} Of Contract {contract.Hash} From Contract {CurrentScriptHash}");
}
if (invocationCounter.TryGetValue(contract.Hash, out var counter))
{
invocationCounter[contract.Hash] = counter + 1;
}
else
{
invocationCounter[contract.Hash] = 1;
}
ExecutionContextState state = CurrentContext.GetState<ExecutionContextState>();
UInt160 callingScriptHash = state.ScriptHash;
CallFlags callingFlags = state.CallFlags;
if (args.Count != method.Parameters.Length) throw new InvalidOperationException($"Method {method} Expects {method.Parameters.Length} Arguments But Receives {args.Count} Arguments");
if (hasReturnValue ^ (method.ReturnType != ContractParameterType.Void)) throw new InvalidOperationException("The return value type does not match.");
ExecutionContext context_new = LoadContract(contract, method, flags & callingFlags);
state = context_new.GetState<ExecutionContextState>();
state.CallingScriptHash = callingScriptHash;
for (int i = args.Count - 1; i >= 0; i--)
context_new.EvaluationStack.Push(args[i]);
return context_new;
}
internal ContractTask CallFromNativeContract(UInt160 callingScriptHash, UInt160 hash, string method, params StackItem[] args)
{
ExecutionContext context_new = CallContractInternal(hash, method, CallFlags.All, false, args);
ExecutionContextState state = context_new.GetState<ExecutionContextState>();
state.CallingScriptHash = callingScriptHash;
ContractTask task = new();
contractTasks.Add(context_new, task.GetAwaiter());
return task;
}
internal ContractTask<T> CallFromNativeContract<T>(UInt160 callingScriptHash, UInt160 hash, string method, params StackItem[] args)
{
ExecutionContext context_new = CallContractInternal(hash, method, CallFlags.All, true, args);
ExecutionContextState state = context_new.GetState<ExecutionContextState>();
state.CallingScriptHash = callingScriptHash;
ContractTask<T> task = new();
contractTasks.Add(context_new, task.GetAwaiter());
return task;
}
protected override void ContextUnloaded(ExecutionContext context)
{
base.ContextUnloaded(context);
if (Diagnostic is not null)
currentNodeOfInvocationTree = currentNodeOfInvocationTree.Parent;
if (!contractTasks.Remove(context, out var awaiter)) return;
if (UncaughtException is not null)
throw new VMUnhandledException(UncaughtException);
awaiter.SetResult(this);
}
/// <summary>
/// Use the loaded <see cref="IApplicationEngineProvider"/> to create a new instance of the <see cref="ApplicationEngine"/> class. If no <see cref="IApplicationEngineProvider"/> is loaded, the constructor of <see cref="ApplicationEngine"/> will be called.
/// </summary>
/// <param name="trigger">The trigger of the execution.</param>
/// <param name="container">The container of the script.</param>
/// <param name="snapshot">The snapshot used by the engine during execution.</param>
/// <param name="persistingBlock">The block being persisted. It should be <see langword="null"/> if the <paramref name="trigger"/> is <see cref="TriggerType.Verification"/>.</param>
/// <param name="settings">The <see cref="Neo.ProtocolSettings"/> used by the engine.</param>
/// <param name="gas">The maximum gas used in this execution. The execution will fail when the gas is exhausted.</param>
/// <param name="diagnostic">The diagnostic to be used by the <see cref="ApplicationEngine"/>.</param>
/// <returns>The engine instance created.</returns>
public static ApplicationEngine Create(TriggerType trigger, IVerifiable container, DataCache snapshot, Block persistingBlock = null, ProtocolSettings settings = null, long gas = TestModeGas, Diagnostic diagnostic = null)
{
return applicationEngineProvider?.Create(trigger, container, snapshot, persistingBlock, settings, gas, diagnostic)
?? new ApplicationEngine(trigger, container, snapshot, persistingBlock, settings, gas, diagnostic);
}
protected override void LoadContext(ExecutionContext context)
{
// Set default execution context state
var state = context.GetState<ExecutionContextState>();
state.ScriptHash ??= ((byte[])context.Script).ToScriptHash();
invocationCounter.TryAdd(state.ScriptHash, 1);
if (Diagnostic is not null)
{
if (currentNodeOfInvocationTree is null)
currentNodeOfInvocationTree = Diagnostic.InvocationTree.AddRoot(state.ScriptHash);
else
currentNodeOfInvocationTree = currentNodeOfInvocationTree.AddChild(state.ScriptHash);
}
base.LoadContext(context);
}
/// <summary>
/// Loads a deployed contract to the invocation stack. If the _initialize method is found on the contract, loads it as well.
/// </summary>
/// <param name="contract">The contract to be loaded.</param>
/// <param name="method">The method of the contract to be called.</param>
/// <param name="callFlags">The <see cref="CallFlags"/> used to call the method.</param>
/// <returns>The loaded context.</returns>
public ExecutionContext LoadContract(ContractState contract, ContractMethodDescriptor method, CallFlags callFlags)
{
ExecutionContext context = LoadScript(contract.Script,
rvcount: method.ReturnType == ContractParameterType.Void ? 0 : 1,
initialPosition: method.Offset,
configureState: p =>
{
p.CallFlags = callFlags;
p.ScriptHash = contract.Hash;
p.Contract = new ContractState
{
Id = contract.Id,
UpdateCounter = contract.UpdateCounter,
Hash = contract.Hash,
Nef = contract.Nef,
Manifest = contract.Manifest
};
});
// Call initialization
var init = contract.Manifest.Abi.GetMethod("_initialize", 0);
if (init != null)
{
LoadContext(context.Clone(init.Offset));
}
return context;
}
/// <summary>
/// Loads a script to the invocation stack.
/// </summary>
/// <param name="script">The script to be loaded.</param>
/// <param name="rvcount">The number of return values of the script.</param>
/// <param name="initialPosition">The initial position of the instruction pointer.</param>
/// <param name="configureState">The action used to configure the state of the loaded context.</param>
/// <returns>The loaded context.</returns>
public ExecutionContext LoadScript(Script script, int rvcount = -1, int initialPosition = 0, Action<ExecutionContextState> configureState = null)
{
// Create and configure context
ExecutionContext context = CreateContext(script, rvcount, initialPosition);
configureState?.Invoke(context.GetState<ExecutionContextState>());
// Load context
LoadContext(context);
return context;
}
protected override ExecutionContext LoadToken(ushort tokenId)
{
ValidateCallFlags(CallFlags.ReadStates | CallFlags.AllowCall);
ContractState contract = CurrentContext.GetState<ExecutionContextState>().Contract;
if (contract is null || tokenId >= contract.Nef.Tokens.Length)
throw new InvalidOperationException();
MethodToken token = contract.Nef.Tokens[tokenId];
if (token.ParametersCount > CurrentContext.EvaluationStack.Count)
throw new InvalidOperationException();
StackItem[] args = new StackItem[token.ParametersCount];
for (int i = 0; i < token.ParametersCount; i++)
args[i] = Pop();
return CallContractInternal(token.Hash, token.Method, token.CallFlags, token.HasReturnValue, args);
}
/// <summary>
/// Converts an <see cref="object"/> to a <see cref="StackItem"/> that used in the virtual machine.
/// </summary>
/// <param name="value">The <see cref="object"/> to convert.</param>
/// <returns>The converted <see cref="StackItem"/>.</returns>
protected internal StackItem Convert(object value)
{
if (value is IDisposable disposable) Disposables.Add(disposable);
return value switch
{
null => StackItem.Null,
bool b => b,
sbyte i => i,
byte i => (BigInteger)i,
short i => i,
ushort i => (BigInteger)i,
int i => i,
uint i => i,
long i => i,
ulong i => i,
Enum e => Convert(System.Convert.ChangeType(e, e.GetTypeCode())),
byte[] data => data,
string s => s,
BigInteger i => i,
JObject o => o.ToByteArray(false),
IInteroperable interoperable => interoperable.ToStackItem(ReferenceCounter),
ISerializable i => i.ToArray(),
StackItem item => item,
(object a, object b) => new Struct(ReferenceCounter) { Convert(a), Convert(b) },
Array array => new VMArray(ReferenceCounter, array.OfType<object>().Select(p => Convert(p))),
_ => StackItem.FromInterface(value)
};
}
/// <summary>
/// Converts a <see cref="StackItem"/> to an <see cref="object"/> that to be used as an argument of an interoperable service or native contract.
/// </summary>
/// <param name="item">The <see cref="StackItem"/> to convert.</param>
/// <param name="descriptor">The descriptor of the parameter.</param>
/// <returns>The converted <see cref="object"/>.</returns>
protected internal object Convert(StackItem item, InteropParameterDescriptor descriptor)
{
descriptor.Validate(item);
if (descriptor.IsArray)
{
Array av;
if (item is VMArray array)
{
av = Array.CreateInstance(descriptor.Type.GetElementType(), array.Count);
for (int i = 0; i < av.Length; i++)
av.SetValue(descriptor.Converter(array[i]), i);
}
else
{
int count = (int)item.GetInteger();
if (count > Limits.MaxStackSize) throw new InvalidOperationException();
av = Array.CreateInstance(descriptor.Type.GetElementType(), count);
for (int i = 0; i < av.Length; i++)
av.SetValue(descriptor.Converter(Pop()), i);
}
return av;
}
else
{
object value = descriptor.Converter(item);
if (descriptor.IsEnum)
value = Enum.ToObject(descriptor.Type, value);
else if (descriptor.IsInterface)
value = ((InteropInterface)value).GetInterface<object>();
return value;
}
}
public override void Dispose()
{
if (disposables != null)
{
foreach (IDisposable disposable in disposables)
disposable.Dispose();
disposables = null;
}
base.Dispose();
}
/// <summary>
/// Determines whether the <see cref="CallFlags"/> of the current context meets the specified requirements.
/// </summary>
/// <param name="requiredCallFlags">The requirements to check.</param>
internal protected void ValidateCallFlags(CallFlags requiredCallFlags)
{
ExecutionContextState state = CurrentContext.GetState<ExecutionContextState>();
if (!state.CallFlags.HasFlag(requiredCallFlags))
throw new InvalidOperationException($"Cannot call this SYSCALL with the flag {state.CallFlags}.");
}
protected override void OnSysCall(uint method)
{
OnSysCall(services[method]);
}
/// <summary>
/// Invokes the specified interoperable service.
/// </summary>
/// <param name="descriptor">The descriptor of the interoperable service.</param>
protected virtual void OnSysCall(InteropDescriptor descriptor)
{
ValidateCallFlags(descriptor.RequiredCallFlags);
AddGas(descriptor.FixedPrice * exec_fee_factor);
object[] parameters = new object[descriptor.Parameters.Count];
for (int i = 0; i < parameters.Length; i++)
parameters[i] = Convert(Pop(), descriptor.Parameters[i]);
object returnValue = descriptor.Handler.Invoke(this, parameters);
if (descriptor.Handler.ReturnType != typeof(void))
Push(Convert(returnValue));
}
protected override void PreExecuteInstruction()
{
if (CurrentContext.InstructionPointer < CurrentContext.Script.Length)
AddGas(exec_fee_factor * OpCodePrices[CurrentContext.CurrentInstruction.OpCode]);
}
private static Block CreateDummyBlock(DataCache snapshot, ProtocolSettings settings)
{
UInt256 hash = NativeContract.Ledger.CurrentHash(snapshot);
Block currentBlock = NativeContract.Ledger.GetBlock(snapshot, hash);
return new Block
{
Header = new Header
{
Version = 0,
PrevHash = hash,
MerkleRoot = new UInt256(),
Timestamp = currentBlock.Timestamp + settings.MillisecondsPerBlock,
Index = currentBlock.Index + 1,
NextConsensus = currentBlock.NextConsensus,
Witness = new Witness
{
InvocationScript = Array.Empty<byte>(),
VerificationScript = Array.Empty<byte>()
},
},
Transactions = Array.Empty<Transaction>()
};
}
private static InteropDescriptor Register(string name, string handler, long fixedPrice, CallFlags requiredCallFlags)
{
MethodInfo method = typeof(ApplicationEngine).GetMethod(handler, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)
?? typeof(ApplicationEngine).GetProperty(handler, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static).GetMethod;
InteropDescriptor descriptor = new()
{
Name = name,
Handler = method,
FixedPrice = fixedPrice,
RequiredCallFlags = requiredCallFlags
};
services ??= new Dictionary<uint, InteropDescriptor>();
services.Add(descriptor.Hash, descriptor);
return descriptor;
}
internal static void ResetApplicationEngineProvider()
{
Exchange(ref applicationEngineProvider, null);
}
/// <summary>
/// Creates a new instance of the <see cref="ApplicationEngine"/> class, and use it to run the specified script.
/// </summary>
/// <param name="script">The script to be executed.</param>
/// <param name="snapshot">The snapshot used by the engine during execution.</param>
/// <param name="container">The container of the script.</param>
/// <param name="persistingBlock">The block being persisted.</param>
/// <param name="settings">The <see cref="Neo.ProtocolSettings"/> used by the engine.</param>
/// <param name="offset">The initial position of the instruction pointer.</param>
/// <param name="gas">The maximum gas used in this execution. The execution will fail when the gas is exhausted.</param>
/// <param name="diagnostic">The diagnostic to be used by the <see cref="ApplicationEngine"/>.</param>
/// <returns>The engine instance created.</returns>
public static ApplicationEngine Run(byte[] script, DataCache snapshot, IVerifiable container = null, Block persistingBlock = null, ProtocolSettings settings = null, int offset = 0, long gas = TestModeGas, Diagnostic diagnostic = null)
{
persistingBlock ??= CreateDummyBlock(snapshot, settings ?? ProtocolSettings.Default);
ApplicationEngine engine = Create(TriggerType.Application, container, snapshot, persistingBlock, settings, gas, diagnostic);
engine.LoadScript(script, initialPosition: offset);
engine.Execute();
return engine;
}
internal static bool SetApplicationEngineProvider(IApplicationEngineProvider provider)
{
return CompareExchange(ref applicationEngineProvider, provider, null) is null;
}
public T GetState<T>()
{
if (states is null) return default;
if (!states.TryGetValue(typeof(T), out object state)) return default;
return (T)state;
}
public void SetState<T>(T state)
{
states ??= new Dictionary<Type, object>();
states[typeof(T)] = state;
}
}
}
| |
using Robust.Shared.GameObjects;
using Robust.Shared.Serialization;
using Robust.Shared.Utility;
using System;
using Content.Shared.Database;
using System.Collections.Generic;
namespace Content.Shared.Verbs
{
/// <summary>
/// Verb objects describe actions that a user can take. The actions can be specified via an Action, local
/// events, or networked events. Verbs also provide text, icons, and categories for displaying in the
/// context-menu.
/// </summary>
[Serializable, NetSerializable, Virtual]
public class Verb : IComparable
{
public static string DefaultTextStyleClass = "Verb";
/// <summary>
/// Determines the priority of this type of verb when displaying in the verb-menu. See <see
/// cref="CompareTo"/>.
/// </summary>
public virtual int TypePriority => 0;
/// <summary>
/// Style class for drawing in the context menu
/// </summary>
public string TextStyleClass = DefaultTextStyleClass;
/// <summary>
/// This is an action that will be run when the verb is "acted" out.
/// </summary>
/// <remarks>
/// This delegate probably just points to some function in the system assembling this verb. This delegate
/// will be run regardless of whether <see cref="ExecutionEventArgs"/> is defined.
/// </remarks>
[NonSerialized]
public Action? Act;
/// <summary>
/// This is a general local event that will be raised when the verb is executed.
/// </summary>
/// <remarks>
/// If not null, this event will be raised regardless of whether <see cref="Act"/> was run. If this event
/// exists purely to call a specific system method, then <see cref="Act"/> should probably be used instead (method
/// events are a no-go).
/// </remarks>
[NonSerialized]
public object? ExecutionEventArgs;
/// <summary>
/// Where do direct the local event. If invalid, the event is not raised directed at any entity.
/// </summary>
[NonSerialized]
public EntityUid EventTarget = EntityUid.Invalid;
/// <summary>
/// If a verb is only defined client-side, this should be set to true.
/// </summary>
/// <remarks>
/// If true, the client will not also ask the server to run this verb when executed locally. This just
/// prevents unnecessary network events and "404-verb-not-found" log entries.
/// </remarks>
[NonSerialized]
public bool ClientExclusive;
/// <summary>
/// The text that the user sees on the verb button.
/// </summary>
public string Text = string.Empty;
/// <summary>
/// Sprite of the icon that the user sees on the verb button.
/// </summary>
public SpriteSpecifier? Icon
{
get => _icon ??=
IconTexture == null ? null : new SpriteSpecifier.Texture(new ResourcePath(IconTexture));
set => _icon = value;
}
[NonSerialized]
private SpriteSpecifier? _icon;
/// <summary>
/// Name of the category this button is under. Used to group verbs in the context menu.
/// </summary>
public VerbCategory? Category;
/// <summary>
/// Whether this verb is disabled.
/// </summary>
/// <remarks>
/// Disabled verbs are shown in the context menu with a slightly darker background color, and cannot be
/// executed. It is recommended that a <see cref="Message"/> message be provided outlining why this verb is
/// disabled.
/// </remarks>
public bool Disabled;
/// <summary>
/// Optional informative message.
/// </summary>
/// <remarks>
/// This will be shown as a tooltip when hovering over this verb in the context menu. Additionally, iF a
/// <see cref="Disabled"/> verb is executed, this message will also be shown as a pop-up message. Useful for
/// disabled verbs to inform users about why they cannot perform a given action.
/// </remarks>
public string? Message;
/// <summary>
/// Determines the priority of the verb. This affects both how the verb is displayed in the context menu
/// GUI, and which verb is actually executed when left/alt clicking.
/// </summary>
/// <remarks>
/// Bigger is higher priority (appears first, gets executed preferentially).
/// </remarks>
public int Priority;
/// <summary>
/// Raw texture path used to load the <see cref="Icon"/> for displaying on the client.
/// </summary>
public string? IconTexture;
/// <summary>
/// If this is not null, and no icon or icon texture were specified, a sprite view of this entity will be
/// used as the icon for this verb.
/// </summary>
public EntityUid? IconEntity;
/// <summary>
/// Whether or not to close the context menu after using it to run this verb.
/// </summary>
/// <remarks>
/// Setting this to false may be useful for repeatable actions, like rotating an object or maybe knocking on
/// a window.
/// </remarks>
public bool CloseMenu = true;
/// <summary>
/// How important is this verb, for the purposes of admin logging?
/// </summary>
/// <remarks>
/// If this is just opening a UI or ejecting an id card, this should probably be low.
/// </remarks>
public LogImpact Impact = LogImpact.Low;
/// <summary>
/// Whether this verb requires confirmation before being executed.
/// </summary>
public bool ConfirmationPopup = false;
/// <summary>
/// Compares two verbs based on their <see cref="Priority"/>, <see cref="Category"/>, <see cref="Text"/>,
/// and <see cref="IconTexture"/>.
/// </summary>
/// <remarks>
/// <para>
/// This is comparison is used when storing verbs in a SortedSet. The ordering of verbs determines both how
/// the verbs are displayed in the context menu, and the order in which alternative action verbs are
/// executed when alt-clicking.
/// </para>
/// <para>
/// If two verbs are equal according to this comparison, they cannot both be added to the same sorted set of
/// verbs. This is desirable, given that these verbs would also appear identical in the context menu.
/// Distinct verbs should always have a unique and descriptive combination of text, icon, and category.
/// </para>
/// </remarks>
public int CompareTo(object? obj)
{
if (obj is not Verb otherVerb)
return -1;
// Sort first by type-priority
if (TypePriority != otherVerb.TypePriority)
return otherVerb.TypePriority - TypePriority;
// Then by verb-priority
if (Priority != otherVerb.Priority)
return otherVerb.Priority - Priority;
// Then try use alphabetical verb categories. Uncategorized verbs always appear first.
if (Category?.Text != otherVerb.Category?.Text)
{
return string.Compare(Category?.Text, otherVerb.Category?.Text, StringComparison.CurrentCulture);
}
// Then try use alphabetical verb text.
if (Text != otherVerb.Text)
{
return string.Compare(Text, otherVerb.Text, StringComparison.CurrentCulture);
}
// Finally, compare icon texture paths. Note that this matters for verbs that don't have any text (e.g., the rotate-verbs)
return string.Compare(IconTexture, otherVerb.IconTexture, StringComparison.CurrentCulture);
}
/// <summary>
/// Collection of all verb types, along with string keys.
/// </summary>
/// <remarks>
/// Useful when iterating over verb types, though maybe this should be obtained and stored via reflection or
/// something (list of all classes that inherit from Verb). Currently used for networking (apparently Type
/// is not serializable?), and resolving console commands.
/// </remarks>
public static List<Type> VerbTypes = new()
{
{ typeof(Verb) },
{ typeof(InteractionVerb) },
{ typeof(UtilityVerb) },
{ typeof(AlternativeVerb) },
{ typeof(ActivationVerb) },
{ typeof(ExamineVerb) }
};
}
/// <summary>
/// Primary interaction verbs. This includes both use-in-hand and interacting with external entities.
/// </summary>
/// <remarks>
/// These verbs those that involve using the hands or the currently held item on some entity. These verbs usually
/// correspond to interactions that can be triggered by left-clicking or using 'Z', and often depend on the
/// currently held item. These verbs are collectively shown first in the context menu.
/// </remarks>
[Serializable, NetSerializable]
public sealed class InteractionVerb : Verb
{
public new static string DefaultTextStyleClass = "InteractionVerb";
public override int TypePriority => 4;
public InteractionVerb() : base()
{
TextStyleClass = DefaultTextStyleClass;
}
}
/// <summary>
/// These verbs are similar to the normal interaction verbs, except these interactions are facilitated by the
/// currently held entity.
/// </summary>
/// <remarks>
/// The only notable difference between these and InteractionVerbs is that they are obtained by raising an event
/// directed at the currently held entity. Distinguishing between utility and interaction verbs helps avoid
/// confusion if a component enables verbs both when the item is used on something else, or when it is the
/// target of an interaction. These verbs are only obtained if the target and the held entity are NOT the same.
/// </remarks>
[Serializable, NetSerializable]
public sealed class UtilityVerb : Verb
{
public override int TypePriority => 3;
public UtilityVerb() : base()
{
TextStyleClass = InteractionVerb.DefaultTextStyleClass;
}
}
/// <summary>
/// Verbs for alternative-interactions.
/// </summary>
/// <remarks>
/// When interacting with an entity via alt + left-click/E/Z the highest priority alt-interact verb is executed.
/// These verbs are collectively shown second-to-last in the context menu.
/// </remarks>
[Serializable, NetSerializable]
public sealed class AlternativeVerb : Verb
{
public override int TypePriority => 2;
public new static string DefaultTextStyleClass = "AlternativeVerb";
public AlternativeVerb() : base()
{
TextStyleClass = DefaultTextStyleClass;
}
}
/// <summary>
/// Activation-type verbs.
/// </summary>
/// <remarks>
/// These are verbs that activate an item in the world but are independent of the currently held items. For
/// example, opening a door or a GUI. These verbs should correspond to interactions that can be triggered by
/// using 'E', though many of those can also be triggered by left-mouse or 'Z' if there is no other interaction.
/// These verbs are collectively shown second in the context menu.
/// </remarks>
[Serializable, NetSerializable]
public sealed class ActivationVerb : Verb
{
public override int TypePriority => 1;
public new static string DefaultTextStyleClass = "ActivationVerb";
public ActivationVerb() : base()
{
TextStyleClass = DefaultTextStyleClass;
}
}
[Serializable, NetSerializable]
public sealed class ExamineVerb : Verb
{
public override int TypePriority => 0;
public bool ShowOnExamineTooltip = true;
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Management.ApiManagement;
using Microsoft.Azure.Management.ApiManagement.SmapiModels;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.ApiManagement
{
/// <summary>
/// Operations for managing User Identities.
/// </summary>
internal partial class UserIdentitiesOperations : IServiceOperations<ApiManagementClient>, IUserIdentitiesOperations
{
/// <summary>
/// Initializes a new instance of the UserIdentitiesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal UserIdentitiesOperations(ApiManagementClient client)
{
this._client = client;
}
private ApiManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.ApiManagement.ApiManagementClient.
/// </summary>
public ApiManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// List all user identities.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='uid'>
/// Required. Identifier of the user.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List User Identities operation response details.
/// </returns>
public async Task<UserIdentityListResponse> ListAsync(string resourceGroupName, string serviceName, string uid, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (uid == null)
{
throw new ArgumentNullException("uid");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("uid", uid);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/users/";
url = url + Uri.EscapeDataString(uid);
url = url + "/identities";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-10-10");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
UserIdentityListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new UserIdentityListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc;
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
UserIdentityContract userIdentityContractInstance = new UserIdentityContract();
result.Values.Add(userIdentityContractInstance);
JToken providerValue = valueValue["provider"];
if (providerValue != null && providerValue.Type != JTokenType.Null)
{
string providerInstance = ((string)providerValue);
userIdentityContractInstance.Provider = providerInstance;
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
userIdentityContractInstance.Id = idInstance;
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using OmniSharp.Models;
using Xunit;
namespace OmniSharp.Tests
{
public class FixUsingsFacts
{
string fileName = "test.cs";
[Fact]
public async Task FixUsings_AddsUsingSingle()
{
const string fileContents = @"namespace nsA {
public class classX{}
}
namespace OmniSharp {
public class class1
{
public method1()
{
var c1 = new classX();
}
}
}";
string expectedFileContents = @"using nsA;" +
Environment.NewLine +
@"namespace nsA {
public class classX{}
}
namespace OmniSharp {
public class class1
{
public method1()
{
var c1 = new classX();
}
}
}";
await AssertBufferContents(fileContents, expectedFileContents);
}
[Fact]
public async Task FixUsings_AddsUsingSingleForFrameworkMethod()
{
const string fileContents = @"namespace OmniSharp {
public class class1
{
public void method1()()
{
Console.WriteLine(""abc"");
}
}
}";
string expectedFileContents = @"using System;" +
Environment.NewLine +
@"namespace OmniSharp {
public class class1
{
public void method1()()
{
Console.WriteLine(""abc"");
}
}
}";
await AssertBufferContents(fileContents, expectedFileContents);
}
[Fact]
public async Task FixUsings_AddsUsingSingleForFrameworkClass()
{
const string fileContents = @"namespace OmniSharp {
public class class1
{
public void method1()()
{
var s = new StringBuilder();
}
}
}";
string expectedFileContents = @"using System.Text;" +
Environment.NewLine +
@"namespace OmniSharp {
public class class1
{
public void method1()()
{
var s = new StringBuilder();
}
}
}";
await AssertBufferContents(fileContents, expectedFileContents);
}
[Fact]
public async Task FixUsings_AddsUsingMultiple()
{
const string fileContents = @"namespace nsA {
public class classX{}
}
namespace nsB {
public class classY{}
}
namespace OmniSharp {
public class class1
{
public method1()
{
var c1 = new classX();
var c2 = new classY();
}
}
}";
string expectedFileContents = @"using nsA;" +
Environment.NewLine +
@"using nsB;" +
Environment.NewLine +
@"namespace nsA {
public class classX{}
}
namespace nsB {
public class classY{}
}
namespace OmniSharp {
public class class1
{
public method1()
{
var c1 = new classX();
var c2 = new classY();
}
}
}";
await AssertBufferContents(fileContents, expectedFileContents);
}
[Fact]
public async Task FixUsings_AddsUsingMultipleForFramework()
{
const string fileContents = @"namespace OmniSharp {
public class class1
{
public void method1()
{
Console.WriteLine(""abc"");
var sb = new StringBuilder();
}
}
}";
string expectedFileContents = @"using System;" +
Environment.NewLine +
@"using System.Text;" +
Environment.NewLine +
@"namespace OmniSharp {
public class class1
{
public void method1()
{
Console.WriteLine(""abc"");
var sb = new StringBuilder();
}
}
}";
await AssertBufferContents(fileContents, expectedFileContents);
}
[Fact]
public async Task FixUsings_ReturnsAmbiguousResult()
{
const string fileContents = @"
namespace nsA {
public class classX{}
}
namespace nsB {
public class classX{}
}
namespace OmniSharp {
public class class1
{
public method1()
{
var c1 = new $classX();
}
}
}";
var classLineColumn = TestHelpers.GetLineAndColumnFromDollar(TestHelpers.RemovePercentMarker(fileContents));
var fileContentNoDollarMarker = TestHelpers.RemoveDollarMarker(fileContents);
var expectedUnresolved = new List<QuickFix>();
expectedUnresolved.Add(new QuickFix()
{
Line = classLineColumn.Line,
Column = classLineColumn.Column,
FileName = fileName,
Text = "`classX` is ambiguous"
});
await AssertUnresolvedReferences(fileContentNoDollarMarker, expectedUnresolved);
}
[Fact]
public async Task FixUsings_ReturnsNoUsingsForAmbiguousResult()
{
const string fileContents = @"namespace nsA {
public class classX{}
}
namespace nsB {
public class classX{}
}
namespace OmniSharp {
public class class1
{
public method1()
{
var c1 = new classX();
}
}
}";
await AssertBufferContents(fileContents, fileContents);
}
[Fact]
public async Task FixUsings_AddsUsingForExtension()
{
const string fileContents = @"namespace nsA {
public static class StringExtension {
public static void Whatever(this string astring) {}
}
}
namespace OmniSharp {
public class class1
{
public method1()
{
""string"".Whatever();
}
}
}";
string expectedFileContents = @"using nsA;" +
Environment.NewLine +
@"namespace nsA {
public static class StringExtension {
public static void Whatever(this string astring) {}
}
}
namespace OmniSharp {
public class class1
{
public method1()
{
""string"".Whatever();
}
}
}";
await AssertBufferContents(fileContents, expectedFileContents);
}
[Fact]
public async Task FixUsings_AddsUsingLinq()
{
const string fileContents = @"namespace OmniSharp {
public class class1
{
public void method1()
{
List<string> first = new List<string>();
var testing = first.Where(s => s == ""abc"");
}
}
}";
string expectedFileContents = @"using System.Collections.Generic;" +
Environment.NewLine +
@"using System.Linq;" +
Environment.NewLine +
@"namespace OmniSharp {
public class class1
{
public void method1()
{
List<string> first = new List<string>();
var testing = first.Where(s => s == ""abc"");
}
}
}";
await AssertBufferContents(fileContents, expectedFileContents);
}
private async Task AssertBufferContents(string fileContents, string expectedFileContents)
{
var response = await RunFixUsings(fileContents);
Assert.Equal(response.Buffer, expectedFileContents);
}
private async Task AssertUnresolvedReferences(string fileContents, List<QuickFix> expectedUnresolved)
{
var response = await RunFixUsings(fileContents);
var qfList = response.AmbiguousResults.ToList();
Assert.Equal(qfList.Count(), expectedUnresolved.Count());
var i = 0;
foreach (var expectedQuickFix in expectedUnresolved)
{
Assert.Equal(qfList[i].Line, expectedQuickFix.Line);
Assert.Equal(qfList[i].Column, expectedQuickFix.Column);
Assert.Equal(qfList[i].FileName, expectedQuickFix.FileName);
Assert.Equal(qfList[i].Text, expectedQuickFix.Text);
i++;
}
}
private async Task<FixUsingsResponse> RunFixUsings(string fileContents)
{
var workspace = TestHelpers.CreateSimpleWorkspace(fileContents, fileName);
var controller = new OmnisharpController(workspace, null);
var request = new Request
{
FileName = fileName,
Buffer = fileContents
};
return await controller.FixUsings(request);
}
}
}
| |
// 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.
/*
Test the following matrix for classes with virtual newslot final methods (explicit override):
Non-Generic virtual methods:
Non-generic Interface Generic Interface
Non-generic type N/A Test4
Generic type Test2 Test6
Generic virtual methods:
Non-generic Interface Generic Interface
Non-generic type Test1 Test5
Generic type Test3 Test7
*/
using System;
public class A<T>
{}
public struct S<T>
{}
public interface I
{
int method1();
int method2<T>();
}
public interface IGen<T>
{
int method1();
int method2<M>();
}
public class C1 : I
{
int I.method1()
{
return 1;
}
int I.method2<T>()
{
return 2;
}
}
public class C2<T> : I
{
int I.method1()
{
return 3;
}
int I.method2<U>()
{
return 4;
}
}
public class C3Int : IGen<int>
{
int IGen<int>.method1()
{
return 5;
}
int IGen<int>.method2<U>()
{
return 6;
}
}
public class C3String : IGen<string>
{
int IGen<string>.method1()
{
return 5;
}
int IGen<string>.method2<U>()
{
return 6;
}
}
public class C3Object: IGen<object>
{
int IGen<object>.method1()
{
return 5;
}
int IGen<object>.method2<U>()
{
return 6;
}
}
public class C4<T> : IGen<T>
{
int IGen<T>.method1()
{
return 7;
}
int IGen<T>.method2<U>()
{
return 8;
}
}
public class Test
{
public static bool pass = true;
public static void TestNonGenInterface_NonGenType()
{
I ic1 = new C1();
// TEST1: test generic virtual method
if (ic1.method2<int>() != 2 || ic1.method2<string>() != 2 || ic1.method2<object>() != 2
|| ic1.method2<A<int>>() != 2 || ic1.method2<S<object>>() != 2 )
{
Console.WriteLine("Failed at TestNonGenInterface_NonGenType: generic method");
pass = false;
}
}
public static void TestNonGenInterface_GenType()
{
I ic2Int = new C2<int>();
I ic2Object = new C2<object>();
I ic2String = new C2<string>();
// TEST2: test non generic virtual method
if ( ic2Int.method1() != 3 || ic2String.method1() != 3 || ic2Object.method1() != 3 )
{
Console.WriteLine("Failed at TestNonGenInterface_GenType: non generic method");
pass = false;
}
// TEST3: test generic virtual method
if (ic2Int.method2<int>() != 4 || ic2Int.method2<object>() != 4|| ic2Int.method2<string>() != 4
|| ic2Int.method2<A<int>>() != 4 || ic2Int.method2<S<string>>() != 4
|| ic2String.method2<int>() != 4 || ic2String.method2<object>() != 4|| ic2String.method2<string>() != 4
|| ic2String.method2<A<int>>() != 4 || ic2String.method2<S<string>>() != 4
|| ic2Object.method2<int>() != 4 || ic2Object.method2<object>() != 4|| ic2Object.method2<string>() != 4
|| ic2Object.method2<A<int>>() != 4 || ic2Object.method2<S<string>>() != 4
)
{
Console.WriteLine("Failed at TestNonGenInterface_GenType: generic method");
pass = false;
}
}
public static void TestGenInterface_NonGenType()
{
IGen<int> iIntc3 = new C3Int();
IGen<object> iObjectc3 = new C3Object();
IGen<string> iStringc3 = new C3String();
// TEST4: test non generic virtual method
if ( iIntc3.method1() != 5 || iObjectc3.method1() != 5 || iStringc3.method1() != 5 )
{
Console.WriteLine("Failed at TestGenInterface_NonGenType: non generic method");
pass = false;
}
// TEST5: test generic virtual method
if (iIntc3.method2<int>() != 6 || iIntc3.method2<object>() != 6|| iIntc3.method2<string>() != 6
|| iIntc3.method2<A<int>>() != 6 || iIntc3.method2<S<string>>() != 6
|| iObjectc3.method2<int>() != 6 || iObjectc3.method2<object>() != 6|| iObjectc3.method2<string>() != 6
|| iObjectc3.method2<A<int>>() != 6 || iObjectc3.method2<S<string>>() != 6
|| iStringc3.method2<int>() != 6 || iStringc3.method2<object>() != 6|| iStringc3.method2<string>() != 6
|| iStringc3.method2<A<int>>() != 6 || iStringc3.method2<S<string>>() != 6
)
{
Console.WriteLine("Failed at TestGenInterface_NonGenType: generic method");
pass = false;
}
}
public static void TestGenInterface_GenType()
{
IGen<int> iGenC4Int = new C4<int>();
IGen<object> iGenC4Object = new C4<object>();
IGen<string> iGenC4String = new C4<string>();
// TEST6: test non generic virtual method
if ( iGenC4Int.method1() != 7 || iGenC4Object.method1() != 7 || iGenC4String.method1() != 7 )
{
Console.WriteLine("Failed at TestGenInterface_GenType: non generic method");
pass = false;
}
// TEST7: test generic virtual method
if (iGenC4Int.method2<int>() != 8 || iGenC4Int.method2<object>() != 8 || iGenC4Int.method2<string>() != 8
|| iGenC4Int.method2<A<int>>() != 8 || iGenC4Int.method2<S<string>>() != 8
|| iGenC4Object.method2<int>() != 8 || iGenC4Object.method2<object>() != 8 || iGenC4Object.method2<string>() != 8
|| iGenC4Object.method2<A<int>>() != 8 || iGenC4Object.method2<S<string>>() != 8
|| iGenC4String.method2<int>() != 8 || iGenC4String.method2<object>() != 8 || iGenC4String.method2<string>() != 8
|| iGenC4String.method2<A<int>>() != 8 || iGenC4String.method2<S<string>>() != 8
)
{
Console.WriteLine("Failed at TestGenInterface_GenType: generic method");
pass = false;
}
}
public static int Main()
{
TestNonGenInterface_NonGenType();
TestNonGenInterface_GenType();
TestGenInterface_NonGenType();
TestGenInterface_GenType();
if (pass)
{
Console.WriteLine("PASS");
return 100;
}
else
{
Console.WriteLine("FAIL");
return 101;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V9.Services
{
/// <summary>Settings for <see cref="CampaignAudienceViewServiceClient"/> instances.</summary>
public sealed partial class CampaignAudienceViewServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="CampaignAudienceViewServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="CampaignAudienceViewServiceSettings"/>.</returns>
public static CampaignAudienceViewServiceSettings GetDefault() => new CampaignAudienceViewServiceSettings();
/// <summary>
/// Constructs a new <see cref="CampaignAudienceViewServiceSettings"/> object with default settings.
/// </summary>
public CampaignAudienceViewServiceSettings()
{
}
private CampaignAudienceViewServiceSettings(CampaignAudienceViewServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetCampaignAudienceViewSettings = existing.GetCampaignAudienceViewSettings;
OnCopy(existing);
}
partial void OnCopy(CampaignAudienceViewServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>CampaignAudienceViewServiceClient.GetCampaignAudienceView</c> and
/// <c>CampaignAudienceViewServiceClient.GetCampaignAudienceViewAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetCampaignAudienceViewSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="CampaignAudienceViewServiceSettings"/> object.</returns>
public CampaignAudienceViewServiceSettings Clone() => new CampaignAudienceViewServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="CampaignAudienceViewServiceClient"/> to provide simple configuration of
/// credentials, endpoint etc.
/// </summary>
internal sealed partial class CampaignAudienceViewServiceClientBuilder : gaxgrpc::ClientBuilderBase<CampaignAudienceViewServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public CampaignAudienceViewServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public CampaignAudienceViewServiceClientBuilder()
{
UseJwtAccessWithScopes = CampaignAudienceViewServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref CampaignAudienceViewServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CampaignAudienceViewServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override CampaignAudienceViewServiceClient Build()
{
CampaignAudienceViewServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<CampaignAudienceViewServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<CampaignAudienceViewServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private CampaignAudienceViewServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return CampaignAudienceViewServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<CampaignAudienceViewServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return CampaignAudienceViewServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => CampaignAudienceViewServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => CampaignAudienceViewServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => CampaignAudienceViewServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>CampaignAudienceViewService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage campaign audience views.
/// </remarks>
public abstract partial class CampaignAudienceViewServiceClient
{
/// <summary>
/// The default endpoint for the CampaignAudienceViewService service, which is a host of
/// "googleads.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default CampaignAudienceViewService scopes.</summary>
/// <remarks>
/// The default CampaignAudienceViewService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="CampaignAudienceViewServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="CampaignAudienceViewServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="CampaignAudienceViewServiceClient"/>.</returns>
public static stt::Task<CampaignAudienceViewServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new CampaignAudienceViewServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="CampaignAudienceViewServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="CampaignAudienceViewServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="CampaignAudienceViewServiceClient"/>.</returns>
public static CampaignAudienceViewServiceClient Create() => new CampaignAudienceViewServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="CampaignAudienceViewServiceClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="CampaignAudienceViewServiceSettings"/>.</param>
/// <returns>The created <see cref="CampaignAudienceViewServiceClient"/>.</returns>
internal static CampaignAudienceViewServiceClient Create(grpccore::CallInvoker callInvoker, CampaignAudienceViewServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
CampaignAudienceViewService.CampaignAudienceViewServiceClient grpcClient = new CampaignAudienceViewService.CampaignAudienceViewServiceClient(callInvoker);
return new CampaignAudienceViewServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC CampaignAudienceViewService client</summary>
public virtual CampaignAudienceViewService.CampaignAudienceViewServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested campaign audience view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CampaignAudienceView GetCampaignAudienceView(GetCampaignAudienceViewRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested campaign audience view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CampaignAudienceView> GetCampaignAudienceViewAsync(GetCampaignAudienceViewRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested campaign audience view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CampaignAudienceView> GetCampaignAudienceViewAsync(GetCampaignAudienceViewRequest request, st::CancellationToken cancellationToken) =>
GetCampaignAudienceViewAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested campaign audience view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the campaign audience view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CampaignAudienceView GetCampaignAudienceView(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCampaignAudienceView(new GetCampaignAudienceViewRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested campaign audience view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the campaign audience view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CampaignAudienceView> GetCampaignAudienceViewAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCampaignAudienceViewAsync(new GetCampaignAudienceViewRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested campaign audience view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the campaign audience view to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CampaignAudienceView> GetCampaignAudienceViewAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetCampaignAudienceViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested campaign audience view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the campaign audience view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CampaignAudienceView GetCampaignAudienceView(gagvr::CampaignAudienceViewName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCampaignAudienceView(new GetCampaignAudienceViewRequest
{
ResourceNameAsCampaignAudienceViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested campaign audience view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the campaign audience view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CampaignAudienceView> GetCampaignAudienceViewAsync(gagvr::CampaignAudienceViewName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCampaignAudienceViewAsync(new GetCampaignAudienceViewRequest
{
ResourceNameAsCampaignAudienceViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested campaign audience view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the campaign audience view to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CampaignAudienceView> GetCampaignAudienceViewAsync(gagvr::CampaignAudienceViewName resourceName, st::CancellationToken cancellationToken) =>
GetCampaignAudienceViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>CampaignAudienceViewService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage campaign audience views.
/// </remarks>
public sealed partial class CampaignAudienceViewServiceClientImpl : CampaignAudienceViewServiceClient
{
private readonly gaxgrpc::ApiCall<GetCampaignAudienceViewRequest, gagvr::CampaignAudienceView> _callGetCampaignAudienceView;
/// <summary>
/// Constructs a client wrapper for the CampaignAudienceViewService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="CampaignAudienceViewServiceSettings"/> used within this client.
/// </param>
public CampaignAudienceViewServiceClientImpl(CampaignAudienceViewService.CampaignAudienceViewServiceClient grpcClient, CampaignAudienceViewServiceSettings settings)
{
GrpcClient = grpcClient;
CampaignAudienceViewServiceSettings effectiveSettings = settings ?? CampaignAudienceViewServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetCampaignAudienceView = clientHelper.BuildApiCall<GetCampaignAudienceViewRequest, gagvr::CampaignAudienceView>(grpcClient.GetCampaignAudienceViewAsync, grpcClient.GetCampaignAudienceView, effectiveSettings.GetCampaignAudienceViewSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetCampaignAudienceView);
Modify_GetCampaignAudienceViewApiCall(ref _callGetCampaignAudienceView);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetCampaignAudienceViewApiCall(ref gaxgrpc::ApiCall<GetCampaignAudienceViewRequest, gagvr::CampaignAudienceView> call);
partial void OnConstruction(CampaignAudienceViewService.CampaignAudienceViewServiceClient grpcClient, CampaignAudienceViewServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC CampaignAudienceViewService client</summary>
public override CampaignAudienceViewService.CampaignAudienceViewServiceClient GrpcClient { get; }
partial void Modify_GetCampaignAudienceViewRequest(ref GetCampaignAudienceViewRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested campaign audience view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::CampaignAudienceView GetCampaignAudienceView(GetCampaignAudienceViewRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetCampaignAudienceViewRequest(ref request, ref callSettings);
return _callGetCampaignAudienceView.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested campaign audience view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::CampaignAudienceView> GetCampaignAudienceViewAsync(GetCampaignAudienceViewRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetCampaignAudienceViewRequest(ref request, ref callSettings);
return _callGetCampaignAudienceView.Async(request, callSettings);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Xml.Xsl.XsltOld
{
using System;
using System.Globalization;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Collections;
internal class ReaderOutput : XmlReader, RecordOutput
{
private Processor _processor;
private XmlNameTable _nameTable;
// Main node + Fields Collection
private RecordBuilder _builder;
private BuilderInfo _mainNode;
private ArrayList _attributeList;
private int _attributeCount;
private BuilderInfo _attributeValue;
// OutputScopeManager
private OutputScopeManager _manager;
// Current position in the list
private int _currentIndex;
private BuilderInfo _currentInfo;
// Reader state
private ReadState _state = ReadState.Initial;
private bool _haveRecord;
// Static default record
private static BuilderInfo s_DefaultInfo = new BuilderInfo();
private XmlEncoder _encoder = new XmlEncoder();
private XmlCharType _xmlCharType = XmlCharType.Instance;
internal ReaderOutput(Processor processor)
{
Debug.Assert(processor != null);
Debug.Assert(processor.NameTable != null);
_processor = processor;
_nameTable = processor.NameTable;
Reset();
}
// XmlReader abstract methods implementation
public override XmlNodeType NodeType
{
get
{
CheckCurrentInfo();
return _currentInfo.NodeType;
}
}
public override string Name
{
get
{
CheckCurrentInfo();
string prefix = Prefix;
string localName = LocalName;
if (prefix != null && prefix.Length > 0)
{
if (localName.Length > 0)
{
return _nameTable.Add(prefix + ":" + localName);
}
else
{
return prefix;
}
}
else
{
return localName;
}
}
}
public override string LocalName
{
get
{
CheckCurrentInfo();
return _currentInfo.LocalName;
}
}
public override string NamespaceURI
{
get
{
CheckCurrentInfo();
return _currentInfo.NamespaceURI;
}
}
public override string Prefix
{
get
{
CheckCurrentInfo();
return _currentInfo.Prefix;
}
}
public override bool HasValue
{
get
{
return XmlReader.HasValueInternal(NodeType);
}
}
public override string Value
{
get
{
CheckCurrentInfo();
return _currentInfo.Value;
}
}
public override int Depth
{
get
{
CheckCurrentInfo();
return _currentInfo.Depth;
}
}
public override string BaseURI
{
get
{
return string.Empty;
}
}
public override bool IsEmptyElement
{
get
{
CheckCurrentInfo();
return _currentInfo.IsEmptyTag;
}
}
public override char QuoteChar
{
get { return _encoder.QuoteChar; }
}
public override bool IsDefault
{
get { return false; }
}
public override XmlSpace XmlSpace
{
get { return _manager != null ? _manager.XmlSpace : XmlSpace.None; }
}
public override string XmlLang
{
get { return _manager != null ? _manager.XmlLang : string.Empty; }
}
// Attribute Accessors
public override int AttributeCount
{
get { return _attributeCount; }
}
public override string GetAttribute(string name)
{
int ordinal;
if (FindAttribute(name, out ordinal))
{
Debug.Assert(ordinal >= 0);
return ((BuilderInfo)_attributeList[ordinal]).Value;
}
else
{
Debug.Assert(ordinal == -1);
return null;
}
}
public override string GetAttribute(string localName, string namespaceURI)
{
int ordinal;
if (FindAttribute(localName, namespaceURI, out ordinal))
{
Debug.Assert(ordinal >= 0);
return ((BuilderInfo)_attributeList[ordinal]).Value;
}
else
{
Debug.Assert(ordinal == -1);
return null;
}
}
public override string GetAttribute(int i)
{
BuilderInfo attribute = GetBuilderInfo(i);
return attribute.Value;
}
public override string this[int i]
{
get { return GetAttribute(i); }
}
public override string this[string name, string namespaceURI]
{
get { return GetAttribute(name, namespaceURI); }
}
public override bool MoveToAttribute(string name)
{
int ordinal;
if (FindAttribute(name, out ordinal))
{
Debug.Assert(ordinal >= 0);
SetAttribute(ordinal);
return true;
}
else
{
Debug.Assert(ordinal == -1);
return false;
}
}
public override bool MoveToAttribute(string localName, string namespaceURI)
{
int ordinal;
if (FindAttribute(localName, namespaceURI, out ordinal))
{
Debug.Assert(ordinal >= 0);
SetAttribute(ordinal);
return true;
}
else
{
Debug.Assert(ordinal == -1);
return false;
}
}
public override void MoveToAttribute(int i)
{
if (i < 0 || _attributeCount <= i)
{
throw new ArgumentOutOfRangeException(nameof(i));
}
SetAttribute(i);
}
public override bool MoveToFirstAttribute()
{
if (_attributeCount <= 0)
{
Debug.Assert(_attributeCount == 0);
return false;
}
else
{
SetAttribute(0);
return true;
}
}
public override bool MoveToNextAttribute()
{
if (_currentIndex + 1 < _attributeCount)
{
SetAttribute(_currentIndex + 1);
return true;
}
return false;
}
public override bool MoveToElement()
{
if (NodeType == XmlNodeType.Attribute || _currentInfo == _attributeValue)
{
SetMainNode();
return true;
}
return false;
}
// Moving through the Stream
public override bool Read()
{
Debug.Assert(_processor != null || _state == ReadState.Closed);
if (_state != ReadState.Interactive)
{
if (_state == ReadState.Initial)
{
_state = ReadState.Interactive;
}
else
{
return false;
}
}
while (true)
{ // while -- to ignor empty whitespace nodes.
if (_haveRecord)
{
_processor.ResetOutput();
_haveRecord = false;
}
_processor.Execute();
if (_haveRecord)
{
CheckCurrentInfo();
// check text nodes on whitespace;
switch (this.NodeType)
{
case XmlNodeType.Text:
if (_xmlCharType.IsOnlyWhitespace(this.Value))
{
_currentInfo.NodeType = XmlNodeType.Whitespace;
goto case XmlNodeType.Whitespace;
}
Debug.Assert(this.Value.Length != 0, "It whould be Whitespace in this case");
break;
case XmlNodeType.Whitespace:
if (this.Value.Length == 0)
{
continue; // ignoring emty text nodes
}
if (this.XmlSpace == XmlSpace.Preserve)
{
_currentInfo.NodeType = XmlNodeType.SignificantWhitespace;
}
break;
}
}
else
{
Debug.Assert(_processor.ExecutionDone);
_state = ReadState.EndOfFile;
Reset();
}
return _haveRecord;
}
}
public override bool EOF
{
get { return _state == ReadState.EndOfFile; }
}
public override void Close()
{
_processor = null;
_state = ReadState.Closed;
Reset();
}
public override ReadState ReadState
{
get { return _state; }
}
// Whole Content Read Methods
public override string ReadString()
{
string result = string.Empty;
if (NodeType == XmlNodeType.Element || NodeType == XmlNodeType.Attribute || _currentInfo == _attributeValue)
{
if (_mainNode.IsEmptyTag)
{
return result;
}
if (!Read())
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
}
StringBuilder sb = null;
bool first = true;
while (true)
{
switch (NodeType)
{
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
// case XmlNodeType.CharacterEntity:
if (first)
{
result = this.Value;
first = false;
}
else
{
if (sb == null)
{
sb = new StringBuilder(result);
}
sb.Append(this.Value);
}
if (!Read())
throw new InvalidOperationException(SR.Xml_InvalidOperation);
break;
default:
return (sb == null) ? result : sb.ToString();
}
}
}
public override string ReadInnerXml()
{
if (ReadState == ReadState.Interactive)
{
if (NodeType == XmlNodeType.Element && !IsEmptyElement)
{
StringOutput output = new StringOutput(_processor);
output.OmitXmlDecl();
int depth = Depth;
Read(); // skeep begin Element
while (depth < Depth)
{ // process content
Debug.Assert(_builder != null);
output.RecordDone(_builder);
Read();
}
Debug.Assert(NodeType == XmlNodeType.EndElement);
Read(); // skeep end element
output.TheEnd();
return output.Result;
}
else if (NodeType == XmlNodeType.Attribute)
{
return _encoder.AtributeInnerXml(Value);
}
else
{
Read();
}
}
return string.Empty;
}
public override string ReadOuterXml()
{
if (ReadState == ReadState.Interactive)
{
if (NodeType == XmlNodeType.Element)
{
StringOutput output = new StringOutput(_processor);
output.OmitXmlDecl();
bool emptyElement = IsEmptyElement;
int depth = Depth;
// process current record
output.RecordDone(_builder);
Read();
// process internal elements & text nodes
while (depth < Depth)
{
Debug.Assert(_builder != null);
output.RecordDone(_builder);
Read();
}
// process end element
if (!emptyElement)
{
output.RecordDone(_builder);
Read();
}
output.TheEnd();
return output.Result;
}
else if (NodeType == XmlNodeType.Attribute)
{
return _encoder.AtributeOuterXml(Name, Value);
}
else
{
Read();
}
}
return string.Empty;
}
//
// Nametable and Namespace Helpers
//
public override XmlNameTable NameTable
{
get
{
Debug.Assert(_nameTable != null);
return _nameTable;
}
}
public override string LookupNamespace(string prefix)
{
prefix = _nameTable.Get(prefix);
if (_manager != null && prefix != null)
{
return _manager.ResolveNamespace(prefix);
}
return null;
}
public override void ResolveEntity()
{
Debug.Assert(NodeType != XmlNodeType.EntityReference);
if (NodeType != XmlNodeType.EntityReference)
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
}
public override bool ReadAttributeValue()
{
if (ReadState != ReadState.Interactive || NodeType != XmlNodeType.Attribute)
{
return false;
}
if (_attributeValue == null)
{
_attributeValue = new BuilderInfo();
_attributeValue.NodeType = XmlNodeType.Text;
}
if (_currentInfo == _attributeValue)
{
return false;
}
_attributeValue.Value = _currentInfo.Value;
_attributeValue.Depth = _currentInfo.Depth + 1;
_currentInfo = _attributeValue;
return true;
}
//
// RecordOutput interface method implementation
//
public Processor.OutputResult RecordDone(RecordBuilder record)
{
_builder = record;
_mainNode = record.MainNode;
_attributeList = record.AttributeList;
_attributeCount = record.AttributeCount;
_manager = record.Manager;
_haveRecord = true;
SetMainNode();
return Processor.OutputResult.Interrupt;
}
public void TheEnd()
{
// nothing here, was taken care of by RecordBuilder
}
//
// Implementation internals
//
private void SetMainNode()
{
_currentIndex = -1;
_currentInfo = _mainNode;
}
private void SetAttribute(int attrib)
{
Debug.Assert(0 <= attrib && attrib < _attributeCount);
Debug.Assert(0 <= attrib && attrib < _attributeList.Count);
Debug.Assert(_attributeList[attrib] is BuilderInfo);
_currentIndex = attrib;
_currentInfo = (BuilderInfo)_attributeList[attrib];
}
private BuilderInfo GetBuilderInfo(int attrib)
{
if (attrib < 0 || _attributeCount <= attrib)
{
throw new ArgumentOutOfRangeException(nameof(attrib));
}
Debug.Assert(_attributeList[attrib] is BuilderInfo);
return (BuilderInfo)_attributeList[attrib];
}
private bool FindAttribute(String localName, String namespaceURI, out int attrIndex)
{
if (namespaceURI == null)
{
namespaceURI = string.Empty;
}
if (localName == null)
{
localName = string.Empty;
}
for (int index = 0; index < _attributeCount; index++)
{
Debug.Assert(_attributeList[index] is BuilderInfo);
BuilderInfo attribute = (BuilderInfo)_attributeList[index];
if (attribute.NamespaceURI == namespaceURI && attribute.LocalName == localName)
{
attrIndex = index;
return true;
}
}
attrIndex = -1;
return false;
}
private bool FindAttribute(String name, out int attrIndex)
{
if (name == null)
{
name = string.Empty;
}
for (int index = 0; index < _attributeCount; index++)
{
Debug.Assert(_attributeList[index] is BuilderInfo);
BuilderInfo attribute = (BuilderInfo)_attributeList[index];
if (attribute.Name == name)
{
attrIndex = index;
return true;
}
}
attrIndex = -1;
return false;
}
private void Reset()
{
_currentIndex = -1;
_currentInfo = s_DefaultInfo;
_mainNode = s_DefaultInfo;
_manager = null;
}
[System.Diagnostics.Conditional("DEBUG")]
private void CheckCurrentInfo()
{
Debug.Assert(_currentInfo != null);
Debug.Assert(_attributeCount == 0 || _attributeList != null);
Debug.Assert((_currentIndex == -1) == (_currentInfo == _mainNode));
Debug.Assert((_currentIndex == -1) || (_currentInfo == _attributeValue || _attributeList[_currentIndex] is BuilderInfo && _attributeList[_currentIndex] == _currentInfo));
}
private class XmlEncoder
{
private StringBuilder _buffer = null;
private XmlTextEncoder _encoder = null;
private void Init()
{
_buffer = new StringBuilder();
_encoder = new XmlTextEncoder(new StringWriter(_buffer, CultureInfo.InvariantCulture));
}
public string AtributeInnerXml(string value)
{
if (_encoder == null) Init();
_buffer.Length = 0; // clean buffer
_encoder.StartAttribute(/*save:*/false);
_encoder.Write(value);
_encoder.EndAttribute();
return _buffer.ToString();
}
public string AtributeOuterXml(string name, string value)
{
if (_encoder == null) Init();
_buffer.Length = 0; // clean buffer
_buffer.Append(name);
_buffer.Append('=');
_buffer.Append(QuoteChar);
_encoder.StartAttribute(/*save:*/false);
_encoder.Write(value);
_encoder.EndAttribute();
_buffer.Append(QuoteChar);
return _buffer.ToString();
}
public char QuoteChar
{
get { return '"'; }
}
}
}
}
| |
using MonoTouch.UIKit;
using System.Drawing;
using System;
using MonoTouch.Foundation;
using Mono.Data.Sqlite;
using System.IO;
namespace MonoTouchData_Hal
{
class CreateSQLiteAppViewController
{
}
public partial class SQLiteX : UIViewController
{
public SQLiteX() : base("SQLiteX", null)
{
}
public override void DidReceiveMemoryWarning()
{
// Releases the view if it doesn't have a superview.
base.DidReceiveMemoryWarning();
// Release any cached data, images, etc that aren't in use.
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
string SQLitePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "MyDB.db3");
olusturX.TouchUpInside+= delegate
{
CreateSQLiteDatabase(SQLitePath);
};
yazdirX.TouchUpInside+= delegate
{
InsertData(SQLitePath);
};
guncelleX.TouchUpInside+= delegate
{
UpdateData(SQLitePath);
};
listeleX.TouchUpInside+= delegate
{
SelectData(SQLitePath);
};
}
private void CreateSQLiteDatabase (string databaseFile)
{
try
{
// Check if database already exists
if (!File.Exists (databaseFile))
{
// Create the database
SqliteConnection.CreateFile (databaseFile);
// Connect to the database
using (SqliteConnection sqlCon = new SqliteConnection (String.Format ("Data Source = {0};", databaseFile)))
{
sqlCon.Open ();
// Create a table
using (SqliteCommand sqlCom = new SqliteCommand (sqlCon))
{
sqlCom.CommandText = "CREATE TABLE Customers (ID INTEGER PRIMARY KEY, FirstName VARCHAR(20), LastName VARCHAR(20))";
//veri Ekleme
//Update
// sqlCom.CommandText = "UPDATE Customers SET FirstName= 'Haluk' WHERE LastName = @lastName";
// sqlCom.Parameters.Add(new SqliteParameter("@lastName","Haluky"));
sqlCom.ExecuteNonQuery ();
Console.WriteLine(sqlCom.ExecuteNonQuery());
}
//end using sqlCom
sqlCon.Close ();
}
//end using sqlCon
this.bilgiX.Text = "Database created!";
} else
{
this.bilgiX.Text = "Database already exists!";
}//end if else
} catch (Exception ex)
{
this.bilgiX.Text = String.Format ("Sqlite error: {0}", ex.Message);
}//end try catch
}//end void CreateSQLiteDatabase
private void deleteSqLite (string databaseFile)
{
try
{
// Check if database already exists
if (!File.Exists (databaseFile))
{
// Create the database
SqliteConnection.CreateFile (databaseFile);
// Connect to the database
using (SqliteConnection sqlCon = new SqliteConnection (String.Format ("Data Source = {0};", databaseFile)))
{
sqlCon.Open ();
// Create a table
using (SqliteCommand sqlCom = new SqliteCommand (sqlCon))
{
sqlCom.CommandText = "CREATE TABLE Customers (ID INTEGER PRIMARY KEY, FirstName VARCHAR(20), LastName VARCHAR(20))";
//veri Ekleme
//Update
// sqlCom.CommandText = "UPDATE Customers SET FirstName= 'Haluk' WHERE LastName = @lastName";
// sqlCom.Parameters.Add(new SqliteParameter("@lastName","Haluky"));
sqlCom.ExecuteNonQuery ();
Console.WriteLine(sqlCom.ExecuteNonQuery());
}
//end using sqlCom
sqlCon.Close ();
}
//end using sqlCon
this.bilgiX.Text = "Database created!";
} else
{
this.bilgiX.Text = "Database already exists!";
}//end if else
} catch (Exception ex)
{
this.bilgiX.Text = String.Format ("Sqlite error: {0}", ex.Message);
}//end try catch
}//end void CreateSQLiteDatabase
private void InsertData (string databaseFile)
{
try
{
if (!File.Exists (databaseFile))
{
this.bilgiX.Text = "Database file does not exist. Tap the appropriate button to create it.";
return;
}
//end if
// Connect to database
using (SqliteConnection sqlCon = new SqliteConnection (String.Format ("Data Source = {0}", databaseFile)))
{
sqlCon.Open ();
using (SqliteCommand sqlCom = new SqliteCommand (sqlCon))
{
sqlCom.CommandText = "INSERT INTO Customers (FirstName, LastName) VALUES (@firstName, @lastName)";
sqlCom.Parameters.Add (new SqliteParameter ("@firstName", "Haluk"));
sqlCom.Parameters.Add (new SqliteParameter ("@lastName", "YILMAZ"));
sqlCom.ExecuteNonQuery ();
}
//end using sqlCom
sqlCon.Close ();
}
//end using sqlCon
this.bilgiX.Text = "Customer data inserted.";
} catch (Exception ex)
{
this.bilgiX.Text = String.Format ("Sqlite error: {0}", ex.Message);
}//end try catch
}//end void InsertData
private void UpdateData (string databaseFile)
{
try
{
if (!File.Exists (databaseFile))
{
this.bilgiX.Text = "Database file does not exist. Tap the appropriate button to create it.";
return;
}
//end if
// Connect to database
using (SqliteConnection sqlCon = new SqliteConnection (String.Format ("Data Source = {0}", databaseFile)))
{
sqlCon.Open ();
using (SqliteCommand sqlCom = new SqliteCommand (sqlCon))
{
sqlCom.CommandText = "UPDATE Customers SET FirstName = 'Haluk' WHERE LastName = @lastName";
sqlCom.Parameters.Add (new SqliteParameter ("@lastName", "Smith"));
sqlCom.ExecuteNonQuery ();
}
//end using sqlCom
sqlCon.Close ();
}
//end using sqlCon
this.bilgiX.Text = "Customer data updated.";
} catch (Exception ex)
{
this.bilgiX.Text = String.Format ("Sqlite error: {0}", ex.Message);
}
//end try catch
}//end void UpdateData
public void SelectData (string databaseFile)
{
try
{
if (!File.Exists (databaseFile))
{
this.bilgiX.Text = "Database file does not exist. Tap the appropriate button to create it.";
return;
}
//end if
// Connect to database
using (SqliteConnection sqlCon = new SqliteConnection (String.Format ("Data Source = {0}", databaseFile)))
{
sqlCon.Open ();
using (SqliteCommand sqlCom = new SqliteCommand (sqlCon))
{
sqlCom.CommandText = "SELECT * FROM Customers WHERE LastName = @lastName";
sqlCom.Parameters.Add (new SqliteParameter ("@lastName", "YILMAZ"));
// Execute the SELECT statement and retrieve the data
using (SqliteDataReader dbReader = sqlCom.ExecuteReader ())
{
if (dbReader.HasRows)
{
// Advance through each row
while (dbReader.Read ())
{
this.birinciX.Text += String.Format ("ID: {0}\n", Convert.ToString (dbReader["ID"]));
this.birinciX.Text += String.Format ("First name: {0}\n", Convert.ToString (dbReader["FirstName"]));
this.ikinciX.Text += String.Format ("Last name: {0}\n", Convert.ToString (dbReader["LastName"]));
}
//end while
}
//end if
}//end using dbReader
}
//end using sqlCom
sqlCon.Close ();
}
//end using sqlCon
this.bilgiX.Text += "Customer data retrieved.\n";
} catch (Exception ex)
{
this.bilgiX.Text = String.Format ("Sqlite error: {0}", ex.Message);
}
//end try catch
}//end void SelectData
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mime;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Dictionary;
using Umbraco.Cms.Core.Editors;
using Umbraco.Cms.Core.Hosting;
using Umbraco.Cms.Core.Mapping;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.ContentEditing;
using Umbraco.Cms.Core.PropertyEditors;
using Umbraco.Cms.Core.Security;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Strings;
using Umbraco.Cms.Infrastructure.Packaging;
using Umbraco.Cms.Web.Common.ActionsResults;
using Umbraco.Cms.Web.Common.Attributes;
using Umbraco.Cms.Web.Common.Authorization;
using Umbraco.Extensions;
using Constants = Umbraco.Cms.Core.Constants;
using ContentType = Umbraco.Cms.Core.Models.ContentType;
namespace Umbraco.Cms.Web.BackOffice.Controllers
{
/// <summary>
/// An API controller used for dealing with content types
/// </summary>
[PluginController(Constants.Web.Mvc.BackOfficeApiArea)]
[ParameterSwapControllerActionSelector(nameof(GetById), "id", typeof(int), typeof(Guid), typeof(Udi))]
public class ContentTypeController : ContentTypeControllerBase<IContentType>
{
// TODO: Split this controller apart so that authz is consistent, currently we need to authz each action individually.
// It would be possible to have something like a ContentTypeInfoController for the GetAllPropertyTypeAliases/GetCount/GetAllowedChildren/etc... actions
private readonly IEntityXmlSerializer _serializer;
private readonly PropertyEditorCollection _propertyEditors;
private readonly IContentTypeService _contentTypeService;
private readonly IUmbracoMapper _umbracoMapper;
private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor;
private readonly IDataTypeService _dataTypeService;
private readonly IShortStringHelper _shortStringHelper;
private readonly ILocalizedTextService _localizedTextService;
private readonly IFileService _fileService;
private readonly ILogger<ContentTypeController> _logger;
private readonly IContentService _contentService;
private readonly IContentTypeBaseServiceProvider _contentTypeBaseServiceProvider;
private readonly IHostingEnvironment _hostingEnvironment;
private readonly PackageDataInstallation _packageDataInstallation;
public ContentTypeController(
ICultureDictionary cultureDictionary,
IContentTypeService contentTypeService,
IMediaTypeService mediaTypeService,
IMemberTypeService memberTypeService,
IUmbracoMapper umbracoMapper,
ILocalizedTextService localizedTextService,
IEntityXmlSerializer serializer,
PropertyEditorCollection propertyEditors,
IBackOfficeSecurityAccessor backofficeSecurityAccessor,
IDataTypeService dataTypeService,
IShortStringHelper shortStringHelper,
IFileService fileService,
ILogger<ContentTypeController> logger,
IContentService contentService,
IContentTypeBaseServiceProvider contentTypeBaseServiceProvider,
IHostingEnvironment hostingEnvironment,
EditorValidatorCollection editorValidatorCollection,
PackageDataInstallation packageDataInstallation)
: base(cultureDictionary,
editorValidatorCollection,
contentTypeService,
mediaTypeService,
memberTypeService,
umbracoMapper,
localizedTextService)
{
_serializer = serializer;
_propertyEditors = propertyEditors;
_contentTypeService = contentTypeService;
_umbracoMapper = umbracoMapper;
_backofficeSecurityAccessor = backofficeSecurityAccessor;
_dataTypeService = dataTypeService;
_shortStringHelper = shortStringHelper;
_localizedTextService = localizedTextService;
_fileService = fileService;
_logger = logger;
_contentService = contentService;
_contentTypeBaseServiceProvider = contentTypeBaseServiceProvider;
_hostingEnvironment = hostingEnvironment;
_packageDataInstallation = packageDataInstallation;
}
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public int GetCount()
{
return _contentTypeService.Count();
}
[HttpGet]
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public bool HasContentNodes(int id)
{
return _contentTypeService.HasContentNodes(id);
}
/// <summary>
/// Gets the document type a given id
/// </summary>
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public ActionResult<DocumentTypeDisplay> GetById(int id)
{
var ct = _contentTypeService.Get(id);
if (ct == null)
{
return NotFound();
}
var dto = _umbracoMapper.Map<IContentType, DocumentTypeDisplay>(ct);
return dto;
}
/// <summary>
/// Gets the document type a given guid
/// </summary>
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public ActionResult<DocumentTypeDisplay> GetById(Guid id)
{
var contentType = _contentTypeService.Get(id);
if (contentType == null)
{
return NotFound();
}
var dto = _umbracoMapper.Map<IContentType, DocumentTypeDisplay>(contentType);
return dto;
}
/// <summary>
/// Gets the document type a given udi
/// </summary>
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public ActionResult<DocumentTypeDisplay> GetById(Udi id)
{
var guidUdi = id as GuidUdi;
if (guidUdi == null)
return NotFound();
var contentType = _contentTypeService.Get(guidUdi.Guid);
if (contentType == null)
{
return NotFound();
}
var dto = _umbracoMapper.Map<IContentType, DocumentTypeDisplay>(contentType);
return dto;
}
/// <summary>
/// Deletes a document type with a given ID
/// </summary>
[HttpDelete]
[HttpPost]
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public IActionResult DeleteById(int id)
{
var foundType = _contentTypeService.Get(id);
if (foundType == null)
{
return NotFound();
}
_contentTypeService.Delete(foundType, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id);
return Ok();
}
/// <summary>
/// Gets all user defined properties.
/// </summary>
[Authorize(Policy = AuthorizationPolicies.TreeAccessAnyContentOrTypes)]
public IEnumerable<string> GetAllPropertyTypeAliases()
{
return _contentTypeService.GetAllPropertyTypeAliases();
}
/// <summary>
/// Gets all the standard fields.
/// </summary>
[Authorize(Policy = AuthorizationPolicies.TreeAccessAnyContentOrTypes)]
public IEnumerable<string> GetAllStandardFields()
{
string[] preValuesSource = { "createDate", "creatorName", "level", "nodeType", "nodeTypeAlias", "pageID", "pageName", "parentID", "path", "template", "updateDate", "writerID", "writerName" };
return preValuesSource;
}
/// <summary>
/// Returns the available compositions for this content type
/// This has been wrapped in a dto instead of simple parameters to support having multiple parameters in post request body
/// </summary>
[HttpPost]
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public ActionResult GetAvailableCompositeContentTypes(GetAvailableCompositionsFilter filter)
{
var actionResult = PerformGetAvailableCompositeContentTypes(filter.ContentTypeId,
UmbracoObjectTypes.DocumentType, filter.FilterContentTypes, filter.FilterPropertyTypes,
filter.IsElement);
if (!(actionResult.Result is null))
{
return actionResult.Result;
}
var result = actionResult.Value
.Select(x => new
{
contentType = x.Item1,
allowed = x.Item2
});
return Ok(result);
}
/// <summary>
/// Returns true if any content types have culture variation enabled
/// </summary>
[HttpGet]
[Authorize(Policy = AuthorizationPolicies.BackOfficeAccess)]
public bool AllowsCultureVariation()
{
IEnumerable<IContentType> contentTypes = _contentTypeService.GetAll();
return contentTypes.Any(contentType => contentType.VariesByCulture());
}
/// <summary>
/// Returns where a particular composition has been used
/// This has been wrapped in a dto instead of simple parameters to support having multiple parameters in post request body
/// </summary>
[HttpPost]
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public IActionResult GetWhereCompositionIsUsedInContentTypes(GetAvailableCompositionsFilter filter)
{
var result = PerformGetWhereCompositionIsUsedInContentTypes(filter.ContentTypeId, UmbracoObjectTypes.DocumentType).Value
.Select(x => new
{
contentType = x
});
return Ok(result);
}
[Authorize(Policy = AuthorizationPolicies.TreeAccessAnyContentOrTypes)]
public ActionResult<ContentPropertyDisplay> GetPropertyTypeScaffold(int id)
{
var dataTypeDiff = _dataTypeService.GetDataType(id);
if (dataTypeDiff == null)
{
return NotFound();
}
var configuration = _dataTypeService.GetDataType(id).Configuration;
var editor = _propertyEditors[dataTypeDiff.EditorAlias];
return new ContentPropertyDisplay()
{
Editor = dataTypeDiff.EditorAlias,
Validation = new PropertyTypeValidation(),
View = editor.GetValueEditor().View,
Config = editor.GetConfigurationEditor().ToConfigurationEditor(configuration)
};
}
/// <summary>
/// Deletes a document type container with a given ID
/// </summary>
[HttpDelete]
[HttpPost]
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public IActionResult DeleteContainer(int id)
{
_contentTypeService.DeleteContainer(id, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id);
return Ok();
}
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public IActionResult PostCreateContainer(int parentId, string name)
{
var result = _contentTypeService.CreateContainer(parentId, Guid.NewGuid(), name, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id);
if (result.Success)
return Ok(result.Result); //return the id
else
return ValidationProblem(result.Exception.Message);
}
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public IActionResult PostRenameContainer(int id, string name)
{
var result = _contentTypeService.RenameContainer(id, name, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id);
if (result.Success)
return Ok(result.Result); //return the id
else
return ValidationProblem(result.Exception.Message);
}
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public ActionResult<DocumentTypeDisplay> PostSave(DocumentTypeSave contentTypeSave)
{
//Before we send this model into this saving/mapping pipeline, we need to do some cleanup on variations.
//If the doc type does not allow content variations, we need to update all of it's property types to not allow this either
//else we may end up with ysods. I'm unsure if the service level handles this but we'll make sure it is updated here
if (!contentTypeSave.AllowCultureVariant)
{
foreach(var prop in contentTypeSave.Groups.SelectMany(x => x.Properties))
{
prop.AllowCultureVariant = false;
}
}
var savedCt = PerformPostSave<DocumentTypeDisplay, DocumentTypeSave, PropertyTypeBasic>(
contentTypeSave: contentTypeSave,
getContentType: i => _contentTypeService.Get(i),
saveContentType: type => _contentTypeService.Save(type),
beforeCreateNew: ctSave =>
{
//create a default template if it doesn't exist -but only if default template is == to the content type
if (ctSave.DefaultTemplate.IsNullOrWhiteSpace() == false && ctSave.DefaultTemplate == ctSave.Alias)
{
var template = CreateTemplateForContentType(ctSave.Alias, ctSave.Name);
// If the alias has been manually updated before the first save,
// make sure to also update the first allowed template, as the
// name will come back as a SafeAlias of the document type name,
// not as the actual document type alias.
// For more info: http://issues.umbraco.org/issue/U4-11059
if (ctSave.DefaultTemplate != template.Alias)
{
var allowedTemplates = ctSave.AllowedTemplates.ToArray();
if (allowedTemplates.Any())
allowedTemplates[0] = template.Alias;
ctSave.AllowedTemplates = allowedTemplates;
}
//make sure the template alias is set on the default and allowed template so we can map it back
ctSave.DefaultTemplate = template.Alias;
}
});
if (!(savedCt.Result is null))
{
return savedCt.Result;
}
var display = _umbracoMapper.Map<DocumentTypeDisplay>(savedCt.Value);
display.AddSuccessNotification(
_localizedTextService.Localize("speechBubbles","contentTypeSavedHeader"),
string.Empty);
return display;
}
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public ActionResult<TemplateDisplay> PostCreateDefaultTemplate(int id)
{
var contentType = _contentTypeService.Get(id);
if (contentType == null)
{
return NotFound("No content type found with id " + id);
}
var template = CreateTemplateForContentType(contentType.Alias, contentType.Name);
if (template == null)
{
throw new InvalidOperationException("Could not create default template for content type with id " + id);
}
return _umbracoMapper.Map<TemplateDisplay>(template);
}
private ITemplate CreateTemplateForContentType(string contentTypeAlias, string contentTypeName)
{
var template = _fileService.GetTemplate(contentTypeAlias);
if (template == null)
{
var tryCreateTemplate = _fileService.CreateTemplateForContentType(contentTypeAlias, contentTypeName);
if (tryCreateTemplate == false)
{
_logger.LogWarning("Could not create a template for Content Type: \"{ContentTypeAlias}\", status: {Status}",
contentTypeAlias, tryCreateTemplate.Result.Result);
}
template = tryCreateTemplate.Result.Entity;
}
return template;
}
/// <summary>
/// Returns an empty content type for use as a scaffold when creating a new type
/// </summary>
/// <param name="parentId"></param>
/// <returns></returns>
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public DocumentTypeDisplay GetEmpty(int parentId)
{
IContentType ct;
if (parentId != Constants.System.Root)
{
var parent = _contentTypeService.Get(parentId);
ct = parent != null ? new ContentType(_shortStringHelper, parent, string.Empty) : new ContentType(_shortStringHelper, parentId);
}
else
ct = new ContentType(_shortStringHelper, parentId);
ct.Icon = Constants.Icons.Content;
var dto = _umbracoMapper.Map<IContentType, DocumentTypeDisplay>(ct);
return dto;
}
/// <summary>
/// Returns all content type objects
/// </summary>
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public IEnumerable<ContentTypeBasic> GetAll()
{
var types = _contentTypeService.GetAll();
var basics = types.Select(_umbracoMapper.Map<IContentType, ContentTypeBasic>);
return basics.Select(basic =>
{
basic.Name = TranslateItem(basic.Name);
basic.Description = TranslateItem(basic.Description);
return basic;
});
}
/// <summary>
/// Returns the allowed child content type objects for the content item id passed in
/// </summary>
/// <param name="contentId"></param>
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentsOrDocumentTypes)]
public IEnumerable<ContentTypeBasic> GetAllowedChildren(int contentId)
{
if (contentId == Constants.System.RecycleBinContent)
return Enumerable.Empty<ContentTypeBasic>();
IEnumerable<IContentType> types;
if (contentId == Constants.System.Root)
{
types = _contentTypeService.GetAll().Where(x => x.AllowedAsRoot).ToList();
}
else
{
var contentItem = _contentService.GetById(contentId);
if (contentItem == null)
{
return Enumerable.Empty<ContentTypeBasic>();
}
var contentType = _contentTypeBaseServiceProvider.GetContentTypeOf(contentItem);
var ids = contentType.AllowedContentTypes.OrderBy(c => c.SortOrder).Select(x => x.Id.Value).ToArray();
if (ids.Any() == false) return Enumerable.Empty<ContentTypeBasic>();
types = _contentTypeService.GetAll(ids).OrderBy(c => ids.IndexOf(c.Id)).ToList();
}
var basics = types.Where(type => type.IsElement == false).Select(_umbracoMapper.Map<IContentType, ContentTypeBasic>).ToList();
var localizedTextService = _localizedTextService;
foreach (var basic in basics)
{
basic.Name = localizedTextService.UmbracoDictionaryTranslate(CultureDictionary, basic.Name);
basic.Description = localizedTextService.UmbracoDictionaryTranslate(CultureDictionary, basic.Description);
}
//map the blueprints
var blueprints = _contentService.GetBlueprintsForContentTypes(types.Select(x => x.Id).ToArray()).ToArray();
foreach (var basic in basics)
{
var docTypeBluePrints = blueprints.Where(x => x.ContentTypeId == (int) basic.Id).ToArray();
foreach (var blueprint in docTypeBluePrints)
{
basic.Blueprints[blueprint.Id] = blueprint.Name;
}
}
return basics.OrderBy(c => contentId == Constants.System.Root ? c.Name : string.Empty);
}
/// <summary>
/// Move the content type
/// </summary>
/// <param name="move"></param>
/// <returns></returns>
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public IActionResult PostMove(MoveOrCopy move)
{
return PerformMove(
move,
getContentType: i => _contentTypeService.Get(i),
doMove: (type, i) => _contentTypeService.Move(type, i));
}
/// <summary>
/// Copy the content type
/// </summary>
/// <param name="copy"></param>
/// <returns></returns>
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public IActionResult PostCopy(MoveOrCopy copy)
{
return PerformCopy(
copy,
getContentType: i => _contentTypeService.Get(i),
doCopy: (type, i) => _contentTypeService.Copy(type, i));
}
[HttpGet]
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public IActionResult Export(int id)
{
var contentType = _contentTypeService.Get(id);
if (contentType == null) throw new NullReferenceException("No content type found with id " + id);
var xml = _serializer.Serialize(contentType);
var fileName = $"{contentType.Alias}.udt";
// Set custom header so umbRequestHelper.downloadFile can save the correct filename
HttpContext.Response.Headers.Add("x-filename", fileName);
return File( Encoding.UTF8.GetBytes(xml.ToDataString()), MediaTypeNames.Application.Octet, fileName);
}
[HttpPost]
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public IActionResult Import(string file)
{
var filePath = Path.Combine(_hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.Data), file);
if (string.IsNullOrEmpty(file) || !System.IO.File.Exists(filePath))
{
return NotFound();
}
var xd = new XmlDocument {XmlResolver = null};
xd.Load(filePath);
var userId = _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0);
var element = XElement.Parse(xd.InnerXml);
_packageDataInstallation.ImportDocumentType(element, userId);
// Try to clean up the temporary file.
try
{
System.IO.File.Delete(filePath);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error cleaning up temporary udt file in {File}", filePath);
}
return Ok();
}
[HttpPost]
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public ActionResult<ContentTypeImportModel> Upload(List<IFormFile> file)
{
var model = new ContentTypeImportModel();
foreach (var formFile in file)
{
var fileName = formFile.FileName.Trim(Constants.CharArrays.DoubleQuote);
var ext = fileName.Substring(fileName.LastIndexOf('.') + 1).ToLower();
var root = _hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.TempFileUploads);
var tempPath = Path.Combine(root,fileName);
if (Path.GetFullPath(tempPath).StartsWith(Path.GetFullPath(root)))
{
using (var stream = System.IO.File.Create(tempPath))
{
formFile.CopyToAsync(stream).GetAwaiter().GetResult();
}
if (ext.InvariantEquals("udt"))
{
model.TempFileName = Path.Combine(root, fileName);
var xd = new XmlDocument
{
XmlResolver = null
};
xd.Load(model.TempFileName);
model.Alias = xd.DocumentElement?.SelectSingleNode("//DocumentType/Info/Alias")?.FirstChild.Value;
model.Name = xd.DocumentElement?.SelectSingleNode("//DocumentType/Info/Name")?.FirstChild.Value;
}
else
{
model.Notifications.Add(new BackOfficeNotification(
_localizedTextService.Localize("speechBubbles","operationFailedHeader"),
_localizedTextService.Localize("media","disallowedFileType"),
NotificationStyle.Warning));
}
}
else
{
model.Notifications.Add(new BackOfficeNotification(
_localizedTextService.Localize("speechBubbles", "operationFailedHeader"),
_localizedTextService.Localize("media", "invalidFileName"),
NotificationStyle.Warning));
}
}
return model;
}
}
}
| |
// ****************************************************************
// Copyright 2009, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************
using System;
using System.Collections;
using NUnit.Framework.Constraints;
namespace NUnit.Framework
{
/// <summary>
/// Helper class with properties and methods that supply
/// a number of constraints used in Asserts.
/// </summary>
public class Is
{
#region Not
/// <summary>
/// Returns a ConstraintExpression that negates any
/// following constraint.
/// </summary>
public static ConstraintExpression Not
{
get { return new ConstraintExpression().Not; }
}
#endregion
#region All
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding if all of them succeed.
/// </summary>
public static ConstraintExpression All
{
get { return new ConstraintExpression().All; }
}
#endregion
#region Null
/// <summary>
/// Returns a constraint that tests for null
/// </summary>
public static NullConstraint Null
{
get { return new NullConstraint(); }
}
#endregion
#region True
/// <summary>
/// Returns a constraint that tests for True
/// </summary>
public static TrueConstraint True
{
get { return new TrueConstraint(); }
}
#endregion
#region False
/// <summary>
/// Returns a constraint that tests for False
/// </summary>
public static FalseConstraint False
{
get { return new FalseConstraint(); }
}
#endregion
#region Positive
/// <summary>
/// Returns a constraint that tests for a positive value
/// </summary>
public static GreaterThanConstraint Positive
{
get { return new GreaterThanConstraint(0); }
}
#endregion
#region Negative
/// <summary>
/// Returns a constraint that tests for a negative value
/// </summary>
public static LessThanConstraint Negative
{
get { return new LessThanConstraint(0); }
}
#endregion
#region NaN
/// <summary>
/// Returns a constraint that tests for NaN
/// </summary>
public static NaNConstraint NaN
{
get { return new NaNConstraint(); }
}
#endregion
#region Empty
/// <summary>
/// Returns a constraint that tests for empty
/// </summary>
public static EmptyConstraint Empty
{
get { return new EmptyConstraint(); }
}
#endregion
#region Unique
/// <summary>
/// Returns a constraint that tests whether a collection
/// contains all unique items.
/// </summary>
public static UniqueItemsConstraint Unique
{
get { return new UniqueItemsConstraint(); }
}
#endregion
#region BinarySerializable
/// <summary>
/// Returns a constraint that tests whether an object graph is serializable in binary format.
/// </summary>
public static BinarySerializableConstraint BinarySerializable
{
get { return new BinarySerializableConstraint(); }
}
#endregion
#region XmlSerializable
/// <summary>
/// Returns a constraint that tests whether an object graph is serializable in xml format.
/// </summary>
public static XmlSerializableConstraint XmlSerializable
{
get { return new XmlSerializableConstraint(); }
}
#endregion
#region EqualTo
/// <summary>
/// Returns a constraint that tests two items for equality
/// </summary>
public static EqualConstraint EqualTo(object expected)
{
return new EqualConstraint(expected);
}
#endregion
#region SameAs
/// <summary>
/// Returns a constraint that tests that two references are the same object
/// </summary>
public static SameAsConstraint SameAs(object expected)
{
return new SameAsConstraint(expected);
}
#endregion
#region GreaterThan
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than the suppled argument
/// </summary>
public static GreaterThanConstraint GreaterThan(object expected)
{
return new GreaterThanConstraint(expected);
}
#endregion
#region GreaterThanOrEqualTo
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than or equal to the suppled argument
/// </summary>
public static GreaterThanOrEqualConstraint GreaterThanOrEqualTo(object expected)
{
return new GreaterThanOrEqualConstraint(expected);
}
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than or equal to the suppled argument
/// </summary>
public static GreaterThanOrEqualConstraint AtLeast(object expected)
{
return new GreaterThanOrEqualConstraint(expected);
}
#endregion
#region LessThan
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than the suppled argument
/// </summary>
public static LessThanConstraint LessThan(object expected)
{
return new LessThanConstraint(expected);
}
#endregion
#region LessThanOrEqualTo
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than or equal to the suppled argument
/// </summary>
public static LessThanOrEqualConstraint LessThanOrEqualTo(object expected)
{
return new LessThanOrEqualConstraint(expected);
}
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than or equal to the suppled argument
/// </summary>
public static LessThanOrEqualConstraint AtMost(object expected)
{
return new LessThanOrEqualConstraint(expected);
}
#endregion
#region TypeOf
/// <summary>
/// Returns a constraint that tests whether the actual
/// value is of the exact type supplied as an argument.
/// </summary>
public static ExactTypeConstraint TypeOf(Type expectedType)
{
return new ExactTypeConstraint(expectedType);
}
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Returns a constraint that tests whether the actual
/// value is of the exact type supplied as an argument.
/// </summary>
public static ExactTypeConstraint TypeOf<T>()
{
return new ExactTypeConstraint(typeof(T));
}
#endif
#endregion
#region InstanceOf
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
public static InstanceOfTypeConstraint InstanceOf(Type expectedType)
{
return new InstanceOfTypeConstraint(expectedType);
}
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
public static InstanceOfTypeConstraint InstanceOf<T>()
{
return new InstanceOfTypeConstraint(typeof(T));
}
#endif
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
[Obsolete("Use InstanceOf(expectedType)")]
public static InstanceOfTypeConstraint InstanceOfType(Type expectedType)
{
return new InstanceOfTypeConstraint(expectedType);
}
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
[Obsolete("Use InstanceOf<T>()")]
public static InstanceOfTypeConstraint InstanceOfType<T>()
{
return new InstanceOfTypeConstraint(typeof(T));
}
#endif
#endregion
#region AssignableFrom
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public static AssignableFromConstraint AssignableFrom(Type expectedType)
{
return new AssignableFromConstraint(expectedType);
}
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public static AssignableFromConstraint AssignableFrom<T>()
{
return new AssignableFromConstraint(typeof(T));
}
#endif
#endregion
#region AssignableTo
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public static AssignableToConstraint AssignableTo(Type expectedType)
{
return new AssignableToConstraint(expectedType);
}
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public static AssignableToConstraint AssignableTo<T>()
{
return new AssignableToConstraint(typeof(T));
}
#endif
#endregion
#region EquivalentTo
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is a collection containing the same elements as the
/// collection supplied as an argument.
/// </summary>
public static CollectionEquivalentConstraint EquivalentTo(IEnumerable expected)
{
return new CollectionEquivalentConstraint(expected);
}
#endregion
#region SubsetOf
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is a subset of the collection supplied as an argument.
/// </summary>
public static CollectionSubsetConstraint SubsetOf(IEnumerable expected)
{
return new CollectionSubsetConstraint(expected);
}
#endregion
#region Ordered
/// <summary>
/// Returns a constraint that tests whether a collection is ordered
/// </summary>
public static CollectionOrderedConstraint Ordered
{
get { return new CollectionOrderedConstraint(); }
}
#endregion
#region StringContaining
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value contains the substring supplied as an argument.
/// </summary>
public static SubstringConstraint StringContaining(string expected)
{
return new SubstringConstraint(expected);
}
#endregion
#region StringStarting
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
public static StartsWithConstraint StringStarting(string expected)
{
return new StartsWithConstraint(expected);
}
#endregion
#region StringEnding
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
public static EndsWithConstraint StringEnding(string expected)
{
return new EndsWithConstraint(expected);
}
#endregion
#region StringMatching
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value matches the Regex pattern supplied as an argument.
/// </summary>
public static RegexConstraint StringMatching(string pattern)
{
return new RegexConstraint(pattern);
}
#endregion
#region SamePath
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is the same as an expected path after canonicalization.
/// </summary>
public static SamePathConstraint SamePath(string expected)
{
return new SamePathConstraint(expected);
}
#endregion
#region SubPath
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is the same path or under an expected path after canonicalization.
/// </summary>
public static SubPathConstraint SubPath(string expected)
{
return new SubPathConstraint(expected);
}
#endregion
#region SamePathOrUnder
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is the same path or under an expected path after canonicalization.
/// </summary>
public static SamePathOrUnderConstraint SamePathOrUnder(string expected)
{
return new SamePathOrUnderConstraint(expected);
}
#endregion
#region InRange
#if !CLR_2_0 && !CLR_4_0
/// <summary>
/// Returns a constraint that tests whether the actual value falls
/// within a specified range.
/// </summary>
public static RangeConstraint InRange(IComparable from, IComparable to)
{
return new RangeConstraint(from, to);
}
#endif
#endregion
#region InRange<T>
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Returns a constraint that tests whether the actual value falls
/// within a specified range.
/// </summary>
public static RangeConstraint<T> InRange<T>(T from, T to) where T : IComparable<T>
{
return new RangeConstraint<T>(from, to);
}
#endif
#endregion
}
}
| |
/*
' Copyright (c) 2015 Aspose.com
' All rights reserved.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
' DEALINGS IN THE SOFTWARE.
'
*/
using System;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Services.Localization;
using Aspose.Cells;
using System.Collections;
using System.Data;
using System.IO;
using System.Drawing;
using DotNetNuke.Entities.Users;
using System.Web.UI.WebControls;
using System.Collections.Generic;
namespace Aspose.DNN.ExportUsersAndRolesToExcel
{
/// -----------------------------------------------------------------------------
/// <summary>
/// The View class displays the content
///
/// Typically your view control would be used to display content or functionality in your module.
///
/// View may be the only control you have in your project depending on the complexity of your module
///
/// Because the control inherits from Aspose.DNN.ExportUsersAndRolesToExcelModuleBase you have access to any custom properties
/// defined there, as well as properties from DNN such as PortalId, ModuleId, TabId, UserId and many more.
///
/// </summary>
/// -----------------------------------------------------------------------------
public partial class View : ExportUsersAndRolesToExcelModuleBase, IActionable
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
ArrayList dnnUsersArrayList = UserController.GetUsers(PortalId);
if (dnnUsersArrayList.Count == 0)
{
ExportButton.Visible = false;
ExportTypeDropDown.Visible = false;
}
ArrayList stuffedUsers = new ArrayList();
DataTable output = new DataTable("ASA");
output.Columns.Add("DisplayName");
output.Columns.Add("Email");
output.Columns.Add("Roles");
output.Columns.Add("UserID");
foreach (UserInfo user in dnnUsersArrayList)
{
string roles = string.Join(",", user.Roles);
DataRow dr;
dr = output.NewRow();
dr["DisplayName"] = user.DisplayName;
dr["Email"] = user.Email;
dr["Roles"] = roles;
dr["UserID"] = user.UserID;
output.Rows.Add(dr);
}
UsersGridView.DataSource = output;
if (!IsPostBack)
UsersGridView.DataBind();
}
catch (Exception exc) //Module failed to load
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
public ModuleActionCollection ModuleActions
{
get
{
var actions = new ModuleActionCollection
{
{
GetNextActionID(), Localization.GetString("EditModule", LocalResourceFile), "", "", "",
EditUrl(), false, SecurityAccessLevel.Edit, true, false
}
};
return actions;
}
}
protected void ExportButton_Click(object sender, EventArgs e)
{
string format = ExportTypeDropDown.SelectedValue;
DataTable selectedUsers = new DataTable("SU");
selectedUsers.Columns.Add("DisplayName");
selectedUsers.Columns.Add("Email");
selectedUsers.Columns.Add("Roles");
selectedUsers.Columns.Add("UserID");
foreach (GridViewRow row in UsersGridView.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("SelectedCheckBox") as CheckBox);
if (chkRow.Checked)
{
int userId = Convert.ToInt32(UsersGridView.DataKeys[row.RowIndex].Value.ToString());
UserInfo user = UserController.GetUserById(PortalId, userId);
string roles = string.Join(",", user.Roles);
DataRow dr;
dr = selectedUsers.NewRow();
dr["UserID"] = user.UserID;
dr["DisplayName"] = user.DisplayName;
dr["Email"] = user.Email;
dr["Roles"] = roles;
selectedUsers.Rows.Add(dr);
}
}
}
if (selectedUsers.Rows.Count == 0)
{
NoRowSelectedErrorDiv.Visible = true;
}
else
{
// Check for license and apply if exists
string licenseFile = Server.MapPath("~/App_Data/Aspose.Words.lic");
if (File.Exists(licenseFile))
{
License license = new License();
license.SetLicense(licenseFile);
}
//Instantiate a new Workbook
Workbook book = new Workbook();
//Clear all the worksheets
book.Worksheets.Clear();
//Add a new Sheet "Data";
Worksheet sheet = book.Worksheets.Add("DNN Users");
//We pick a few columns not all to import to the worksheet
sheet.Cells.ImportDataTable(selectedUsers,true,"A1");
Worksheet worksheet = book.Worksheets[0];
ApplyCellStyle(ref worksheet, "A1");
ApplyCellStyle(ref worksheet, "B1");
ApplyCellStyle(ref worksheet, "C1");
ApplyCellStyle(ref worksheet, "D1");
worksheet.Cells.InsertRow(0);
worksheet.Cells.InsertColumn(0);
worksheet.AutoFitColumns();
string fileName = System.Guid.NewGuid().ToString() + "." + format;
book.Save(this.Response, fileName, ContentDisposition.Attachment, GetSaveFormat(format));
Response.End();
}
}
private void ApplyCellStyle(ref Worksheet worksheet, string cellName)
{
Cell cell = worksheet.Cells[cellName];
Aspose.Cells.Style style = cell.GetStyle();
style.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;
style.Borders[BorderType.TopBorder].Color = Color.Black;
style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;
style.Borders[BorderType.BottomBorder].Color = Color.Black;
style.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;
style.Borders[BorderType.LeftBorder].Color = Color.Black;
style.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;
style.Borders[BorderType.RightBorder].Color = Color.Black;
style.Pattern = BackgroundType.Solid;
style.ForegroundColor = Color.LightGray;
style.Font.IsBold = true;
cell.SetStyle(style);
}
private XlsSaveOptions GetSaveFormat(string format)
{
XlsSaveOptions saveOption = new XlsSaveOptions(SaveFormat.Xlsx);
switch (format)
{
case "xlsx":
saveOption = new XlsSaveOptions(SaveFormat.Xlsx); break;
case "xlsb":
saveOption = new XlsSaveOptions(SaveFormat.Xlsb); break;
case "xls":
saveOption = new XlsSaveOptions(SaveFormat.Excel97To2003); break;
case "txt":
saveOption = new XlsSaveOptions(SaveFormat.TabDelimited); break;
case "csv":
saveOption = new XlsSaveOptions(SaveFormat.CSV); break;
case "ods":
saveOption = new XlsSaveOptions(SaveFormat.ODS); break;
}
return saveOption;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class BinaryLogicalTests
{
//TODO: Need tests on the short-circuit and non-short-circuit nature of the two forms.
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckBoolAndTest(bool useInterpreter)
{
bool[] array = new bool[] { true, false };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyBoolAnd(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckBoolAndAlsoTest(bool useInterpreter)
{
bool[] array = new bool[] { true, false };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyBoolAndAlso(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckBoolOrTest(bool useInterpreter)
{
bool[] array = new bool[] { true, false };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyBoolOr(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckBoolOrElseTest(bool useInterpreter)
{
bool[] array = new bool[] { true, false };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyBoolOrElse(array[i], array[j], useInterpreter);
}
}
}
#endregion
#region Test verifiers
private static void VerifyBoolAnd(bool a, bool b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.And(
Expression.Constant(a, typeof(bool)),
Expression.Constant(b, typeof(bool))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a & b, f());
}
private static void VerifyBoolAndAlso(bool a, bool b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.AndAlso(
Expression.Constant(a, typeof(bool)),
Expression.Constant(b, typeof(bool))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a && b, f());
}
private static void VerifyBoolOr(bool a, bool b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.Or(
Expression.Constant(a, typeof(bool)),
Expression.Constant(b, typeof(bool))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a | b, f());
}
private static void VerifyBoolOrElse(bool a, bool b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.OrElse(
Expression.Constant(a, typeof(bool)),
Expression.Constant(b, typeof(bool))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a || b, f());
}
#endregion
public static IEnumerable<object[]> AndAlso_TestData()
{
yield return new object[] { 5, 3, 1, true };
yield return new object[] { 0, 3, 0, false };
yield return new object[] { 5, 0, 0, true };
}
[Theory]
[PerCompilationType(nameof(AndAlso_TestData))]
public static void AndAlso_UserDefinedOperator(int leftValue, int rightValue, int expectedValue, bool calledMethod, bool useInterpreter)
{
TrueFalseClass left = new TrueFalseClass(leftValue);
TrueFalseClass right = new TrueFalseClass(rightValue);
BinaryExpression expression = Expression.AndAlso(Expression.Constant(left), Expression.Constant(right));
Func<TrueFalseClass> lambda = Expression.Lambda<Func<TrueFalseClass>>(expression).Compile(useInterpreter);
Assert.Equal(expectedValue, lambda().Value);
// AndAlso only evaluates the false operator of left
Assert.Equal(0, left.TrueCallCount);
Assert.Equal(1, left.FalseCallCount);
Assert.Equal(0, right.TrueCallCount);
Assert.Equal(0, right.FalseCallCount);
// AndAlso only evaluates the operator if left is not false
Assert.Equal(calledMethod ? 1 : 0, left.OperatorCallCount);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void AndAlso_UserDefinedOperator_HasMethodNotOperator(bool useInterpreter)
{
BinaryExpression expression = Expression.AndAlso(Expression.Constant(new NamedMethods(5)), Expression.Constant(new NamedMethods(3)));
Func<NamedMethods> lambda = Expression.Lambda<Func<NamedMethods>>(expression).Compile(useInterpreter);
Assert.Equal(1, lambda().Value);
}
[Theory]
[PerCompilationType(nameof(AndAlso_TestData))]
public static void AndAlso_Method(int leftValue, int rightValue, int expectedValue, bool calledMethod, bool useInterpreter)
{
MethodInfo method = typeof(TrueFalseClass).GetMethod(nameof(TrueFalseClass.AndMethod));
TrueFalseClass left = new TrueFalseClass(leftValue);
TrueFalseClass right = new TrueFalseClass(rightValue);
BinaryExpression expression = Expression.AndAlso(Expression.Constant(left), Expression.Constant(right), method);
Func<TrueFalseClass> lambda = Expression.Lambda<Func<TrueFalseClass>>(expression).Compile(useInterpreter);
Assert.Equal(expectedValue, lambda().Value);
// AndAlso only evaluates the false operator of left
Assert.Equal(0, left.TrueCallCount);
Assert.Equal(1, left.FalseCallCount);
Assert.Equal(0, right.TrueCallCount);
Assert.Equal(0, right.FalseCallCount);
// AndAlso only evaluates the method if left is not false
Assert.Equal(0, left.OperatorCallCount);
Assert.Equal(calledMethod ? 1 : 0, left.MethodCallCount);
}
public static IEnumerable<object[]> OrElse_TestData()
{
yield return new object[] { 5, 3, 5, false };
yield return new object[] { 0, 3, 3, true };
yield return new object[] { 5, 0, 5, false };
}
[Theory]
[PerCompilationType(nameof(OrElse_TestData))]
public static void OrElse_UserDefinedOperator(int leftValue, int rightValue, int expectedValue, bool calledMethod, bool useInterpreter)
{
TrueFalseClass left = new TrueFalseClass(leftValue);
TrueFalseClass right = new TrueFalseClass(rightValue);
BinaryExpression expression = Expression.OrElse(Expression.Constant(left), Expression.Constant(right));
Func<TrueFalseClass> lambda = Expression.Lambda<Func<TrueFalseClass>>(expression).Compile(useInterpreter);
Assert.Equal(expectedValue, lambda().Value);
// OrElse only evaluates the true operator of left
Assert.Equal(1, left.TrueCallCount);
Assert.Equal(0, left.FalseCallCount);
Assert.Equal(0, right.TrueCallCount);
Assert.Equal(0, right.FalseCallCount);
// OrElse only evaluates the operator if left is not true
Assert.Equal(calledMethod ? 1 : 0, left.OperatorCallCount);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void OrElse_UserDefinedOperator_HasMethodNotOperator(bool useInterpreter)
{
BinaryExpression expression = Expression.OrElse(Expression.Constant(new NamedMethods(0)), Expression.Constant(new NamedMethods(3)));
Func<NamedMethods> lambda = Expression.Lambda<Func<NamedMethods>>(expression).Compile(useInterpreter);
Assert.Equal(3, lambda().Value);
}
[Theory]
[PerCompilationType(nameof(OrElse_TestData))]
public static void OrElse_Method(int leftValue, int rightValue, int expectedValue, bool calledMethod, bool useInterpreter)
{
MethodInfo method = typeof(TrueFalseClass).GetMethod(nameof(TrueFalseClass.OrMethod));
TrueFalseClass left = new TrueFalseClass(leftValue);
TrueFalseClass right = new TrueFalseClass(rightValue);
BinaryExpression expression = Expression.OrElse(Expression.Constant(left), Expression.Constant(right), method);
Func<TrueFalseClass> lambda = Expression.Lambda<Func<TrueFalseClass>>(expression).Compile(useInterpreter);
Assert.Equal(expectedValue, lambda().Value);
// OrElse only evaluates the true operator of left
Assert.Equal(1, left.TrueCallCount);
Assert.Equal(0, left.FalseCallCount);
Assert.Equal(0, right.TrueCallCount);
Assert.Equal(0, right.FalseCallCount);
// OrElse only evaluates the method if left is not true
Assert.Equal(0, left.OperatorCallCount);
Assert.Equal(calledMethod ? 1 : 0, left.MethodCallCount);
}
[Fact]
public static void AndAlso_CannotReduce()
{
Expression exp = Expression.AndAlso(Expression.Constant(true), Expression.Constant(false));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
AssertExtensions.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public static void OrElse_CannotReduce()
{
Expression exp = Expression.OrElse(Expression.Constant(true), Expression.Constant(false));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
AssertExtensions.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public static void AndAlso_LeftNull_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("left", () => Expression.AndAlso(null, Expression.Constant(true)));
AssertExtensions.Throws<ArgumentNullException>("left", () => Expression.AndAlso(null, Expression.Constant(true), null));
}
[Fact]
public static void OrElse_LeftNull_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("left", () => Expression.OrElse(null, Expression.Constant(true)));
AssertExtensions.Throws<ArgumentNullException>("left", () => Expression.OrElse(null, Expression.Constant(true), null));
}
[Fact]
public static void AndAlso_RightNull_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("right", () => Expression.AndAlso(Expression.Constant(true), null));
AssertExtensions.Throws<ArgumentNullException>("right", () => Expression.AndAlso(Expression.Constant(true), null, null));
}
[Fact]
public static void OrElse_RightNull_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("right", () => Expression.OrElse(Expression.Constant(true), null));
AssertExtensions.Throws<ArgumentNullException>("right", () => Expression.OrElse(Expression.Constant(true), null, null));
}
[Fact]
public static void AndAlso_BinaryOperatorNotDefined_ThrowsInvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(5), Expression.Constant("hello")));
Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(5), Expression.Constant("hello"), null));
}
[Fact]
public static void OrElse_BinaryOperatorNotDefined_ThrowsInvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(5), Expression.Constant("hello")));
Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(5), Expression.Constant("hello"), null));
}
public static IEnumerable<object[]> InvalidMethod_TestData()
{
yield return new object[] { typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.InstanceMethod)) };
yield return new object[] { typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.StaticVoidMethod)) };
}
[Theory]
[ClassData(typeof(OpenGenericMethodsData))]
[MemberData(nameof(InvalidMethod_TestData))]
public static void InvalidMethod_ThrowsArgumentException(MethodInfo method)
{
AssertExtensions.Throws<ArgumentException>("method", () => Expression.AndAlso(Expression.Constant(5), Expression.Constant(5), method));
AssertExtensions.Throws<ArgumentException>("method", () => Expression.OrElse(Expression.Constant(5), Expression.Constant(5), method));
}
[Theory]
[InlineData(typeof(NonGenericClass), nameof(NonGenericClass.StaticIntMethod0))]
[InlineData(typeof(NonGenericClass), nameof(NonGenericClass.StaticIntMethod1))]
[InlineData(typeof(NonGenericClass), nameof(NonGenericClass.StaticIntMethod3))]
public static void Method_DoesntHaveTwoParameters_ThrowsArgumentException(Type type, string methodName)
{
MethodInfo method = type.GetMethod(methodName);
AssertExtensions.Throws<ArgumentException>("method", () => Expression.AndAlso(Expression.Constant(5), Expression.Constant(5), method));
AssertExtensions.Throws<ArgumentException>("method", () => Expression.OrElse(Expression.Constant(5), Expression.Constant(5), method));
}
[Fact]
public static void AndAlso_Method_ExpressionDoesntMatchMethodParameters_ThrowsInvalidOperationException()
{
MethodInfo method = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.StaticIntMethod2Valid));
Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant("abc"), Expression.Constant(5), method));
Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(5), Expression.Constant("abc"), method));
}
[Fact]
public static void OrElse_ExpressionDoesntMatchMethodParameters_ThrowsInvalidOperationException()
{
MethodInfo method = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.StaticIntMethod2Valid));
Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant("abc"), Expression.Constant(5), method));
Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(5), Expression.Constant("abc"), method));
}
[Fact]
public static void MethodParametersNotEqual_ThrowsArgumentException()
{
MethodInfo method = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.StaticIntMethod2Invalid1));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(5), Expression.Constant("abc"), method));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(5), Expression.Constant("abc"), method));
}
[Fact]
public static void Method_ReturnTypeNotEqualToParameterTypes_ThrowsArgumentException()
{
MethodInfo method = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.StaticIntMethod2Invalid2));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(5), Expression.Constant(5), method));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(5), Expression.Constant(5), method));
}
[Fact]
public static void MethodDeclaringTypeHasNoTrueFalseOperator_ThrowsArgumentException()
{
MethodInfo method = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.StaticIntMethod2Valid));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(5), Expression.Constant(5), method));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(5), Expression.Constant(5), method));
}
#if FEATURE_COMPILE
[Fact]
public static void AndAlso_NoMethod_NotStatic_ThrowsInvalidOperationException()
{
TypeBuilder type = GetTypeBuilder();
MethodBuilder andOperator = type.DefineMethod("op_BitwiseAnd", MethodAttributes.Public, type, new Type[] { type, type });
andOperator.GetILGenerator().Emit(OpCodes.Ret);
Type createdType = type.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj)));
}
[Fact]
public static void OrElse_NoMethod_NotStatic_ThrowsInvalidOperationException()
{
TypeBuilder type = GetTypeBuilder();
MethodBuilder andOperator = type.DefineMethod("op_BitwiseOr", MethodAttributes.Public, type, new Type[] { type, type });
andOperator.GetILGenerator().Emit(OpCodes.Ret);
Type createdType = type.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj)));
}
[Fact]
public static void AndAlso_NoMethod_VoidReturnType_ThrowsArgumentException()
{
TypeBuilder type = GetTypeBuilder();
MethodBuilder andOperator = type.DefineMethod("op_BitwiseAnd", MethodAttributes.Public | MethodAttributes.Static, typeof(void), new Type[] { type, type });
andOperator.GetILGenerator().Emit(OpCodes.Ret);
Type createdType = type.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
AssertExtensions.Throws<ArgumentException>("method", () => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj)));
}
[Fact]
public static void OrElse_NoMethod_VoidReturnType_ThrowsArgumentException()
{
TypeBuilder type = GetTypeBuilder();
MethodBuilder andOperator = type.DefineMethod("op_BitwiseOr", MethodAttributes.Public | MethodAttributes.Static, typeof(void), new Type[] { type, type });
andOperator.GetILGenerator().Emit(OpCodes.Ret);
Type createdType = type.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
AssertExtensions.Throws<ArgumentException>("method", () => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj)));
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(3)]
public static void AndAlso_NoMethod_DoesntHaveTwoParameters_ThrowsInvalidOperationException(int parameterCount)
{
TypeBuilder type = GetTypeBuilder();
MethodBuilder andOperator = type.DefineMethod("op_BitwiseAnd", MethodAttributes.Public | MethodAttributes.Static, type, Enumerable.Repeat(type, parameterCount).ToArray());
andOperator.GetILGenerator().Emit(OpCodes.Ret);
Type createdType = type.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj)));
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(3)]
public static void OrElse_NoMethod_DoesntHaveTwoParameters_ThrowsInvalidOperationException(int parameterCount)
{
TypeBuilder type = GetTypeBuilder();
MethodBuilder andOperator = type.DefineMethod("op_BitwiseOr", MethodAttributes.Public | MethodAttributes.Static, type, Enumerable.Repeat(type, parameterCount).ToArray());
andOperator.GetILGenerator().Emit(OpCodes.Ret);
Type createdType = type.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj)));
}
[Fact]
public static void AndAlso_NoMethod_ExpressionDoesntMatchMethodParameters_ThrowsInvalidOperationException()
{
TypeBuilder type = GetTypeBuilder();
MethodBuilder andOperator = type.DefineMethod("op_BitwiseAnd", MethodAttributes.Public | MethodAttributes.Static, type, new Type[] { typeof(int), type });
andOperator.GetILGenerator().Emit(OpCodes.Ret);
Type createdType = type.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj)));
}
[Fact]
public static void OrElse_NoMethod_ExpressionDoesntMatchMethodParameters_ThrowsInvalidOperationException()
{
TypeBuilder type = GetTypeBuilder();
MethodBuilder andOperator = type.DefineMethod("op_BitwiseOr", MethodAttributes.Public | MethodAttributes.Static, type, new Type[] { typeof(int), type });
andOperator.GetILGenerator().Emit(OpCodes.Ret);
Type createdType = type.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj)));
}
[Fact]
public static void AndAlso_NoMethod_ReturnTypeNotEqualToParameterTypes_ThrowsArgumentException()
{
TypeBuilder type = GetTypeBuilder();
MethodBuilder andOperator = type.DefineMethod("op_BitwiseAnd", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { type, type });
andOperator.GetILGenerator().Emit(OpCodes.Ret);
Type createdType = type.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
AssertExtensions.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj)));
}
[Fact]
public static void OrElse_NoMethod_ReturnTypeNotEqualToParameterTypes_ThrowsArgumentException()
{
TypeBuilder type = GetTypeBuilder();
MethodBuilder andOperator = type.DefineMethod("op_BitwiseOr", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { type, type });
andOperator.GetILGenerator().Emit(OpCodes.Ret);
Type createdType = type.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
AssertExtensions.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj)));
}
public static IEnumerable<object[]> Operator_IncorrectMethod_TestData()
{
// Does not return bool
TypeBuilder typeBuilder1 = GetTypeBuilder();
yield return new object[] { typeBuilder1, typeof(void), new Type[] { typeBuilder1 } };
// Parameter is not assignable from left
yield return new object[] { GetTypeBuilder(), typeof(bool), new Type[] { typeof(int) } };
// Has two parameters
TypeBuilder typeBuilder2 = GetTypeBuilder();
yield return new object[] { typeBuilder2, typeof(bool), new Type[] { typeBuilder2, typeBuilder2 } };
// Has no parameters
yield return new object[] { GetTypeBuilder(), typeof(bool), new Type[0] };
}
[Theory]
[MemberData(nameof(Operator_IncorrectMethod_TestData))]
public static void Method_TrueOperatorIncorrectMethod_ThrowsArgumentException(TypeBuilder builder, Type returnType, Type[] parameterTypes)
{
MethodBuilder opTrue = builder.DefineMethod("op_True", MethodAttributes.SpecialName | MethodAttributes.Static, returnType, parameterTypes);
opTrue.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder opFalse = builder.DefineMethod("op_False", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opFalse.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder method = builder.DefineMethod("Method", MethodAttributes.Public | MethodAttributes.Static, builder, new Type[] { builder, builder });
method.GetILGenerator().Emit(OpCodes.Ret);
TypeInfo createdType = builder.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
MethodInfo createdMethod = createdType.GetMethod("Method");
AssertExtensions.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj), createdMethod));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj), createdMethod));
}
[Theory]
[MemberData(nameof(Operator_IncorrectMethod_TestData))]
public static void Method_FalseOperatorIncorrectMethod_ThrowsArgumentException(TypeBuilder builder, Type returnType, Type[]parameterTypes)
{
MethodBuilder opTrue = builder.DefineMethod("op_True", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opTrue.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder opFalse = builder.DefineMethod("op_False", MethodAttributes.SpecialName | MethodAttributes.Static, returnType, parameterTypes);
opFalse.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder method = builder.DefineMethod("Method", MethodAttributes.Public | MethodAttributes.Static, builder, new Type[] { builder, builder });
method.GetILGenerator().Emit(OpCodes.Ret);
TypeInfo createdType = builder.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
MethodInfo createdMethod = createdType.GetMethod("Method");
AssertExtensions.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj), createdMethod));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj), createdMethod));
}
[Theory]
[MemberData(nameof(Operator_IncorrectMethod_TestData))]
public static void AndAlso_NoMethod_TrueOperatorIncorrectMethod_ThrowsArgumentException(TypeBuilder builder, Type returnType, Type[] parameterTypes)
{
MethodBuilder opTrue = builder.DefineMethod("op_True", MethodAttributes.SpecialName | MethodAttributes.Static, returnType, parameterTypes);
opTrue.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder opFalse = builder.DefineMethod("op_False", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opFalse.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder method = builder.DefineMethod("op_BitwiseAnd", MethodAttributes.Public | MethodAttributes.Static, builder, new Type[] { builder, builder });
method.GetILGenerator().Emit(OpCodes.Ret);
TypeInfo createdType = builder.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
AssertExtensions.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj)));
}
[Theory]
[MemberData(nameof(Operator_IncorrectMethod_TestData))]
public static void OrElse_NoMethod_TrueOperatorIncorrectMethod_ThrowsArgumentException(TypeBuilder builder, Type returnType, Type[] parameterTypes)
{
MethodBuilder opTrue = builder.DefineMethod("op_True", MethodAttributes.SpecialName | MethodAttributes.Static, returnType, parameterTypes);
opTrue.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder opFalse = builder.DefineMethod("op_False", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opFalse.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder method = builder.DefineMethod("op_BitwiseOr", MethodAttributes.Public | MethodAttributes.Static, builder, new Type[] { builder, builder });
method.GetILGenerator().Emit(OpCodes.Ret);
TypeInfo createdType = builder.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
AssertExtensions.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj)));
}
[Theory]
[InlineData("op_True")]
[InlineData("op_False")]
public static void Method_NoTrueFalseOperator_ThrowsArgumentException(string name)
{
AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run);
ModuleBuilder module = assembly.DefineDynamicModule("Name");
TypeBuilder builder = module.DefineType("Type");
MethodBuilder opTrue = builder.DefineMethod(name, MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opTrue.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder method = builder.DefineMethod("Method", MethodAttributes.Public | MethodAttributes.Static, builder, new Type[] { builder, builder });
method.GetILGenerator().Emit(OpCodes.Ret);
TypeInfo createdType = builder.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
MethodInfo createdMethod = createdType.GetMethod("Method");
AssertExtensions.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj), createdMethod));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj), createdMethod));
}
[Theory]
[InlineData("op_True")]
[InlineData("op_False")]
public static void AndAlso_NoMethod_NoTrueFalseOperator_ThrowsArgumentException(string name)
{
AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run);
ModuleBuilder module = assembly.DefineDynamicModule("Name");
TypeBuilder builder = module.DefineType("Type");
MethodBuilder opTrue = builder.DefineMethod(name, MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opTrue.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder method = builder.DefineMethod("op_BitwiseAnd", MethodAttributes.Public | MethodAttributes.Static, builder, new Type[] { builder, builder });
method.GetILGenerator().Emit(OpCodes.Ret);
TypeInfo createdType = builder.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
AssertExtensions.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj)));
}
[Theory]
[InlineData("op_True")]
[InlineData("op_False")]
public static void OrElse_NoMethod_NoTrueFalseOperator_ThrowsArgumentException(string name)
{
AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run);
ModuleBuilder module = assembly.DefineDynamicModule("Name");
TypeBuilder builder = module.DefineType("Type");
MethodBuilder opTrue = builder.DefineMethod(name, MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opTrue.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder method = builder.DefineMethod("op_BitwiseOr", MethodAttributes.Public | MethodAttributes.Static, builder, new Type[] { builder, builder });
method.GetILGenerator().Emit(OpCodes.Ret);
TypeInfo createdType = builder.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
AssertExtensions.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj)));
}
[Fact]
public static void Method_ParamsDontMatchOperator_ThrowsInvalidOperationException()
{
TypeBuilder builder = GetTypeBuilder();
MethodBuilder opTrue = builder.DefineMethod("op_True", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opTrue.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder opFalse = builder.DefineMethod("op_False", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opFalse.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder method = builder.DefineMethod("Method", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { typeof(int), typeof(int) });
method.GetILGenerator().Emit(OpCodes.Ret);
TypeInfo createdType = builder.CreateTypeInfo();
MethodInfo createdMethod = createdType.GetMethod("Method");
Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(5), Expression.Constant(5), createdMethod));
Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(5), Expression.Constant(5), createdMethod));
}
[Fact]
public static void AndAlso_NoMethod_ParamsDontMatchOperator_ThrowsInvalidOperationException()
{
TypeBuilder builder = GetTypeBuilder();
MethodBuilder opTrue = builder.DefineMethod("op_True", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opTrue.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder opFalse = builder.DefineMethod("op_False", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opFalse.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder method = builder.DefineMethod("op_BitwiseAnd", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { typeof(int), typeof(int) });
method.GetILGenerator().Emit(OpCodes.Ret);
TypeInfo createdType = builder.CreateTypeInfo();
Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(5), Expression.Constant(5)));
}
[Fact]
public static void OrElse_NoMethod_ParamsDontMatchOperator_ThrowsInvalidOperationException()
{
TypeBuilder builder = GetTypeBuilder();
MethodBuilder opTrue = builder.DefineMethod("op_True", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opTrue.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder opFalse = builder.DefineMethod("op_False", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opFalse.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder method = builder.DefineMethod("op_BitwiseOr", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { typeof(int), typeof(int) });
method.GetILGenerator().Emit(OpCodes.Ret);
TypeInfo createdType = builder.CreateTypeInfo();
Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(5), Expression.Constant(5)));
}
#endif
[Fact]
public static void ImplicitConversionToBool_ThrowsArgumentException()
{
MethodInfo method = typeof(ClassWithImplicitBoolOperator).GetMethod(nameof(ClassWithImplicitBoolOperator.ConversionMethod));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(new ClassWithImplicitBoolOperator()), Expression.Constant(new ClassWithImplicitBoolOperator()), method));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(new ClassWithImplicitBoolOperator()), Expression.Constant(new ClassWithImplicitBoolOperator()), method));
}
[Theory]
[ClassData(typeof(UnreadableExpressionsData))]
public static void AndAlso_LeftIsWriteOnly_ThrowsArgumentException(Expression unreadableExpression)
{
AssertExtensions.Throws<ArgumentException>("left", () => Expression.AndAlso(unreadableExpression, Expression.Constant(true)));
}
[Theory]
[ClassData(typeof(UnreadableExpressionsData))]
public static void AndAlso_RightIsWriteOnly_ThrowsArgumentException(Expression unreadableExpression)
{
AssertExtensions.Throws<ArgumentException>("right", () => Expression.AndAlso(Expression.Constant(true), unreadableExpression));
}
[Theory]
[ClassData(typeof(UnreadableExpressionsData))]
public static void OrElse_LeftIsWriteOnly_ThrowsArgumentException(Expression unreadableExpression)
{
AssertExtensions.Throws<ArgumentException>("left", () => Expression.OrElse(unreadableExpression, Expression.Constant(true)));
}
[Theory]
[ClassData(typeof(UnreadableExpressionsData))]
public static void OrElse_RightIsWriteOnly_ThrowsArgumentException(Expression unreadableExpression)
{
AssertExtensions.Throws<ArgumentException>("right", () => Expression.OrElse(Expression.Constant(false), unreadableExpression));
}
[Fact]
public static void ToStringTest()
{
// NB: These were && and || in .NET 3.5 but shipped as AndAlso and OrElse in .NET 4.0; we kept the latter.
BinaryExpression e1 = Expression.AndAlso(Expression.Parameter(typeof(bool), "a"), Expression.Parameter(typeof(bool), "b"));
Assert.Equal("(a AndAlso b)", e1.ToString());
BinaryExpression e2 = Expression.OrElse(Expression.Parameter(typeof(bool), "a"), Expression.Parameter(typeof(bool), "b"));
Assert.Equal("(a OrElse b)", e2.ToString());
}
#if FEATURE_COMPILE
[Fact]
public static void AndAlsoGlobalMethod()
{
MethodInfo method = GlobalMethod(typeof(int), new[] { typeof(int), typeof(int) });
Assert.Throws<ArgumentException>(() => Expression.AndAlso(Expression.Constant(1), Expression.Constant(2), method));
}
[Fact]
public static void OrElseGlobalMethod()
{
MethodInfo method = GlobalMethod(typeof(int), new [] { typeof(int), typeof(int) });
Assert.Throws<ArgumentException>(() => Expression.OrElse(Expression.Constant(1), Expression.Constant(2), method));
}
private static TypeBuilder GetTypeBuilder()
{
AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run);
ModuleBuilder module = assembly.DefineDynamicModule("Name");
return module.DefineType("Type");
}
private static MethodInfo GlobalMethod(Type returnType, Type[] parameterTypes)
{
ModuleBuilder module = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run).DefineDynamicModule("Module");
MethodBuilder globalMethod = module.DefineGlobalMethod("GlobalMethod", MethodAttributes.Public | MethodAttributes.Static, returnType, parameterTypes);
globalMethod.GetILGenerator().Emit(OpCodes.Ret);
module.CreateGlobalFunctions();
return module.GetMethod(globalMethod.Name);
}
#endif
public class NonGenericClass
{
public void InstanceMethod() { }
public static void StaticVoidMethod() { }
public static int StaticIntMethod0() => 0;
public static int StaticIntMethod1(int i) => 0;
public static int StaticIntMethod3(int i1, int i2, int i3) => 0;
public static int StaticIntMethod2Valid(int i1, int i2) => 0;
public static int StaticIntMethod2Invalid1(int i1, string i2) => 0;
public static string StaticIntMethod2Invalid2(int i1, int i2) => "abc";
}
public class TrueFalseClass
{
public int TrueCallCount { get; set; }
public int FalseCallCount { get; set; }
public int OperatorCallCount { get; set; }
public int MethodCallCount { get; set; }
public TrueFalseClass(int value) { Value = value; }
public int Value { get; }
public static bool operator true(TrueFalseClass c)
{
c.TrueCallCount++;
return c.Value != 0;
}
public static bool operator false(TrueFalseClass c)
{
c.FalseCallCount++;
return c.Value == 0;
}
public static TrueFalseClass operator &(TrueFalseClass c1, TrueFalseClass c2)
{
c1.OperatorCallCount++;
return new TrueFalseClass(c1.Value & c2.Value);
}
public static TrueFalseClass AndMethod(TrueFalseClass c1, TrueFalseClass c2)
{
c1.MethodCallCount++;
return new TrueFalseClass(c1.Value & c2.Value);
}
public static TrueFalseClass operator |(TrueFalseClass c1, TrueFalseClass c2)
{
c1.OperatorCallCount++;
return new TrueFalseClass(c1.Value | c2.Value);
}
public static TrueFalseClass OrMethod(TrueFalseClass c1, TrueFalseClass c2)
{
c1.MethodCallCount++;
return new TrueFalseClass(c1.Value | c2.Value);
}
}
public class NamedMethods
{
public NamedMethods(int value) { Value = value; }
public int Value { get; }
public static bool operator true(NamedMethods c) => c.Value != 0;
public static bool operator false(NamedMethods c) => c.Value == 0;
public static NamedMethods op_BitwiseAnd(NamedMethods c1, NamedMethods c2) => new NamedMethods(c1.Value & c2.Value);
public static NamedMethods op_BitwiseOr(NamedMethods c1, NamedMethods c2) => new NamedMethods(c1.Value | c2.Value);
}
public class ClassWithImplicitBoolOperator
{
public static ClassWithImplicitBoolOperator ConversionMethod(ClassWithImplicitBoolOperator bool1, ClassWithImplicitBoolOperator bool2)
{
return bool1;
}
public static implicit operator bool(ClassWithImplicitBoolOperator boolClass) => true;
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Compute.V1.Snippets
{
using Google.Api.Gax;
using System;
using System.Linq;
using System.Threading.Tasks;
using lro = Google.LongRunning;
/// <summary>Generated snippets.</summary>
public sealed class AllGeneratedTargetSslProxiesClientSnippets
{
/// <summary>Snippet for Delete</summary>
public void DeleteRequestObject()
{
// Snippet: Delete(DeleteTargetSslProxyRequest, CallSettings)
// Create client
TargetSslProxiesClient targetSslProxiesClient = TargetSslProxiesClient.Create();
// Initialize request argument(s)
DeleteTargetSslProxyRequest request = new DeleteTargetSslProxyRequest
{
RequestId = "",
Project = "",
TargetSslProxy = "",
};
// Make the request
lro::Operation<Operation, Operation> response = targetSslProxiesClient.Delete(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = targetSslProxiesClient.PollOnceDelete(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteRequestObjectAsync()
{
// Snippet: DeleteAsync(DeleteTargetSslProxyRequest, CallSettings)
// Additional: DeleteAsync(DeleteTargetSslProxyRequest, CancellationToken)
// Create client
TargetSslProxiesClient targetSslProxiesClient = await TargetSslProxiesClient.CreateAsync();
// Initialize request argument(s)
DeleteTargetSslProxyRequest request = new DeleteTargetSslProxyRequest
{
RequestId = "",
Project = "",
TargetSslProxy = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await targetSslProxiesClient.DeleteAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await targetSslProxiesClient.PollOnceDeleteAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Delete</summary>
public void Delete()
{
// Snippet: Delete(string, string, CallSettings)
// Create client
TargetSslProxiesClient targetSslProxiesClient = TargetSslProxiesClient.Create();
// Initialize request argument(s)
string project = "";
string targetSslProxy = "";
// Make the request
lro::Operation<Operation, Operation> response = targetSslProxiesClient.Delete(project, targetSslProxy);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = targetSslProxiesClient.PollOnceDelete(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteAsync()
{
// Snippet: DeleteAsync(string, string, CallSettings)
// Additional: DeleteAsync(string, string, CancellationToken)
// Create client
TargetSslProxiesClient targetSslProxiesClient = await TargetSslProxiesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string targetSslProxy = "";
// Make the request
lro::Operation<Operation, Operation> response = await targetSslProxiesClient.DeleteAsync(project, targetSslProxy);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await targetSslProxiesClient.PollOnceDeleteAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Get</summary>
public void GetRequestObject()
{
// Snippet: Get(GetTargetSslProxyRequest, CallSettings)
// Create client
TargetSslProxiesClient targetSslProxiesClient = TargetSslProxiesClient.Create();
// Initialize request argument(s)
GetTargetSslProxyRequest request = new GetTargetSslProxyRequest
{
Project = "",
TargetSslProxy = "",
};
// Make the request
TargetSslProxy response = targetSslProxiesClient.Get(request);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetRequestObjectAsync()
{
// Snippet: GetAsync(GetTargetSslProxyRequest, CallSettings)
// Additional: GetAsync(GetTargetSslProxyRequest, CancellationToken)
// Create client
TargetSslProxiesClient targetSslProxiesClient = await TargetSslProxiesClient.CreateAsync();
// Initialize request argument(s)
GetTargetSslProxyRequest request = new GetTargetSslProxyRequest
{
Project = "",
TargetSslProxy = "",
};
// Make the request
TargetSslProxy response = await targetSslProxiesClient.GetAsync(request);
// End snippet
}
/// <summary>Snippet for Get</summary>
public void Get()
{
// Snippet: Get(string, string, CallSettings)
// Create client
TargetSslProxiesClient targetSslProxiesClient = TargetSslProxiesClient.Create();
// Initialize request argument(s)
string project = "";
string targetSslProxy = "";
// Make the request
TargetSslProxy response = targetSslProxiesClient.Get(project, targetSslProxy);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetAsync()
{
// Snippet: GetAsync(string, string, CallSettings)
// Additional: GetAsync(string, string, CancellationToken)
// Create client
TargetSslProxiesClient targetSslProxiesClient = await TargetSslProxiesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string targetSslProxy = "";
// Make the request
TargetSslProxy response = await targetSslProxiesClient.GetAsync(project, targetSslProxy);
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void InsertRequestObject()
{
// Snippet: Insert(InsertTargetSslProxyRequest, CallSettings)
// Create client
TargetSslProxiesClient targetSslProxiesClient = TargetSslProxiesClient.Create();
// Initialize request argument(s)
InsertTargetSslProxyRequest request = new InsertTargetSslProxyRequest
{
RequestId = "",
TargetSslProxyResource = new TargetSslProxy(),
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = targetSslProxiesClient.Insert(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = targetSslProxiesClient.PollOnceInsert(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertRequestObjectAsync()
{
// Snippet: InsertAsync(InsertTargetSslProxyRequest, CallSettings)
// Additional: InsertAsync(InsertTargetSslProxyRequest, CancellationToken)
// Create client
TargetSslProxiesClient targetSslProxiesClient = await TargetSslProxiesClient.CreateAsync();
// Initialize request argument(s)
InsertTargetSslProxyRequest request = new InsertTargetSslProxyRequest
{
RequestId = "",
TargetSslProxyResource = new TargetSslProxy(),
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await targetSslProxiesClient.InsertAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await targetSslProxiesClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void Insert()
{
// Snippet: Insert(string, TargetSslProxy, CallSettings)
// Create client
TargetSslProxiesClient targetSslProxiesClient = TargetSslProxiesClient.Create();
// Initialize request argument(s)
string project = "";
TargetSslProxy targetSslProxyResource = new TargetSslProxy();
// Make the request
lro::Operation<Operation, Operation> response = targetSslProxiesClient.Insert(project, targetSslProxyResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = targetSslProxiesClient.PollOnceInsert(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertAsync()
{
// Snippet: InsertAsync(string, TargetSslProxy, CallSettings)
// Additional: InsertAsync(string, TargetSslProxy, CancellationToken)
// Create client
TargetSslProxiesClient targetSslProxiesClient = await TargetSslProxiesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
TargetSslProxy targetSslProxyResource = new TargetSslProxy();
// Make the request
lro::Operation<Operation, Operation> response = await targetSslProxiesClient.InsertAsync(project, targetSslProxyResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await targetSslProxiesClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for List</summary>
public void ListRequestObject()
{
// Snippet: List(ListTargetSslProxiesRequest, CallSettings)
// Create client
TargetSslProxiesClient targetSslProxiesClient = TargetSslProxiesClient.Create();
// Initialize request argument(s)
ListTargetSslProxiesRequest request = new ListTargetSslProxiesRequest
{
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedEnumerable<TargetSslProxyList, TargetSslProxy> response = targetSslProxiesClient.List(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (TargetSslProxy item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (TargetSslProxyList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TargetSslProxy item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TargetSslProxy> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TargetSslProxy item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListRequestObjectAsync()
{
// Snippet: ListAsync(ListTargetSslProxiesRequest, CallSettings)
// Create client
TargetSslProxiesClient targetSslProxiesClient = await TargetSslProxiesClient.CreateAsync();
// Initialize request argument(s)
ListTargetSslProxiesRequest request = new ListTargetSslProxiesRequest
{
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedAsyncEnumerable<TargetSslProxyList, TargetSslProxy> response = targetSslProxiesClient.ListAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((TargetSslProxy item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((TargetSslProxyList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TargetSslProxy item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TargetSslProxy> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TargetSslProxy item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for List</summary>
public void List()
{
// Snippet: List(string, string, int?, CallSettings)
// Create client
TargetSslProxiesClient targetSslProxiesClient = TargetSslProxiesClient.Create();
// Initialize request argument(s)
string project = "";
// Make the request
PagedEnumerable<TargetSslProxyList, TargetSslProxy> response = targetSslProxiesClient.List(project);
// Iterate over all response items, lazily performing RPCs as required
foreach (TargetSslProxy item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (TargetSslProxyList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TargetSslProxy item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TargetSslProxy> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TargetSslProxy item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListAsync()
{
// Snippet: ListAsync(string, string, int?, CallSettings)
// Create client
TargetSslProxiesClient targetSslProxiesClient = await TargetSslProxiesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
// Make the request
PagedAsyncEnumerable<TargetSslProxyList, TargetSslProxy> response = targetSslProxiesClient.ListAsync(project);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((TargetSslProxy item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((TargetSslProxyList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TargetSslProxy item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TargetSslProxy> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TargetSslProxy item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for SetBackendService</summary>
public void SetBackendServiceRequestObject()
{
// Snippet: SetBackendService(SetBackendServiceTargetSslProxyRequest, CallSettings)
// Create client
TargetSslProxiesClient targetSslProxiesClient = TargetSslProxiesClient.Create();
// Initialize request argument(s)
SetBackendServiceTargetSslProxyRequest request = new SetBackendServiceTargetSslProxyRequest
{
RequestId = "",
TargetSslProxiesSetBackendServiceRequestResource = new TargetSslProxiesSetBackendServiceRequest(),
Project = "",
TargetSslProxy = "",
};
// Make the request
lro::Operation<Operation, Operation> response = targetSslProxiesClient.SetBackendService(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = targetSslProxiesClient.PollOnceSetBackendService(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for SetBackendServiceAsync</summary>
public async Task SetBackendServiceRequestObjectAsync()
{
// Snippet: SetBackendServiceAsync(SetBackendServiceTargetSslProxyRequest, CallSettings)
// Additional: SetBackendServiceAsync(SetBackendServiceTargetSslProxyRequest, CancellationToken)
// Create client
TargetSslProxiesClient targetSslProxiesClient = await TargetSslProxiesClient.CreateAsync();
// Initialize request argument(s)
SetBackendServiceTargetSslProxyRequest request = new SetBackendServiceTargetSslProxyRequest
{
RequestId = "",
TargetSslProxiesSetBackendServiceRequestResource = new TargetSslProxiesSetBackendServiceRequest(),
Project = "",
TargetSslProxy = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await targetSslProxiesClient.SetBackendServiceAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await targetSslProxiesClient.PollOnceSetBackendServiceAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for SetBackendService</summary>
public void SetBackendService()
{
// Snippet: SetBackendService(string, string, TargetSslProxiesSetBackendServiceRequest, CallSettings)
// Create client
TargetSslProxiesClient targetSslProxiesClient = TargetSslProxiesClient.Create();
// Initialize request argument(s)
string project = "";
string targetSslProxy = "";
TargetSslProxiesSetBackendServiceRequest targetSslProxiesSetBackendServiceRequestResource = new TargetSslProxiesSetBackendServiceRequest();
// Make the request
lro::Operation<Operation, Operation> response = targetSslProxiesClient.SetBackendService(project, targetSslProxy, targetSslProxiesSetBackendServiceRequestResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = targetSslProxiesClient.PollOnceSetBackendService(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for SetBackendServiceAsync</summary>
public async Task SetBackendServiceAsync()
{
// Snippet: SetBackendServiceAsync(string, string, TargetSslProxiesSetBackendServiceRequest, CallSettings)
// Additional: SetBackendServiceAsync(string, string, TargetSslProxiesSetBackendServiceRequest, CancellationToken)
// Create client
TargetSslProxiesClient targetSslProxiesClient = await TargetSslProxiesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string targetSslProxy = "";
TargetSslProxiesSetBackendServiceRequest targetSslProxiesSetBackendServiceRequestResource = new TargetSslProxiesSetBackendServiceRequest();
// Make the request
lro::Operation<Operation, Operation> response = await targetSslProxiesClient.SetBackendServiceAsync(project, targetSslProxy, targetSslProxiesSetBackendServiceRequestResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await targetSslProxiesClient.PollOnceSetBackendServiceAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for SetProxyHeader</summary>
public void SetProxyHeaderRequestObject()
{
// Snippet: SetProxyHeader(SetProxyHeaderTargetSslProxyRequest, CallSettings)
// Create client
TargetSslProxiesClient targetSslProxiesClient = TargetSslProxiesClient.Create();
// Initialize request argument(s)
SetProxyHeaderTargetSslProxyRequest request = new SetProxyHeaderTargetSslProxyRequest
{
RequestId = "",
TargetSslProxiesSetProxyHeaderRequestResource = new TargetSslProxiesSetProxyHeaderRequest(),
Project = "",
TargetSslProxy = "",
};
// Make the request
lro::Operation<Operation, Operation> response = targetSslProxiesClient.SetProxyHeader(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = targetSslProxiesClient.PollOnceSetProxyHeader(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for SetProxyHeaderAsync</summary>
public async Task SetProxyHeaderRequestObjectAsync()
{
// Snippet: SetProxyHeaderAsync(SetProxyHeaderTargetSslProxyRequest, CallSettings)
// Additional: SetProxyHeaderAsync(SetProxyHeaderTargetSslProxyRequest, CancellationToken)
// Create client
TargetSslProxiesClient targetSslProxiesClient = await TargetSslProxiesClient.CreateAsync();
// Initialize request argument(s)
SetProxyHeaderTargetSslProxyRequest request = new SetProxyHeaderTargetSslProxyRequest
{
RequestId = "",
TargetSslProxiesSetProxyHeaderRequestResource = new TargetSslProxiesSetProxyHeaderRequest(),
Project = "",
TargetSslProxy = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await targetSslProxiesClient.SetProxyHeaderAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await targetSslProxiesClient.PollOnceSetProxyHeaderAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for SetProxyHeader</summary>
public void SetProxyHeader()
{
// Snippet: SetProxyHeader(string, string, TargetSslProxiesSetProxyHeaderRequest, CallSettings)
// Create client
TargetSslProxiesClient targetSslProxiesClient = TargetSslProxiesClient.Create();
// Initialize request argument(s)
string project = "";
string targetSslProxy = "";
TargetSslProxiesSetProxyHeaderRequest targetSslProxiesSetProxyHeaderRequestResource = new TargetSslProxiesSetProxyHeaderRequest();
// Make the request
lro::Operation<Operation, Operation> response = targetSslProxiesClient.SetProxyHeader(project, targetSslProxy, targetSslProxiesSetProxyHeaderRequestResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = targetSslProxiesClient.PollOnceSetProxyHeader(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for SetProxyHeaderAsync</summary>
public async Task SetProxyHeaderAsync()
{
// Snippet: SetProxyHeaderAsync(string, string, TargetSslProxiesSetProxyHeaderRequest, CallSettings)
// Additional: SetProxyHeaderAsync(string, string, TargetSslProxiesSetProxyHeaderRequest, CancellationToken)
// Create client
TargetSslProxiesClient targetSslProxiesClient = await TargetSslProxiesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string targetSslProxy = "";
TargetSslProxiesSetProxyHeaderRequest targetSslProxiesSetProxyHeaderRequestResource = new TargetSslProxiesSetProxyHeaderRequest();
// Make the request
lro::Operation<Operation, Operation> response = await targetSslProxiesClient.SetProxyHeaderAsync(project, targetSslProxy, targetSslProxiesSetProxyHeaderRequestResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await targetSslProxiesClient.PollOnceSetProxyHeaderAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for SetSslCertificates</summary>
public void SetSslCertificatesRequestObject()
{
// Snippet: SetSslCertificates(SetSslCertificatesTargetSslProxyRequest, CallSettings)
// Create client
TargetSslProxiesClient targetSslProxiesClient = TargetSslProxiesClient.Create();
// Initialize request argument(s)
SetSslCertificatesTargetSslProxyRequest request = new SetSslCertificatesTargetSslProxyRequest
{
RequestId = "",
TargetSslProxiesSetSslCertificatesRequestResource = new TargetSslProxiesSetSslCertificatesRequest(),
Project = "",
TargetSslProxy = "",
};
// Make the request
lro::Operation<Operation, Operation> response = targetSslProxiesClient.SetSslCertificates(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = targetSslProxiesClient.PollOnceSetSslCertificates(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for SetSslCertificatesAsync</summary>
public async Task SetSslCertificatesRequestObjectAsync()
{
// Snippet: SetSslCertificatesAsync(SetSslCertificatesTargetSslProxyRequest, CallSettings)
// Additional: SetSslCertificatesAsync(SetSslCertificatesTargetSslProxyRequest, CancellationToken)
// Create client
TargetSslProxiesClient targetSslProxiesClient = await TargetSslProxiesClient.CreateAsync();
// Initialize request argument(s)
SetSslCertificatesTargetSslProxyRequest request = new SetSslCertificatesTargetSslProxyRequest
{
RequestId = "",
TargetSslProxiesSetSslCertificatesRequestResource = new TargetSslProxiesSetSslCertificatesRequest(),
Project = "",
TargetSslProxy = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await targetSslProxiesClient.SetSslCertificatesAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await targetSslProxiesClient.PollOnceSetSslCertificatesAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for SetSslCertificates</summary>
public void SetSslCertificates()
{
// Snippet: SetSslCertificates(string, string, TargetSslProxiesSetSslCertificatesRequest, CallSettings)
// Create client
TargetSslProxiesClient targetSslProxiesClient = TargetSslProxiesClient.Create();
// Initialize request argument(s)
string project = "";
string targetSslProxy = "";
TargetSslProxiesSetSslCertificatesRequest targetSslProxiesSetSslCertificatesRequestResource = new TargetSslProxiesSetSslCertificatesRequest();
// Make the request
lro::Operation<Operation, Operation> response = targetSslProxiesClient.SetSslCertificates(project, targetSslProxy, targetSslProxiesSetSslCertificatesRequestResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = targetSslProxiesClient.PollOnceSetSslCertificates(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for SetSslCertificatesAsync</summary>
public async Task SetSslCertificatesAsync()
{
// Snippet: SetSslCertificatesAsync(string, string, TargetSslProxiesSetSslCertificatesRequest, CallSettings)
// Additional: SetSslCertificatesAsync(string, string, TargetSslProxiesSetSslCertificatesRequest, CancellationToken)
// Create client
TargetSslProxiesClient targetSslProxiesClient = await TargetSslProxiesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string targetSslProxy = "";
TargetSslProxiesSetSslCertificatesRequest targetSslProxiesSetSslCertificatesRequestResource = new TargetSslProxiesSetSslCertificatesRequest();
// Make the request
lro::Operation<Operation, Operation> response = await targetSslProxiesClient.SetSslCertificatesAsync(project, targetSslProxy, targetSslProxiesSetSslCertificatesRequestResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await targetSslProxiesClient.PollOnceSetSslCertificatesAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for SetSslPolicy</summary>
public void SetSslPolicyRequestObject()
{
// Snippet: SetSslPolicy(SetSslPolicyTargetSslProxyRequest, CallSettings)
// Create client
TargetSslProxiesClient targetSslProxiesClient = TargetSslProxiesClient.Create();
// Initialize request argument(s)
SetSslPolicyTargetSslProxyRequest request = new SetSslPolicyTargetSslProxyRequest
{
RequestId = "",
Project = "",
SslPolicyReferenceResource = new SslPolicyReference(),
TargetSslProxy = "",
};
// Make the request
lro::Operation<Operation, Operation> response = targetSslProxiesClient.SetSslPolicy(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = targetSslProxiesClient.PollOnceSetSslPolicy(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for SetSslPolicyAsync</summary>
public async Task SetSslPolicyRequestObjectAsync()
{
// Snippet: SetSslPolicyAsync(SetSslPolicyTargetSslProxyRequest, CallSettings)
// Additional: SetSslPolicyAsync(SetSslPolicyTargetSslProxyRequest, CancellationToken)
// Create client
TargetSslProxiesClient targetSslProxiesClient = await TargetSslProxiesClient.CreateAsync();
// Initialize request argument(s)
SetSslPolicyTargetSslProxyRequest request = new SetSslPolicyTargetSslProxyRequest
{
RequestId = "",
Project = "",
SslPolicyReferenceResource = new SslPolicyReference(),
TargetSslProxy = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await targetSslProxiesClient.SetSslPolicyAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await targetSslProxiesClient.PollOnceSetSslPolicyAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for SetSslPolicy</summary>
public void SetSslPolicy()
{
// Snippet: SetSslPolicy(string, string, SslPolicyReference, CallSettings)
// Create client
TargetSslProxiesClient targetSslProxiesClient = TargetSslProxiesClient.Create();
// Initialize request argument(s)
string project = "";
string targetSslProxy = "";
SslPolicyReference sslPolicyReferenceResource = new SslPolicyReference();
// Make the request
lro::Operation<Operation, Operation> response = targetSslProxiesClient.SetSslPolicy(project, targetSslProxy, sslPolicyReferenceResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = targetSslProxiesClient.PollOnceSetSslPolicy(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for SetSslPolicyAsync</summary>
public async Task SetSslPolicyAsync()
{
// Snippet: SetSslPolicyAsync(string, string, SslPolicyReference, CallSettings)
// Additional: SetSslPolicyAsync(string, string, SslPolicyReference, CancellationToken)
// Create client
TargetSslProxiesClient targetSslProxiesClient = await TargetSslProxiesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string targetSslProxy = "";
SslPolicyReference sslPolicyReferenceResource = new SslPolicyReference();
// Make the request
lro::Operation<Operation, Operation> response = await targetSslProxiesClient.SetSslPolicyAsync(project, targetSslProxy, sslPolicyReferenceResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await targetSslProxiesClient.PollOnceSetSslPolicyAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using Xunit.Abstractions;
using System.IO;
using System.Xml.Schema;
namespace System.Xml.Tests
{
//[TestCase(Name = "TC_SchemaSet_GlobalTypes", Desc = "")]
public class TC_SchemaSet_GlobalTypes : TC_SchemaSetBase
{
private ITestOutputHelper _output;
public TC_SchemaSet_GlobalTypes(ITestOutputHelper output)
{
_output = output;
}
public XmlSchema GetSchema(string ns, string type1, string type2)
{
string xsd = String.Empty;
if (ns.Equals(String.Empty))
xsd = "<schema xmlns='http://www.w3.org/2001/XMLSchema'><complexType name='" + type1 + "'><sequence><element name='local'/></sequence></complexType><simpleType name='" + type2 + "'><restriction base='int'/></simpleType></schema>";
else
xsd = "<schema xmlns='http://www.w3.org/2001/XMLSchema' targetNamespace='" + ns + "'><complexType name='" + type1 + "'><sequence><element name='local'/></sequence></complexType><simpleType name='" + type2 + "'><restriction base='int'/></simpleType></schema>";
XmlSchema schema = XmlSchema.Read(new StringReader(xsd), null);
return schema;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v1 - GlobalTypes on empty collection")]
[InlineData()]
[Theory]
public void v1()
{
XmlSchemaSet sc = new XmlSchemaSet();
XmlSchemaObjectTable table = sc.GlobalTypes;
CError.Compare(table == null, false, "Count");
return;
}
//-----------------------------------------------------------------------------------
// params is a pair of the following info: (namaespace, type1 type2) two schemas are made from this info
//[Variation(Desc = "v2.1 - GlobalTypes with set with two schemas, both without NS", Params = new object[] { "", "t1", "t2", "", "t3", "t4" })]
[InlineData("", "t1", "t2", "", "t3", "t4")]
//[Variation(Desc = "v2.2 - GlobalTypes with set with two schemas, one without NS one with NS", Params = new object[] { "a", "t1", "t2", "", "t3", "t4" })]
[InlineData("a", "t1", "t2", "", "t3", "t4")]
//[Variation(Desc = "v2.2 - GlobalTypes with set with two schemas, both with NS", Params = new object[] { "a", "t1", "t2", "b", "t3", "t4" })]
[InlineData("a", "t1", "t2", "b", "t3", "t4")]
[Theory]
public void v2(object param0, object param1, object param2, object param3, object param4, object param5)
{
string ns1 = param0.ToString();
string ns2 = param3.ToString();
string type1 = param1.ToString();
string type2 = param2.ToString();
string type3 = param4.ToString();
string type4 = param5.ToString();
XmlSchema s1 = GetSchema(ns1, type1, type2);
XmlSchema s2 = GetSchema(ns2, type3, type4);
XmlSchemaSet ss = new XmlSchemaSet();
ss.Add(s1);
CError.Compare(ss.GlobalTypes.Count, 0, "Types Count after add");
ss.Compile();
ss.Add(s2);
CError.Compare(ss.GlobalTypes.Count, 3, "Types Count after add/compile"); //+1 for anyType
ss.Compile();
//Verify
CError.Compare(ss.GlobalTypes.Count, 5, "Types Count after add/compile/add/compile"); //+1 for anyType
CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), true, "Contains1");
CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type2, ns1)), true, "Contains2");
CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type3, ns2)), true, "Contains3");
CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type4, ns2)), true, "Contains4");
//Now reprocess one schema and check
ss.Reprocess(s1);
CError.Compare(ss.GlobalTypes.Count, 3, "Types Count after repr"); //+1 for anyType
ss.Compile();
CError.Compare(ss.GlobalTypes.Count, 5, "Types Count after repr/comp"); //+1 for anyType
//Now Remove one schema and check
ss.Remove(s1);
CError.Compare(ss.GlobalTypes.Count, 3, "Types Count after remove");
ss.Compile();
CError.Compare(ss.GlobalTypes.Count, 3, "Types Count after remove/comp");
return;
}
// params is a pair of the following info: (namaespace, type1 type2)*, doCompile?
//[Variation(Desc = "v3.1 - GlobalTypes with a set having schema (nons) to another set with schema(nons)", Params = new object[] { "", "t1", "t2", "", "t3", "t4", true })]
[InlineData("", "t1", "t2", "", "t3", "t4", true)]
//[Variation(Desc = "v3.2 - GlobalTypes with a set having schema (ns) to another set with schema(nons)", Params = new object[] { "a", "t1", "t2", "", "t3", "t4", true })]
[InlineData("a", "t1", "t2", "", "t3", "t4", true)]
//[Variation(Desc = "v3.3 - GlobalTypes with a set having schema (nons) to another set with schema(ns)", Params = new object[] { "", "t1", "t2", "a", "t3", "t4", true })]
[InlineData("", "t1", "t2", "a", "t3", "t4", true)]
//[Variation(Desc = "v3.4 - GlobalTypes with a set having schema (ns) to another set with schema(ns)", Params = new object[] { "a", "t1", "t2", "b", "t3", "t4", true })]
[InlineData("a", "t1", "t2", "b", "t3", "t4", true)]
//[Variation(Desc = "v3.5 - GlobalTypes with a set having schema (nons) to another set with schema(nons), no compile", Params = new object[] { "", "t1", "t2", "", "t3", "t4", false })]
[InlineData("", "t1", "t2", "", "t3", "t4", false)]
//[Variation(Desc = "v3.6 - GlobalTypes with a set having schema (ns) to another set with schema(nons), no compile", Params = new object[] { "a", "t1", "t2", "", "t3", "t4", false })]
[InlineData("a", "t1", "t2", "", "t3", "t4", false)]
//[Variation(Desc = "v3.7 - GlobalTypes with a set having schema (nons) to another set with schema(ns), no compile", Params = new object[] { "", "t1", "t2", "a", "t3", "t4", false })]
[InlineData("", "t1", "t2", "a", "t3", "t4", false)]
//[Variation(Desc = "v3.8 - GlobalTypes with a set having schema (ns) to another set with schema(ns), no compile", Params = new object[] { "a", "t1", "t2", "b", "t3", "t4", false })]
[InlineData("a", "t1", "t2", "b", "t3", "t4", false)]
[Theory]
public void v3(object param0, object param1, object param2, object param3, object param4, object param5, object param6)
{
string ns1 = param0.ToString();
string ns2 = param3.ToString();
string type1 = param1.ToString();
string type2 = param2.ToString();
string type3 = param4.ToString();
string type4 = param5.ToString();
bool doCompile = (bool)param6;
XmlSchema s1 = GetSchema(ns1, type1, type2);
XmlSchema s2 = GetSchema(ns2, type3, type4);
XmlSchemaSet ss1 = new XmlSchemaSet();
XmlSchemaSet ss2 = new XmlSchemaSet();
ss1.Add(s1);
ss1.Compile();
ss2.Add(s2);
if (doCompile)
ss2.Compile();
// add one schemaset to another
ss1.Add(ss2);
if (!doCompile)
ss1.Compile();
//Verify
CError.Compare(ss1.GlobalTypes.Count, 5, "Types Count after add/comp"); //+1 for anyType
CError.Compare(ss1.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), true, "Contains1");
CError.Compare(ss1.GlobalTypes.Contains(new XmlQualifiedName(type2, ns1)), true, "Contains2");
CError.Compare(ss1.GlobalTypes.Contains(new XmlQualifiedName(type3, ns2)), true, "Contains3");
CError.Compare(ss1.GlobalTypes.Contains(new XmlQualifiedName(type4, ns2)), true, "Contains4");
//Now reprocess one schema and check
ss1.Reprocess(s1);
CError.Compare(ss1.GlobalTypes.Count, 3, "Types Count repr"); //+1 for anyType
ss1.Compile();
CError.Compare(ss1.GlobalTypes.Count, 5, "Types Count repr/comp"); //+1 for anyType
//Now Remove one schema and check
ss1.Remove(s1);
CError.Compare(ss1.GlobalTypes.Count, 3, "Types Count after remove");
ss1.Compile();
CError.Compare(ss1.GlobalTypes.Count, 3, "Types Count after rem/comp");
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v4.1 - GlobalTypes with set having one which imports another, remove one", Priority = 1, Params = new object[] { "import_v1_a.xsd", "ns-a", "ct-A", "", "ct-B" })]
[InlineData("import_v1_a.xsd", "ns-a", "ct-A", "", "ct-B")]
//[Variation(Desc = "v4.2 - GlobalTypes with set having one which imports another, remove one", Priority = 1, Params = new object[] { "import_v2_a.xsd", "ns-a", "ct-A", "ns-b", "ct-B" })]
[InlineData("import_v2_a.xsd", "ns-a", "ct-A", "ns-b", "ct-B")]
[Theory]
public void v4(object param0, object param1, object param2, object param3, object param4)
{
string uri1 = param0.ToString();
string ns1 = param1.ToString();
string type1 = param2.ToString();
string ns2 = param3.ToString();
string type2 = param4.ToString();
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
XmlSchema schema1 = ss.Add(null, Path.Combine(TestData._Root, uri1));
ss.Compile();
CError.Compare(ss.GlobalTypes.Count, 3, "Types Count"); //+1 for anyType
CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), true, "Contains1");
CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type2, ns2)), true, "Contains2");
//get the SOM for the imported schema
foreach (XmlSchema s in ss.Schemas(ns2))
{
ss.Remove(s);
}
ss.Compile();
CError.Compare(ss.GlobalTypes.Count, 2, "Types Count after Remove"); //+1 for anyType
CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), true, "Contains1");
CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type2, ns2)), false, "Contains2");
return;
}
//[Variation(Desc = "v5.1 - GlobalTypes with set having one which imports another, then removerecursive", Priority = 1, Params = new object[] { "import_v1_a.xsd", "ns-a", "ct-A", "", "ct-B" })]
[InlineData("import_v1_a.xsd", "ns-a", "ct-A", "", "ct-B")]
//[Variation(Desc = "v5.2 - GlobalTypes with set having one which imports another, then removerecursive", Priority = 1, Params = new object[] { "import_v2_a.xsd", "ns-a", "ct-A", "ns-b", "ct-B" })]
[InlineData("import_v2_a.xsd", "ns-a", "ct-A", "ns-b", "ct-B")]
[Theory]
public void v5(object param0, object param1, object param2, object param3, object param4)
{
string uri1 = param0.ToString();
string ns1 = param1.ToString();
string type1 = param2.ToString();
string ns2 = param3.ToString();
string type2 = param4.ToString();
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.Add(null, Path.Combine(TestData._Root, "xsdauthor.xsd"));
XmlSchema schema1 = ss.Add(null, Path.Combine(TestData._Root, uri1));
ss.Compile();
CError.Compare(ss.GlobalTypes.Count, 3, "Types Count"); //+1 for anyType
CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), true, "Contains1");
CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type2, ns2)), true, "Contains2");
ss.RemoveRecursive(schema1); // should not need to compile for RemoveRecursive to take effect
CError.Compare(ss.GlobalTypes.Count, 1, "Types Count"); //+1 for anyType
CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), false, "Contains1");
CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type2, ns2)), false, "Contains2");
return;
}
//-----------------------------------------------------------------------------------
//REGRESSIONS
//[Variation(Desc = "v100 - XmlSchemaSet: Components are not added to the global tabels if it is already compiled", Priority = 1)]
[InlineData()]
[Theory]
public void v100()
{
try
{
// anytype t1 t2
XmlSchema schema1 = XmlSchema.Read(new StringReader("<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' targetNamespace='a'><xs:element name='e1' type='xs:anyType'/><xs:complexType name='t1'/><xs:complexType name='t2'/></xs:schema>"), null);
// anytype t3 t4
XmlSchema schema2 = XmlSchema.Read(new StringReader("<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' ><xs:element name='e1' type='xs:anyType'/><xs:complexType name='t3'/><xs:complexType name='t4'/></xs:schema>"), null);
XmlSchemaSet ss1 = new XmlSchemaSet();
XmlSchemaSet ss2 = new XmlSchemaSet();
ss1.Add(schema1);
ss2.Add(schema2);
ss2.Compile();
ss1.Add(ss2);
ss1.Compile();
CError.Compare(ss1.GlobalTypes.Count, 5, "Count");
CError.Compare(ss1.GlobalTypes.Contains(new XmlQualifiedName("t1", "a")), true, "Contains");
CError.Compare(ss1.GlobalTypes.Contains(new XmlQualifiedName("t2", "a")), true, "Contains");
}
catch (Exception e)
{
_output.WriteLine(e.Message);
Assert.True(false);
}
return;
}
}
}
//todo: add sanity test for include
//todo: copy count checks from element
| |
// Jacqueline Kory Westlund
// June 2016
//
// The MIT License (MIT)
// Copyright (c) 2016 Personal Robots Group
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using UnityEngine;
namespace opal
{
// done playing sidekick audio event -- fire when we're done playing
// an audio file so others can know when we're done
public delegate void DonePlayingEventHandler(object sender);
public class Sidekick : MonoBehaviour
{
AudioSource audioSource = null;
Animator animator = null;
bool checkAudio = false;
bool checkAnim = false;
string currAnim = Constants.ANIM_DEFAULT;
bool playingAnim = false;
public event DonePlayingEventHandler donePlayingEvent;
// fader for fading out the screen
//private GameObject fader = null;
/// <summary>
/// On starting, do some setup
/// </summary>
void Awake()
{
// get the sidekick's audio source once
this.audioSource = this.gameObject.GetComponent<AudioSource>();
// if we didn't find a source, create once
if (this.audioSource == null)
{
this.audioSource = this.gameObject.AddComponent<AudioSource>();
}
// TODO load all audio in Resources/Sidekick folder ahead of time?
// get the sidekick's animator source once
this.animator = this.gameObject.GetComponent<Animator>();
// if we didn't find a source, create once
if (this.animator == null)
{
this.animator = this.gameObject.AddComponent<Animator>();
}
// set up fader
/*this.fader = GameObject.FindGameObjectWithTag(Constants.TAG_FADER);
if(this.fader != null) {
this.fader.SetActive(false);
Logger.Log("Got fader: " + this.fader.name);
} else {
Logger.LogError("ERROR: No fader found");
}*/
}
// Start
void Start ()
{
// always start in an idle, no animations state
foreach (string flag in Constants.ANIM_FLAGS.Values)
{
this.animator.SetBool(flag, false);
}
}
void OnEnable ()
{
}
void OnDisable ()
{
}
// Update is called once per frame
void Update ()
{
// we started playing audio and we're waiting for it to finish
if (this.checkAudio && !this.audioSource.isPlaying)
{
// we're done playing audio, tell sidekick to stop playing
// the speaking animation
Logger.Log("done speaking");
this.checkAudio = false;
// NOTE right now we're just fading screen when touch is diabled
// but we could easily just fade screen when toucan speaks, here
//this.fader.SetActive(false);
this.animator.SetBool(Constants.ANIM_FLAGS[Constants.ANIM_SPEAK],false);
// fire event to say we're done playing audio
if(this.donePlayingEvent != null) {
this.donePlayingEvent(this);
}
}
// we started playing an animation and we're waiting for it to finish
if (this.checkAnim && this.animator.GetCurrentAnimatorStateInfo(0).IsName(this.currAnim))
{
this.playingAnim = true;
}
else if (this.checkAnim && this.playingAnim)
{
Logger.Log("done playing animation " + this.currAnim);
this.playingAnim = false;
this.checkAnim = false;
this.animator.SetBool(Constants.ANIM_FLAGS[this.currAnim], false);
this.currAnim = Constants.ANIM_DEFAULT;
}
}
/// <summary>
/// Loads and the sound attached to the object, if one exists
/// </summary>
/// <returns><c>true</c>, if audio is played <c>false</c> otherwise.</returns>
/// <param name="utterance">Utterance to say.</param>
public bool SidekickSay (string utterance)
{
if (utterance.Equals(""))
{
Logger.LogWarning("Sidekick was told to say an empty string!");
return false;
}
// try loading a sound file to play
try {
// to load a sound file this way, the sound file needs to be in an existing
// Assets/Resources folder or subfolder
this.audioSource.clip = Resources.Load(Constants.AUDIO_FILE_PATH +
utterance) as AudioClip;
} catch(UnityException e) {
Logger.LogError("ERROR could not load audio: " + utterance + "\n" + e);
return false;
}
this.audioSource.loop = false;
this.audioSource.playOnAwake = false;
// then play sound if it's not playing
if (!this.gameObject.GetComponent<AudioSource>().isPlaying)
{
// start the speaking animation
//Logger.Log("flag is ... "
// + this.animator.GetBool(Constants.ANIM_FLAGS[Constants.ANIM_SPEAK]));
this.animator.SetBool(Constants.ANIM_FLAGS[Constants.ANIM_SPEAK],true);
//Logger.Log("going to speak ... "
// + this.animator.GetBool(Constants.ANIM_FLAGS[Constants.ANIM_SPEAK]));
// play audio
this.gameObject.GetComponent<AudioSource>().Play();
this.checkAudio = true;
// NOTE right now we're just fading screen when touch is diabled
// but we could easily just fade screen when toucan speaks, here
//this.fader.SetActive(true);
}
return true;
}
/// <summary>
/// Sidekick play an animation
/// </summary>
/// <returns><c>true</c>, if successful <c>false</c> otherwise.</returns>
/// <param name="props">thing to do</param>
public bool SidekickDo (string action)
{
if (action.Equals(""))
{
Logger.LogWarning("Sidekick was told to do an empty string!");
return false;
}
// now try playing animation
try {
// start the animation
Logger.Log("flag is ... " + this.animator.GetBool(Constants.ANIM_FLAGS[action]));
this.animator.SetBool(Constants.ANIM_FLAGS[action],true);
this.currAnim = action;
this.checkAnim = true;
Logger.Log("going to do " + action + " ... "
+ this.animator.GetBool(Constants.ANIM_FLAGS[action]));
}
catch (Exception ex)
{
Logger.LogError("Could not play animation " + action + ": " + ex);
return false;
}
return true;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.Net.Sockets
{
// TODO:
// - Plumb status through async APIs to avoid callbacks on synchronous completion
// - NOTE: this will require refactoring in the *Async APIs to accommodate the lack
// of completion posting
// - Add support for unregistering + reregistering for events
// - This will require a new state for each queue, unregistred, to track whether or
// not the queue is currently registered to receive events
// - Audit Close()-related code for the possibility of file descriptor recycling issues
// - It might make sense to change _closeLock to a ReaderWriterLockSlim that is
// acquired for read by all public methods before attempting a completion and
// acquired for write by Close() and HandlEvents()
// - Audit event-related code for the possibility of GCHandle recycling issues
// - There is a potential issue with handle recycling in event loop processing
// if the processing of an event races with the close of a GCHandle
// - It may be necessary for the event loop thread to do all file descriptor
// unregistration in order to avoid this. If so, this would probably happen
// by adding a flag that indicates that the event loop is processing events and
// a queue of contexts to unregister once processing completes.
//
// NOTE: the publicly-exposed asynchronous methods should match the behavior of
// Winsock overlapped sockets as closely as possible. Especially important are
// completion semantics, as the consuming code relies on the Winsock behavior.
//
// Winsock queues a completion callback for an overlapped operation in two cases:
// 1. the operation successfully completes synchronously, or
// 2. the operation completes asynchronously, successfully or otherwise.
// In other words, a completion callback is queued iff an operation does not
// fail synchronously. The asynchronous methods below (e.g. ReceiveAsync) may
// fail synchronously for either of the following reasons:
// 1. an underlying system call fails synchronously, or
// 2. an underlying system call returns EAGAIN, but the socket is closed before
// the method is able to enqueue its corresponding operation.
// In the first case, the async method should return the SocketError that
// corresponds to the native error code; in the second, the method should return
// SocketError.OperationAborted (which matches what Winsock would return in this
// case). The publicly-exposed synchronous methods may also encounter the second
// case. In this situation these methods should return SocketError.Interrupted
// (which again matches Winsock).
internal sealed class SocketAsyncContext
{
private abstract class AsyncOperation
{
private enum State
{
Waiting = 0,
Running = 1,
Complete = 2,
Cancelled = 3
}
private int _state; // Actually AsyncOperation.State.
#if DEBUG
private int _callbackQueued; // When non-zero, the callback has been queued.
#endif
public AsyncOperation Next;
protected object CallbackOrEvent;
public SocketError ErrorCode;
public byte[] SocketAddress;
public int SocketAddressLen;
public ManualResetEventSlim Event
{
private get { return (ManualResetEventSlim)CallbackOrEvent; }
set { CallbackOrEvent = value; }
}
public AsyncOperation()
{
_state = (int)State.Waiting;
Next = this;
}
public void QueueCompletionCallback()
{
Debug.Assert(!(CallbackOrEvent is ManualResetEventSlim));
Debug.Assert(_state != (int)State.Cancelled);
#if DEBUG
Debug.Assert(Interlocked.CompareExchange(ref _callbackQueued, 1, 0) == 0);
#endif
ThreadPool.QueueUserWorkItem(o => ((AsyncOperation)o).InvokeCallback(), this);
}
public bool TryComplete(int fileDescriptor)
{
Debug.Assert(_state == (int)State.Waiting);
return DoTryComplete(fileDescriptor);
}
public bool TryCompleteAsync(int fileDescriptor)
{
return TryCompleteOrAbortAsync(fileDescriptor, abort: false);
}
public void AbortAsync()
{
bool completed = TryCompleteOrAbortAsync(fileDescriptor: -1, abort: true);
Debug.Assert(completed);
}
private bool TryCompleteOrAbortAsync(int fileDescriptor, bool abort)
{
int state = Interlocked.CompareExchange(ref _state, (int)State.Running, (int)State.Waiting);
if (state == (int)State.Cancelled)
{
// This operation has been cancelled. The canceller is responsible for
// correctly updating any state that would have been handled by
// AsyncOperation.Abort.
return true;
}
Debug.Assert(state != (int)State.Complete && state != (int)State.Running);
bool completed;
if (abort)
{
Abort();
ErrorCode = SocketError.OperationAborted;
completed = true;
}
else
{
completed = DoTryComplete(fileDescriptor);
}
if (completed)
{
var @event = CallbackOrEvent as ManualResetEventSlim;
if (@event != null)
{
@event.Set();
}
else
{
QueueCompletionCallback();
}
Volatile.Write(ref _state, (int)State.Complete);
return true;
}
Volatile.Write(ref _state, (int)State.Waiting);
return false;
}
public bool Wait(int timeout)
{
if (Event.Wait(timeout))
{
return true;
}
var spinWait = new SpinWait();
for (;;)
{
int state = Interlocked.CompareExchange(ref _state, (int)State.Cancelled, (int)State.Waiting);
switch ((State)state)
{
case State.Running:
// A completion attempt is in progress. Keep busy-waiting.
spinWait.SpinOnce();
break;
case State.Complete:
// A completion attempt succeeded. Consider this operation as having completed within the timeout.
return true;
case State.Waiting:
// This operation was successfully cancelled.
return false;
}
}
}
protected abstract void Abort();
protected abstract bool DoTryComplete(int fileDescriptor);
protected abstract void InvokeCallback();
}
private abstract class TransferOperation : AsyncOperation
{
public byte[] Buffer;
public int Offset;
public int Count;
public SocketFlags Flags;
public int BytesTransferred;
public SocketFlags ReceivedFlags;
protected sealed override void Abort() { }
}
private abstract class SendReceiveOperation : TransferOperation
{
public IList<ArraySegment<byte>> Buffers;
public int BufferIndex;
public Action<int, byte[], int, SocketFlags, SocketError> Callback
{
private get { return (Action<int, byte[], int, SocketFlags, SocketError>)CallbackOrEvent; }
set { CallbackOrEvent = value; }
}
protected sealed override void InvokeCallback()
{
Callback(BytesTransferred, SocketAddress, SocketAddressLen, ReceivedFlags, ErrorCode);
}
}
private sealed class SendOperation : SendReceiveOperation
{
protected override bool DoTryComplete(int fileDescriptor)
{
return SocketPal.TryCompleteSendTo(fileDescriptor, Buffer, Buffers, ref BufferIndex, ref Offset, ref Count, Flags, SocketAddress, SocketAddressLen, ref BytesTransferred, out ErrorCode);
}
}
private sealed class ReceiveOperation : SendReceiveOperation
{
protected override bool DoTryComplete(int fileDescriptor)
{
return SocketPal.TryCompleteReceiveFrom(fileDescriptor, Buffer, Buffers, Offset, Count, Flags, SocketAddress, ref SocketAddressLen, out BytesTransferred, out ReceivedFlags, out ErrorCode);
}
}
private sealed class ReceiveMessageFromOperation : TransferOperation
{
public bool IsIPv4;
public bool IsIPv6;
public IPPacketInformation IPPacketInformation;
public Action<int, byte[], int, SocketFlags, IPPacketInformation, SocketError> Callback
{
private get { return (Action<int, byte[], int, SocketFlags, IPPacketInformation, SocketError>)CallbackOrEvent; }
set { CallbackOrEvent = value; }
}
protected override bool DoTryComplete(int fileDescriptor)
{
return SocketPal.TryCompleteReceiveMessageFrom(fileDescriptor, Buffer, Offset, Count, Flags, SocketAddress, ref SocketAddressLen, IsIPv4, IsIPv6, out BytesTransferred, out ReceivedFlags, out IPPacketInformation, out ErrorCode);
}
protected override void InvokeCallback()
{
Callback(BytesTransferred, SocketAddress, SocketAddressLen, ReceivedFlags, IPPacketInformation, ErrorCode);
}
}
private abstract class AcceptOrConnectOperation : AsyncOperation
{
}
private sealed class AcceptOperation : AcceptOrConnectOperation
{
public int AcceptedFileDescriptor;
public Action<int, byte[], int, SocketError> Callback
{
private get { return (Action<int, byte[], int, SocketError>)CallbackOrEvent; }
set { CallbackOrEvent = value; }
}
protected override void Abort()
{
AcceptedFileDescriptor = -1;
}
protected override bool DoTryComplete(int fileDescriptor)
{
bool completed = SocketPal.TryCompleteAccept(fileDescriptor, SocketAddress, ref SocketAddressLen, out AcceptedFileDescriptor, out ErrorCode);
Debug.Assert(ErrorCode == SocketError.Success || AcceptedFileDescriptor == -1);
return completed;
}
protected override void InvokeCallback()
{
Callback(AcceptedFileDescriptor, SocketAddress, SocketAddressLen, ErrorCode);
}
}
private sealed class ConnectOperation : AcceptOrConnectOperation
{
public Action<SocketError> Callback
{
private get { return (Action<SocketError>)CallbackOrEvent; }
set { CallbackOrEvent = value; }
}
protected override void Abort() { }
protected override bool DoTryComplete(int fileDescriptor)
{
return SocketPal.TryCompleteConnect(fileDescriptor, SocketAddressLen, out ErrorCode);
}
protected override void InvokeCallback()
{
Callback(ErrorCode);
}
}
private enum QueueState
{
Clear = 0,
Set = 1,
Stopped = 2,
}
private struct OperationQueue<TOperation>
where TOperation : AsyncOperation
{
private AsyncOperation _tail;
public QueueState State { get; set; }
public bool IsStopped { get { return State == QueueState.Stopped; } }
public bool IsEmpty { get { return _tail == null; } }
public TOperation Head
{
get
{
Debug.Assert(!IsStopped);
return (TOperation)_tail.Next;
}
}
public TOperation Tail
{
get
{
return (TOperation)_tail;
}
}
public void Enqueue(TOperation operation)
{
Debug.Assert(!IsStopped);
Debug.Assert(operation.Next == operation);
if (!IsEmpty)
{
operation.Next = _tail.Next;
_tail.Next = operation;
}
_tail = operation;
}
public void Dequeue()
{
Debug.Assert(!IsStopped);
Debug.Assert(!IsEmpty);
AsyncOperation head = _tail.Next;
if (head == _tail)
{
_tail = null;
}
else
{
_tail.Next = head.Next;
}
}
public OperationQueue<TOperation> Stop()
{
OperationQueue<TOperation> result = this;
_tail = null;
State = QueueState.Stopped;
return result;
}
}
private static SocketAsyncContext s_closedAsyncContext;
public static SocketAsyncContext ClosedAsyncContext
{
get
{
if (Volatile.Read(ref s_closedAsyncContext) == null)
{
var ctx = new SocketAsyncContext(-1, null);
ctx.Close();
Volatile.Write(ref s_closedAsyncContext, ctx);
}
return s_closedAsyncContext;
}
}
private int _fileDescriptor;
private GCHandle _handle;
private OperationQueue<TransferOperation> _receiveQueue;
private OperationQueue<SendOperation> _sendQueue;
private OperationQueue<AcceptOrConnectOperation> _acceptOrConnectQueue;
private SocketAsyncEngine _engine;
private Interop.Sys.SocketEvents _registeredEvents;
// These locks are hierarchical: _closeLock must be acquired before _queueLock in order
// to prevent deadlock.
private object _closeLock = new object();
private object _queueLock = new object();
public SocketAsyncContext(int fileDescriptor, SocketAsyncEngine engine)
{
_fileDescriptor = fileDescriptor;
_engine = engine;
}
private void Register(Interop.Sys.SocketEvents events)
{
Debug.Assert(Monitor.IsEntered(_queueLock));
Debug.Assert(!_handle.IsAllocated || _registeredEvents != Interop.Sys.SocketEvents.None);
Debug.Assert((_registeredEvents & events) == Interop.Sys.SocketEvents.None);
if (_registeredEvents == Interop.Sys.SocketEvents.None)
{
Debug.Assert(!_handle.IsAllocated);
_handle = GCHandle.Alloc(this, GCHandleType.Normal);
}
events |= _registeredEvents;
Interop.Error errorCode;
if (!_engine.TryRegister(_fileDescriptor, _registeredEvents, events, _handle, out errorCode))
{
if (_registeredEvents == Interop.Sys.SocketEvents.None)
{
_handle.Free();
}
// TODO: throw an appropiate exception
throw new Exception(string.Format("SocketAsyncContext.Register: {0}", errorCode));
}
_registeredEvents = events;
}
private void UnregisterRead()
{
Debug.Assert(Monitor.IsEntered(_queueLock));
Debug.Assert((_registeredEvents & Interop.Sys.SocketEvents.Read) != Interop.Sys.SocketEvents.None);
Interop.Sys.SocketEvents events = _registeredEvents & ~Interop.Sys.SocketEvents.Read;
if (events == Interop.Sys.SocketEvents.None)
{
Unregister();
}
else
{
Interop.Error errorCode;
bool unregistered = _engine.TryRegister(_fileDescriptor, _registeredEvents, events, _handle, out errorCode);
if (unregistered)
{
_registeredEvents = events;
}
else
{
Debug.Fail(string.Format("UnregisterRead failed: {0}", errorCode));
}
}
}
private void Unregister()
{
Debug.Assert(Monitor.IsEntered(_queueLock));
if (_registeredEvents == Interop.Sys.SocketEvents.None)
{
Debug.Assert(!_handle.IsAllocated);
return;
}
Interop.Error errorCode;
bool unregistered = _engine.TryRegister(_fileDescriptor, _registeredEvents, Interop.Sys.SocketEvents.None, _handle, out errorCode);
_registeredEvents = (Interop.Sys.SocketEvents)(-1);
if (unregistered)
{
_registeredEvents = Interop.Sys.SocketEvents.None;
_handle.Free();
}
else
{
Debug.Fail(string.Format("Unregister failed: {0}", errorCode));
}
}
private void CloseInner()
{
Debug.Assert(Monitor.IsEntered(_closeLock) && !Monitor.IsEntered(_queueLock));
OperationQueue<AcceptOrConnectOperation> acceptOrConnectQueue;
OperationQueue<SendOperation> sendQueue;
OperationQueue<TransferOperation> receiveQueue;
lock (_queueLock)
{
// Drain queues and unregister events
acceptOrConnectQueue = _acceptOrConnectQueue.Stop();
sendQueue = _sendQueue.Stop();
receiveQueue = _receiveQueue.Stop();
Unregister();
// TODO: assert that queues are all empty if _registeredEvents was Interop.Sys.SocketEvents.None?
}
// TODO: the error codes on these operations may need to be changed to account for
// the close. I think Winsock returns OperationAborted in the case that
// the socket for an outstanding operation is closed.
Debug.Assert(!acceptOrConnectQueue.IsStopped || acceptOrConnectQueue.IsEmpty);
while (!acceptOrConnectQueue.IsEmpty)
{
AcceptOrConnectOperation op = acceptOrConnectQueue.Head;
op.AbortAsync();
acceptOrConnectQueue.Dequeue();
}
Debug.Assert(!sendQueue.IsStopped || sendQueue.IsEmpty);
while (!sendQueue.IsEmpty)
{
SendReceiveOperation op = sendQueue.Head;
op.AbortAsync();
sendQueue.Dequeue();
}
Debug.Assert(!receiveQueue.IsStopped || receiveQueue.IsEmpty);
while (!receiveQueue.IsEmpty)
{
TransferOperation op = receiveQueue.Head;
op.AbortAsync();
receiveQueue.Dequeue();
}
}
public void Close()
{
Debug.Assert(!Monitor.IsEntered(_queueLock));
lock (_closeLock)
{
CloseInner();
}
}
private bool TryBeginOperation<TOperation>(ref OperationQueue<TOperation> queue, TOperation operation, Interop.Sys.SocketEvents events, out bool isStopped)
where TOperation : AsyncOperation
{
lock (_queueLock)
{
switch (queue.State)
{
case QueueState.Stopped:
isStopped = true;
return false;
case QueueState.Clear:
break;
case QueueState.Set:
isStopped = false;
queue.State = QueueState.Clear;
return false;
}
if ((_registeredEvents & events) == Interop.Sys.SocketEvents.None)
{
Register(events);
}
queue.Enqueue(operation);
isStopped = false;
return true;
}
}
private void EndOperation<TOperation>(ref OperationQueue<TOperation> queue)
where TOperation : AsyncOperation
{
lock (_queueLock)
{
Debug.Assert(!queue.IsStopped);
queue.Dequeue();
}
}
public SocketError Accept(byte[] socketAddress, ref int socketAddressLen, int timeout, out int acceptedFd)
{
Debug.Assert(socketAddress != null);
Debug.Assert(socketAddressLen > 0);
Debug.Assert(timeout == -1 || timeout > 0);
SocketError errorCode;
if (SocketPal.TryCompleteAccept(_fileDescriptor, socketAddress, ref socketAddressLen, out acceptedFd, out errorCode))
{
Debug.Assert(errorCode == SocketError.Success || acceptedFd == -1);
return errorCode;
}
using (var @event = new ManualResetEventSlim())
{
var operation = new AcceptOperation {
Event = @event,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen
};
bool isStopped;
while (!TryBeginOperation(ref _acceptOrConnectQueue, operation, Interop.Sys.SocketEvents.Read, out isStopped))
{
if (isStopped)
{
acceptedFd = -1;
return SocketError.Interrupted;
}
if (operation.TryComplete(_fileDescriptor))
{
socketAddressLen = operation.SocketAddressLen;
acceptedFd = operation.AcceptedFileDescriptor;
return operation.ErrorCode;
}
}
if (!operation.Wait(timeout))
{
acceptedFd = -1;
return SocketError.TimedOut;
}
socketAddressLen = operation.SocketAddressLen;
acceptedFd = operation.AcceptedFileDescriptor;
return operation.ErrorCode;
}
}
public SocketError AcceptAsync(byte[] socketAddress, int socketAddressLen, Action<int, byte[], int, SocketError> callback)
{
Debug.Assert(socketAddress != null);
Debug.Assert(socketAddressLen > 0);
Debug.Assert(callback != null);
int acceptedFd;
SocketError errorCode;
if (SocketPal.TryCompleteAccept(_fileDescriptor, socketAddress, ref socketAddressLen, out acceptedFd, out errorCode))
{
Debug.Assert(errorCode == SocketError.Success || acceptedFd == -1);
if (errorCode == SocketError.Success)
{
ThreadPool.QueueUserWorkItem(args =>
{
var tup = (Tuple<Action<int, byte[], int, SocketError>, int, byte[], int>)args;
tup.Item1(tup.Item2, tup.Item3, tup.Item4, SocketError.Success);
}, Tuple.Create(callback, acceptedFd, socketAddress, socketAddressLen));
}
return errorCode;
}
var operation = new AcceptOperation {
Callback = callback,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen
};
bool isStopped;
while (!TryBeginOperation(ref _acceptOrConnectQueue, operation, Interop.Sys.SocketEvents.Read, out isStopped))
{
if (isStopped)
{
return SocketError.OperationAborted;
}
if (operation.TryComplete(_fileDescriptor))
{
operation.QueueCompletionCallback();
break;
}
}
return SocketError.IOPending;
}
public SocketError Connect(byte[] socketAddress, int socketAddressLen, int timeout)
{
Debug.Assert(socketAddress != null);
Debug.Assert(socketAddressLen > 0);
Debug.Assert(timeout == -1 || timeout > 0);
SocketError errorCode;
if (SocketPal.TryStartConnect(_fileDescriptor, socketAddress, socketAddressLen, out errorCode))
{
return errorCode;
}
using (var @event = new ManualResetEventSlim())
{
var operation = new ConnectOperation {
Event = @event,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen
};
bool isStopped;
while (!TryBeginOperation(ref _acceptOrConnectQueue, operation, Interop.Sys.SocketEvents.Write, out isStopped))
{
if (isStopped)
{
return SocketError.Interrupted;
}
if (operation.TryComplete(_fileDescriptor))
{
return operation.ErrorCode;
}
}
return operation.Wait(timeout) ? operation.ErrorCode : SocketError.TimedOut;
}
}
public SocketError ConnectAsync(byte[] socketAddress, int socketAddressLen, Action<SocketError> callback)
{
Debug.Assert(socketAddress != null);
Debug.Assert(socketAddressLen > 0);
Debug.Assert(callback != null);
SocketError errorCode;
if (SocketPal.TryStartConnect(_fileDescriptor, socketAddress, socketAddressLen, out errorCode))
{
if (errorCode == SocketError.Success)
{
ThreadPool.QueueUserWorkItem(arg => ((Action<SocketError>)arg)(SocketError.Success), callback);
}
return errorCode;
}
var operation = new ConnectOperation {
Callback = callback,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen
};
bool isStopped;
while (!TryBeginOperation(ref _acceptOrConnectQueue, operation, Interop.Sys.SocketEvents.Write, out isStopped))
{
if (isStopped)
{
return SocketError.OperationAborted;
}
if (operation.TryComplete(_fileDescriptor))
{
operation.QueueCompletionCallback();
break;
}
}
return SocketError.IOPending;
}
public SocketError Receive(byte[] buffer, int offset, int count, ref SocketFlags flags, int timeout, out int bytesReceived)
{
int socketAddressLen = 0;
return ReceiveFrom(buffer, offset, count, ref flags, null, ref socketAddressLen, timeout, out bytesReceived);
}
public SocketError ReceiveAsync(byte[] buffer, int offset, int count, SocketFlags flags, Action<int, byte[], int, SocketFlags, SocketError> callback)
{
return ReceiveFromAsync(buffer, offset, count, flags, null, 0, callback);
}
public SocketError ReceiveFrom(byte[] buffer, int offset, int count, ref SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, int timeout, out int bytesReceived)
{
Debug.Assert(timeout == -1 || timeout > 0);
SocketFlags receivedFlags;
SocketError errorCode;
if (SocketPal.TryCompleteReceiveFrom(_fileDescriptor, buffer, offset, count, flags, socketAddress, ref socketAddressLen, out bytesReceived, out receivedFlags, out errorCode))
{
flags = receivedFlags;
return errorCode;
}
using (var @event = new ManualResetEventSlim())
{
var operation = new ReceiveOperation {
Event = @event,
Buffer = buffer,
Offset = offset,
Count = count,
Flags = flags,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen,
BytesTransferred = bytesReceived,
ReceivedFlags = receivedFlags
};
bool isStopped;
while (!TryBeginOperation(ref _receiveQueue, operation, Interop.Sys.SocketEvents.Read, out isStopped))
{
if (isStopped)
{
flags = operation.ReceivedFlags;
bytesReceived = operation.BytesTransferred;
return SocketError.Interrupted;
}
if (operation.TryComplete(_fileDescriptor))
{
socketAddressLen = operation.SocketAddressLen;
flags = operation.ReceivedFlags;
bytesReceived = operation.BytesTransferred;
return operation.ErrorCode;
}
}
bool signaled = operation.Wait(timeout);
socketAddressLen = operation.SocketAddressLen;
flags = operation.ReceivedFlags;
bytesReceived = operation.BytesTransferred;
return signaled ? operation.ErrorCode : SocketError.TimedOut;
}
}
public SocketError ReceiveFromAsync(byte[] buffer, int offset, int count, SocketFlags flags, byte[] socketAddress, int socketAddressLen, Action<int, byte[], int, SocketFlags, SocketError> callback)
{
int bytesReceived;
SocketFlags receivedFlags;
SocketError errorCode;
if (SocketPal.TryCompleteReceiveFrom(_fileDescriptor, buffer, offset, count, flags, socketAddress, ref socketAddressLen, out bytesReceived, out receivedFlags, out errorCode))
{
if (errorCode == SocketError.Success)
{
ThreadPool.QueueUserWorkItem(args =>
{
var tup = (Tuple<Action<int, byte[], int, SocketFlags, SocketError>, int, byte[], int, SocketFlags>)args;
tup.Item1(tup.Item2, tup.Item3, tup.Item4, tup.Item5, SocketError.Success);
}, Tuple.Create(callback, bytesReceived, socketAddress, socketAddressLen, receivedFlags));
}
return errorCode;
}
var operation = new ReceiveOperation {
Callback = callback,
Buffer = buffer,
Offset = offset,
Count = count,
Flags = flags,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen,
BytesTransferred = bytesReceived,
ReceivedFlags = receivedFlags
};
bool isStopped;
while (!TryBeginOperation(ref _receiveQueue, operation, Interop.Sys.SocketEvents.Read, out isStopped))
{
if (isStopped)
{
return SocketError.OperationAborted;
}
if (operation.TryComplete(_fileDescriptor))
{
operation.QueueCompletionCallback();
break;
}
}
return SocketError.IOPending;
}
public SocketError Receive(IList<ArraySegment<byte>> buffers, ref SocketFlags flags, int timeout, out int bytesReceived)
{
return ReceiveFrom(buffers, ref flags, null, 0, timeout, out bytesReceived);
}
public SocketError ReceiveAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, Action<int, byte[], int, SocketFlags, SocketError> callback)
{
return ReceiveFromAsync(buffers, flags, null, 0, callback);
}
public SocketError ReceiveFrom(IList<ArraySegment<byte>> buffers, ref SocketFlags flags, byte[] socketAddress, int socketAddressLen, int timeout, out int bytesReceived)
{
Debug.Assert(timeout == -1 || timeout > 0);
SocketFlags receivedFlags;
SocketError errorCode;
if (SocketPal.TryCompleteReceiveFrom(_fileDescriptor, buffers, flags, socketAddress, ref socketAddressLen, out bytesReceived, out receivedFlags, out errorCode))
{
flags = receivedFlags;
return errorCode;
}
using (var @event = new ManualResetEventSlim())
{
var operation = new ReceiveOperation {
Event = @event,
Buffers = buffers,
Flags = flags,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen,
BytesTransferred = bytesReceived,
ReceivedFlags = receivedFlags
};
bool isStopped;
while (!TryBeginOperation(ref _receiveQueue, operation, Interop.Sys.SocketEvents.Read, out isStopped))
{
if (isStopped)
{
flags = operation.ReceivedFlags;
bytesReceived = operation.BytesTransferred;
return SocketError.Interrupted;
}
if (operation.TryComplete(_fileDescriptor))
{
socketAddressLen = operation.SocketAddressLen;
flags = operation.ReceivedFlags;
bytesReceived = operation.BytesTransferred;
return operation.ErrorCode;
}
}
bool signaled = operation.Wait(timeout);
socketAddressLen = operation.SocketAddressLen;
flags = operation.ReceivedFlags;
bytesReceived = operation.BytesTransferred;
return signaled ? operation.ErrorCode : SocketError.TimedOut;
}
}
public SocketError ReceiveFromAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[] socketAddress, int socketAddressLen, Action<int, byte[], int, SocketFlags, SocketError> callback)
{
int bytesReceived;
SocketFlags receivedFlags;
SocketError errorCode;
if (SocketPal.TryCompleteReceiveFrom(_fileDescriptor, buffers, flags, socketAddress, ref socketAddressLen, out bytesReceived, out receivedFlags, out errorCode))
{
if (errorCode == SocketError.Success)
{
ThreadPool.QueueUserWorkItem(args =>
{
var tup = (Tuple<Action<int, byte[], int, SocketFlags, SocketError>, int, byte[], int, SocketFlags>)args;
tup.Item1(tup.Item2, tup.Item3, tup.Item4, tup.Item5, SocketError.Success);
}, Tuple.Create(callback, bytesReceived, socketAddress, socketAddressLen, receivedFlags));
}
return errorCode;
}
var operation = new ReceiveOperation {
Callback = callback,
Buffers = buffers,
Flags = flags,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen,
BytesTransferred = bytesReceived,
ReceivedFlags = receivedFlags
};
bool isStopped;
while (!TryBeginOperation(ref _receiveQueue, operation, Interop.Sys.SocketEvents.Read, out isStopped))
{
if (isStopped)
{
return SocketError.OperationAborted;
}
if (operation.TryComplete(_fileDescriptor))
{
operation.QueueCompletionCallback();
break;
}
}
return SocketError.IOPending;
}
public SocketError ReceiveMessageFrom(byte[] buffer, int offset, int count, ref SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, bool isIPv4, bool isIPv6, int timeout, out IPPacketInformation ipPacketInformation, out int bytesReceived)
{
Debug.Assert(timeout == -1 || timeout > 0);
SocketFlags receivedFlags;
SocketError errorCode;
if (SocketPal.TryCompleteReceiveMessageFrom(_fileDescriptor, buffer, offset, count, flags, socketAddress, ref socketAddressLen, isIPv4, isIPv6, out bytesReceived, out receivedFlags, out ipPacketInformation, out errorCode))
{
flags = receivedFlags;
return errorCode;
}
using (var @event = new ManualResetEventSlim())
{
var operation = new ReceiveMessageFromOperation {
Event = @event,
Buffer = buffer,
Offset = offset,
Count = count,
Flags = flags,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen,
IsIPv4 = isIPv4,
IsIPv6 = isIPv6,
BytesTransferred = bytesReceived,
ReceivedFlags = receivedFlags,
IPPacketInformation = ipPacketInformation,
};
bool isStopped;
while (!TryBeginOperation(ref _receiveQueue, operation, Interop.Sys.SocketEvents.Read, out isStopped))
{
if (isStopped)
{
socketAddressLen = operation.SocketAddressLen;
flags = operation.ReceivedFlags;
ipPacketInformation = operation.IPPacketInformation;
bytesReceived = operation.BytesTransferred;
return SocketError.Interrupted;
}
if (operation.TryComplete(_fileDescriptor))
{
socketAddressLen = operation.SocketAddressLen;
flags = operation.ReceivedFlags;
ipPacketInformation = operation.IPPacketInformation;
bytesReceived = operation.BytesTransferred;
return operation.ErrorCode;
}
}
bool signaled = operation.Wait(timeout);
socketAddressLen = operation.SocketAddressLen;
flags = operation.ReceivedFlags;
ipPacketInformation = operation.IPPacketInformation;
bytesReceived = operation.BytesTransferred;
return signaled ? operation.ErrorCode : SocketError.TimedOut;
}
}
public SocketError ReceiveMessageFromAsync(byte[] buffer, int offset, int count, SocketFlags flags, byte[] socketAddress, int socketAddressLen, bool isIPv4, bool isIPv6, Action<int, byte[], int, SocketFlags, IPPacketInformation, SocketError> callback)
{
int bytesReceived;
SocketFlags receivedFlags;
IPPacketInformation ipPacketInformation;
SocketError errorCode;
if (SocketPal.TryCompleteReceiveMessageFrom(_fileDescriptor, buffer, offset, count, flags, socketAddress, ref socketAddressLen, isIPv4, isIPv6, out bytesReceived, out receivedFlags, out ipPacketInformation, out errorCode))
{
if (errorCode == SocketError.Success)
{
ThreadPool.QueueUserWorkItem(args =>
{
var tup = (Tuple<Action<int, byte[], int, SocketFlags, IPPacketInformation, SocketError>, int, byte[], int, SocketFlags, IPPacketInformation>)args;
tup.Item1(tup.Item2, tup.Item3, tup.Item4, tup.Item5, tup.Item6, SocketError.Success);
}, Tuple.Create(callback, bytesReceived, socketAddress, socketAddressLen, receivedFlags, ipPacketInformation));
}
return errorCode;
}
var operation = new ReceiveMessageFromOperation {
Callback = callback,
Buffer = buffer,
Offset = offset,
Count = count,
Flags = flags,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen,
IsIPv4 = isIPv4,
IsIPv6 = isIPv6,
BytesTransferred = bytesReceived,
ReceivedFlags = receivedFlags,
IPPacketInformation = ipPacketInformation,
};
bool isStopped;
while (!TryBeginOperation(ref _receiveQueue, operation, Interop.Sys.SocketEvents.Read, out isStopped))
{
if (isStopped)
{
return SocketError.OperationAborted;
}
if (operation.TryComplete(_fileDescriptor))
{
operation.QueueCompletionCallback();
break;
}
}
return SocketError.IOPending;
}
public SocketError Send(byte[] buffer, int offset, int count, SocketFlags flags, int timeout, out int bytesSent)
{
return SendTo(buffer, offset, count, flags, null, 0, timeout, out bytesSent);
}
public SocketError SendAsync(byte[] buffer, int offset, int count, SocketFlags flags, Action<int, byte[], int, SocketFlags, SocketError> callback)
{
return SendToAsync(buffer, offset, count, flags, null, 0, callback);
}
public SocketError SendTo(byte[] buffer, int offset, int count, SocketFlags flags, byte[] socketAddress, int socketAddressLen, int timeout, out int bytesSent)
{
Debug.Assert(timeout == -1 || timeout > 0);
bytesSent = 0;
SocketError errorCode;
if (SocketPal.TryCompleteSendTo(_fileDescriptor, buffer, ref offset, ref count, flags, socketAddress, socketAddressLen, ref bytesSent, out errorCode))
{
return errorCode;
}
using (var @event = new ManualResetEventSlim())
{
var operation = new SendOperation {
Event = @event,
Buffer = buffer,
Offset = offset,
Count = count,
Flags = flags,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen,
BytesTransferred = bytesSent
};
bool isStopped;
while (!TryBeginOperation(ref _sendQueue, operation, Interop.Sys.SocketEvents.Write, out isStopped))
{
if (isStopped)
{
bytesSent = operation.BytesTransferred;
return SocketError.Interrupted;
}
if (operation.TryComplete(_fileDescriptor))
{
bytesSent = operation.BytesTransferred;
return operation.ErrorCode;
}
}
bool signaled = operation.Wait(timeout);
bytesSent = operation.BytesTransferred;
return signaled ? operation.ErrorCode : SocketError.TimedOut;
}
}
public SocketError SendToAsync(byte[] buffer, int offset, int count, SocketFlags flags, byte[] socketAddress, int socketAddressLen, Action<int, byte[], int, SocketFlags, SocketError> callback)
{
int bytesSent = 0;
SocketError errorCode;
if (SocketPal.TryCompleteSendTo(_fileDescriptor, buffer, ref offset, ref count, flags, socketAddress, socketAddressLen, ref bytesSent, out errorCode))
{
if (errorCode == SocketError.Success)
{
ThreadPool.QueueUserWorkItem(args =>
{
var tup = (Tuple<Action<int, byte[], int, SocketFlags, SocketError>, int, byte[], int>)args;
tup.Item1(tup.Item2, tup.Item3, tup.Item4, 0, SocketError.Success);
}, Tuple.Create(callback, bytesSent, socketAddress, socketAddressLen));
}
return errorCode;
}
var operation = new SendOperation {
Callback = callback,
Buffer = buffer,
Offset = offset,
Count = count,
Flags = flags,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen,
BytesTransferred = bytesSent
};
bool isStopped;
while (!TryBeginOperation(ref _sendQueue, operation, Interop.Sys.SocketEvents.Write, out isStopped))
{
if (isStopped)
{
return SocketError.OperationAborted;
}
if (operation.TryComplete(_fileDescriptor))
{
operation.QueueCompletionCallback();
break;
}
}
return SocketError.IOPending;
}
public SocketError Send(IList<ArraySegment<byte>> buffers, SocketFlags flags, int timeout, out int bytesSent)
{
return SendTo(buffers, flags, null, 0, timeout, out bytesSent);
}
public SocketError SendAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, Action<int, byte[], int, SocketFlags, SocketError> callback)
{
return SendToAsync(buffers, flags, null, 0, callback);
}
public SocketError SendTo(IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[] socketAddress, int socketAddressLen, int timeout, out int bytesSent)
{
Debug.Assert(timeout == -1 || timeout > 0);
bytesSent = 0;
int bufferIndex = 0;
int offset = 0;
SocketError errorCode;
if (SocketPal.TryCompleteSendTo(_fileDescriptor, buffers, ref bufferIndex, ref offset, flags, socketAddress, socketAddressLen, ref bytesSent, out errorCode))
{
return errorCode;
}
using (var @event = new ManualResetEventSlim())
{
var operation = new SendOperation {
Event = @event,
Buffers = buffers,
BufferIndex = bufferIndex,
Offset = offset,
Flags = flags,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen,
BytesTransferred = bytesSent
};
bool isStopped;
while (!TryBeginOperation(ref _sendQueue, operation, Interop.Sys.SocketEvents.Write, out isStopped))
{
if (isStopped)
{
bytesSent = operation.BytesTransferred;
return SocketError.Interrupted;
}
if (operation.TryComplete(_fileDescriptor))
{
bytesSent = operation.BytesTransferred;
return operation.ErrorCode;
}
}
bool signaled = operation.Wait(timeout);
bytesSent = operation.BytesTransferred;
return signaled ? operation.ErrorCode : SocketError.TimedOut;
}
}
public SocketError SendToAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[] socketAddress, int socketAddressLen, Action<int, byte[], int, SocketFlags, SocketError> callback)
{
int bufferIndex = 0;
int offset = 0;
int bytesSent = 0;
SocketError errorCode;
if (SocketPal.TryCompleteSendTo(_fileDescriptor, buffers, ref bufferIndex, ref offset, flags, socketAddress, socketAddressLen, ref bytesSent, out errorCode))
{
if (errorCode == SocketError.Success)
{
ThreadPool.QueueUserWorkItem(args =>
{
var tup = (Tuple<Action<int, byte[], int, SocketFlags, SocketError>, int, byte[], int>)args;
tup.Item1(tup.Item2, tup.Item3, tup.Item4, SocketFlags.None, SocketError.Success);
}, Tuple.Create(callback, bytesSent, socketAddress, socketAddressLen));
}
return errorCode;
}
var operation = new SendOperation {
Callback = callback,
Buffers = buffers,
BufferIndex = bufferIndex,
Offset = offset,
Flags = flags,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen,
BytesTransferred = bytesSent
};
bool isStopped;
while (!TryBeginOperation(ref _sendQueue, operation, Interop.Sys.SocketEvents.Write, out isStopped))
{
if (isStopped)
{
return SocketError.OperationAborted;
}
if (operation.TryComplete(_fileDescriptor))
{
operation.QueueCompletionCallback();
break;
}
}
return SocketError.IOPending;
}
public unsafe void HandleEvents(Interop.Sys.SocketEvents events)
{
Debug.Assert(!Monitor.IsEntered(_queueLock) || Monitor.IsEntered(_closeLock), "Lock ordering violation");
lock (_closeLock)
{
if (_registeredEvents == (Interop.Sys.SocketEvents)(-1))
{
// This can happen if a previous attempt at unregistration did not succeed.
// Retry the unregistration.
lock (_queueLock)
{
Debug.Assert(_acceptOrConnectQueue.IsStopped, "{Accept,Connect} queue should be stopped before retrying unregistration");
Debug.Assert(_sendQueue.IsStopped, "Send queue should be stopped before retrying unregistration");
Debug.Assert(_receiveQueue.IsStopped, "Receive queue should be stopped before retrying unregistration");
Unregister();
return;
}
}
if ((events & Interop.Sys.SocketEvents.Error) != 0)
{
// Set the Read and Write flags as well; the processing for these events
// will pick up the error.
events |= Interop.Sys.SocketEvents.Read | Interop.Sys.SocketEvents.Write;
}
if ((events & Interop.Sys.SocketEvents.Close) != 0)
{
// Drain queues and unregister this fd, then return.
CloseInner();
return;
}
if ((events & Interop.Sys.SocketEvents.ReadClose) != 0)
{
// Drain read queue and unregister read operations
Debug.Assert(_acceptOrConnectQueue.IsEmpty, "{Accept,Connect} queue should be empty before ReadClose");
OperationQueue<TransferOperation> receiveQueue;
lock (_queueLock)
{
receiveQueue = _receiveQueue.Stop();
}
while (!receiveQueue.IsEmpty)
{
TransferOperation op = receiveQueue.Head;
bool completed = op.TryCompleteAsync(_fileDescriptor);
Debug.Assert(completed);
receiveQueue.Dequeue();
}
lock (_queueLock)
{
UnregisterRead();
}
// Any data left in the socket has been received above; skip further processing.
events &= ~Interop.Sys.SocketEvents.Read;
}
// TODO: optimize locking and completions:
// - Dequeues (and therefore locking) for multiple contiguous operations can be combined
// - Contiguous completions can happen in a single thread
if ((events & Interop.Sys.SocketEvents.Read) != 0)
{
AcceptOrConnectOperation acceptTail;
TransferOperation receiveTail;
lock (_queueLock)
{
acceptTail = _acceptOrConnectQueue.Tail as AcceptOperation;
_acceptOrConnectQueue.State = QueueState.Set;
receiveTail = _receiveQueue.Tail;
_receiveQueue.State = QueueState.Set;
}
if (acceptTail != null)
{
AcceptOrConnectOperation op;
do
{
op = _acceptOrConnectQueue.Head;
if (!op.TryCompleteAsync(_fileDescriptor))
{
break;
}
EndOperation(ref _acceptOrConnectQueue);
} while (op != acceptTail);
}
if (receiveTail != null)
{
TransferOperation op;
do
{
op = _receiveQueue.Head;
if (!op.TryCompleteAsync(_fileDescriptor))
{
break;
}
EndOperation(ref _receiveQueue);
} while (op != receiveTail);
}
}
if ((events & Interop.Sys.SocketEvents.Write) != 0)
{
AcceptOrConnectOperation connectTail;
SendOperation sendTail;
lock (_queueLock)
{
connectTail = _acceptOrConnectQueue.Tail as ConnectOperation;
_acceptOrConnectQueue.State = QueueState.Set;
sendTail = _sendQueue.Tail;
_sendQueue.State = QueueState.Set;
}
if (connectTail != null)
{
AcceptOrConnectOperation op;
do
{
op = _acceptOrConnectQueue.Head;
if (!op.TryCompleteAsync(_fileDescriptor))
{
break;
}
EndOperation(ref _acceptOrConnectQueue);
} while (op != connectTail);
}
if (sendTail != null)
{
SendOperation op;
do
{
op = _sendQueue.Head;
if (!op.TryCompleteAsync(_fileDescriptor))
{
break;
}
EndOperation(ref _sendQueue);
} while (op != sendTail);
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using SteamLanguageParser;
using System.Text.RegularExpressions;
namespace GoSteamLanguageGenerator
{
public class GoGen
{
/// <summary>
/// Maps the SteamLanguage types to Go types.
/// </summary>
private static Dictionary<String, String> typeMap = new Dictionary<String, String> {
{"byte", "uint8"},
{"short", "int16"},
{"ushort", "uint16"},
{"int", "int32"},
{"uint", "uint32"},
{"long", "int64"},
{"ulong", "uint64"},
{"char", "uint16"}
};
/// <summary>
/// Maps the enum names to their underlying Go types. In most cases, this is int32.
/// </summary>
private Dictionary<string, string> enumTypes = new Dictionary<string, string>();
public void EmitEnums(Node root, StringBuilder sb)
{
sb.AppendLine("// Generated code");
sb.AppendLine("// DO NOT EDIT");
sb.AppendLine();
sb.AppendLine("package steamlang");
sb.AppendLine();
sb.AppendLine("import (");
sb.AppendLine(" \"strings\"");
sb.AppendLine(" \"sort\"");
sb.AppendLine(" \"fmt\"");
sb.AppendLine(")");
sb.AppendLine();
foreach (Node n in root.childNodes) {
EmitEnumNode(n as EnumNode, sb);
}
}
public void EmitClasses(Node root, StringBuilder sb)
{
sb.AppendLine("// Generated code");
sb.AppendLine("// DO NOT EDIT");
sb.AppendLine();
sb.AppendLine("package steamlang");
sb.AppendLine();
sb.AppendLine("import (");
sb.AppendLine(" \"io\"");
sb.AppendLine(" \"encoding/binary\"");
sb.AppendLine(" \"github.com/golang/protobuf/proto\"");
sb.AppendLine(" \"github.com/Philipp15b/go-steam/steamid\"");
sb.AppendLine(" \"github.com/Philipp15b/go-steam/rwu\"");
sb.AppendLine(" . \"github.com/Philipp15b/go-steam/protocol/protobuf\"");
sb.AppendLine(")");
sb.AppendLine();
foreach (Node n in root.childNodes) {
EmitClassNode(n as ClassNode, sb);
}
}
private static string EmitSymbol(Symbol sym)
{
string s = null;
if (sym is WeakSymbol) {
s = (sym as WeakSymbol).Identifier;
} else if (sym is StrongSymbol) {
StrongSymbol ssym = sym as StrongSymbol;
if (ssym.Prop == null) {
s = ssym.Class.Name;
} else {
s = ssym.Class.Name + "_" + ssym.Prop.Name;
}
}
return s.Replace("ulong.MaxValue", "^uint64(0)").Replace("SteamKit2.Internal.", "").Replace("SteamKit2.GC.Internal.", "");
}
private static string EmitType(Symbol sym)
{
string type = EmitSymbol(sym);
return typeMap.ContainsKey(type) ? typeMap[type] : type;
}
private static string GetUpperName(string name)
{
return name.Substring(0, 1).ToUpper() + name.Remove(0, 1);
}
private void EmitEnumNode(EnumNode enode, StringBuilder sb)
{
string type = enode.Type != null ? EmitType(enode.Type) : "int32";
enumTypes.Add(enode.Name, type);
sb.AppendLine("type " + enode.Name + " " + type);
sb.AppendLine();
sb.AppendLine("const (");
bool first = true;
foreach (PropNode prop in enode.childNodes) {
string val = String.Join(" | ", prop.Default.Select(item => {
var name = EmitSymbol(item);
// if this is an element of this enum, make sure to prefix it with its name
return (enode.childNodes.Exists(node => node.Name == name) ? enode.Name + "_" : "") + name;
}));
sb.Append(" " + enode.Name + "_" + prop.Name + " " + enode.Name + " = " + val);
if (prop.Obsolete != null) {
if (prop.Obsolete.Length > 0)
sb.Append(" // Deprecated: " + prop.Obsolete);
else
sb.Append(" // Deprecated");
}
sb.AppendLine();
if (first)
first = false;
}
sb.AppendLine(")");
sb.AppendLine();
EmitEnumStringer(enode, sb);
}
private void EmitEnumStringer(EnumNode enode, StringBuilder sb)
{
sb.AppendLine("var " + enode.Name + "_name = map[" + enode.Name + "]string{");
// duplicate elements don't really make sense here, so we filter them
var uniqueNodes = new List<PropNode>();
{
var allValues = new List<long>();
foreach (var node in enode.childNodes) {
if (!(node is PropNode))
continue;
var prop = node as PropNode;
long val = EvalEnum(enode, prop);
if (allValues.Contains(val))
continue;
allValues.Add(val);
uniqueNodes.Add(prop);
}
}
foreach (PropNode prop in uniqueNodes) {
sb.Append(" " + EvalEnum(enode, prop) + ": ");
sb.AppendLine("\"" + enode.Name + "_" + prop.Name + "\",");
}
sb.AppendLine("}");
sb.AppendLine();
sb.AppendLine("func (e " + enode.Name + ") String() string {");
sb.AppendLine(" if s, ok := " + enode.Name + "_name[e]; ok {");
sb.AppendLine(" return s");
sb.AppendLine(" }");
sb.AppendLine(" var flags []string");
sb.AppendLine(" for k, v := range " + enode.Name + "_name {");
sb.AppendLine(" if e&k != 0 {");
sb.AppendLine(" flags = append(flags, v)");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine(" if len(flags) == 0 {");
sb.AppendLine(" return fmt.Sprintf(\"%d\", e)");
sb.AppendLine(" }");
sb.AppendLine(" sort.Strings(flags)");
sb.AppendLine(" return strings.Join(flags, \" | \")");
sb.AppendLine("}");
sb.AppendLine();
}
private long EvalEnum(EnumNode enode, PropNode prop)
{
long number = 0;
foreach (Symbol sym in prop.Default) {
long n = 0;
var val = (sym as WeakSymbol).Identifier;
if (new Regex("^[-0-9]+$|^0x[-0-9a-fA-F]+$").IsMatch(val)) {
int bas = 10;
if (val.StartsWith("0x", StringComparison.Ordinal)) {
bas = 16;
val = val.Substring(2);
}
n = Convert.ToInt64(val, bas);
} else {
var otherNode = enode.childNodes.Single(o => o is PropNode && (o as PropNode).Name == val) as PropNode;
n = EvalEnum(enode, otherNode);
}
number = number | n;
}
return number;
}
private void EmitClassNode(ClassNode cnode, StringBuilder sb)
{
EmitClassConstants(cnode, sb);
EmitClassDef(cnode, sb);
EmitClassConstructor(cnode, sb);
EmitClassEMsg(cnode, sb);
EmitClassSerializer(cnode, sb);
EmitClassDeserializer(cnode, sb);
}
private void EmitClassConstants(ClassNode cnode, StringBuilder sb)
{
Func<PropNode, string> emitElement = node => cnode.Name + "_" + node.Name + " " + EmitType(node.Type) + " = " + EmitType(node.Default.FirstOrDefault());
var statics = cnode.childNodes.Where(node => node is PropNode && (node as PropNode).Flags == "const");
if (statics.Count() == 1) {
sb.AppendLine("const " + emitElement(cnode.childNodes[0] as PropNode));
sb.AppendLine();
return;
}
bool first = true;
foreach (PropNode node in statics) {
if (first) {
sb.AppendLine("const (");
first = false;
}
sb.AppendLine(" " + emitElement(node));
}
if (!first) {
sb.AppendLine(")");
sb.AppendLine();
}
}
private void EmitClassDef(ClassNode cnode, StringBuilder sb)
{
sb.AppendLine("type " + cnode.Name + " struct {");
foreach (PropNode node in cnode.childNodes) {
if (node.Flags == "const") {
continue;
} else if (node.Flags == "boolmarshal" && EmitSymbol(node.Type) == "byte") {
sb.AppendLine(" " + GetUpperName(node.Name) + " bool");
} else if (node.Flags == "steamidmarshal" && EmitSymbol(node.Type) == "ulong") {
sb.AppendLine(" " + GetUpperName(node.Name) + " steamid.SteamId");
} else if (node.Flags == "proto") {
sb.AppendLine(" " + GetUpperName(node.Name) + " *" + EmitType(node.Type));
} else {
int arraySize;
string typestr = EmitType(node.Type);
if (!String.IsNullOrEmpty(node.FlagsOpt) && Int32.TryParse(node.FlagsOpt, out arraySize)) {
// TODO: use arrays instead of slices?
typestr = "[]" + typestr;
}
sb.AppendLine(" " + GetUpperName(node.Name) + " " + typestr);
}
}
sb.AppendLine("}");
sb.AppendLine();
}
private void EmitClassConstructor(ClassNode cnode, StringBuilder sb)
{
sb.AppendLine("func New" + cnode.Name + "() *" + cnode.Name + " {");
sb.AppendLine(" return &" + cnode.Name + "{");
foreach (PropNode node in cnode.childNodes) {
string ctor = null;
Symbol firstDefault = node.Default.FirstOrDefault();
if (node.Flags == "const") {
continue;
} else if (node.Flags == "proto") {
ctor = "new(" + GetUpperName(EmitType(node.Type)) + ")";
} else if (firstDefault == null) {
// only arrays/slices need explicit initialization
if (String.IsNullOrEmpty(node.FlagsOpt))
continue;
ctor = "make([]" + EmitType(node.Type) + ", " + node.FlagsOpt + ", " + node.FlagsOpt + ")";
} else {
ctor = EmitSymbol(firstDefault);
}
sb.AppendLine(" " + GetUpperName(node.Name) + ": " + ctor + ",");
}
sb.AppendLine(" }");
sb.AppendLine("}");
sb.AppendLine();
}
private void EmitClassEMsg(ClassNode cnode, StringBuilder sb)
{
if (cnode.Ident == null)
return;
string ident = EmitSymbol(cnode.Ident);
if (!ident.Contains("EMsg_"))
return;
sb.AppendLine("func (d *" + cnode.Name + ") GetEMsg() EMsg {");
sb.AppendLine(" return " + ident);
sb.AppendLine("}");
sb.AppendLine();
}
private void EmitClassSerializer(ClassNode cnode, StringBuilder sb)
{
var nodeToBuf = new Dictionary<PropNode, string>();
int tempNum = 0;
sb.AppendLine("func (d *" + cnode.Name + ") Serialize(w io.Writer) error {");
sb.AppendLine(" var err error");
foreach (PropNode node in cnode.childNodes) {
if (node.Flags == "proto") {
sb.AppendLine(" buf" + tempNum + ", err := proto.Marshal(d." + GetUpperName(node.Name) + ")");
sb.AppendLine(" if err != nil { return err }");
if (node.FlagsOpt != null) {
sb.AppendLine(" d." + GetUpperName(node.FlagsOpt) + " = int32(len(buf" + tempNum + "))");
}
nodeToBuf[node] = "buf" + tempNum;
tempNum++;
}
}
foreach (PropNode node in cnode.childNodes) {
if (node.Flags == "const") {
continue;
} else if (node.Flags == "boolmarshal") {
sb.AppendLine(" err = rwu.WriteBool(w, d." + GetUpperName(node.Name) + ")");
} else if (node.Flags == "steamidmarshal") {
sb.AppendLine(" err = binary.Write(w, binary.LittleEndian, d." + GetUpperName(node.Name) + ")");
} else if (node.Flags == "protomask") {
sb.AppendLine(" err = binary.Write(w, binary.LittleEndian, EMsg(uint32(d." + GetUpperName(node.Name) + ") | ProtoMask))");
} else if (node.Flags == "protomaskgc") {
sb.AppendLine(" err = binary.Write(w, binary.LittleEndian, EMsg(uint32(d." + GetUpperName(node.Name) + ") | ProtoMask))");
} else if (node.Flags == "proto") {
sb.AppendLine(" _, err = w.Write(" + nodeToBuf[node] + ")");
} else {
sb.AppendLine(" err = binary.Write(w, binary.LittleEndian, d." + GetUpperName(node.Name) + ")");
}
if (node != cnode.childNodes[cnode.childNodes.Count - 1])
sb.AppendLine(" if err != nil { return err }");
}
sb.AppendLine(" return err");
sb.AppendLine("}");
sb.AppendLine();
}
private void EmitClassDeserializer(ClassNode cnode, StringBuilder sb)
{
int tempNum = 0;
sb.AppendLine("func (d *" + cnode.Name + ") Deserialize(r io.Reader) error {");
sb.AppendLine(" var err error");
foreach (PropNode node in cnode.childNodes) {
if (node.Flags == "const") {
continue;
} else if (node.Flags == "boolmarshal") {
sb.AppendLine(" d." + GetUpperName(node.Name) + ", err = rwu.ReadBool(r)");
} else if (node.Flags == "steamidmarshal") {
sb.AppendLine(" t" + tempNum + ", err := rwu.ReadUint64(r)");
sb.AppendLine(" if err != nil { return err }");
sb.AppendLine(" d." + GetUpperName(node.Name) + " = steamid.SteamId(t" + tempNum + ")");
tempNum++;
continue;
} else if (node.Flags == "protomask") {
string type = EmitType(node.Type);
if (enumTypes.ContainsKey(type))
type = enumTypes[type];
sb.AppendLine(" t" + tempNum + ", err := rwu.Read" + GetUpperName(type) + "(r)");
sb.AppendLine(" if err != nil { return err }");
sb.AppendLine(" d." + GetUpperName(node.Name) + " = EMsg(uint32(t" + tempNum + ") & EMsgMask)");
tempNum++;
continue;
} else if (node.Flags == "protomaskgc") {
sb.AppendLine(" t" + tempNum + ", err := rwu.Read" + GetUpperName(EmitType(node.Type)) + "(r)");
sb.AppendLine(" if err != nil { return err }");
sb.AppendLine(" d." + GetUpperName(node.Name) + " = uint32(t" + tempNum + ") & EMsgMask");
tempNum++;
continue;
} else if (node.Flags == "proto") {
sb.AppendLine(" buf" + tempNum + " := make([]byte, d." + GetUpperName(node.FlagsOpt) + ", d." + GetUpperName(node.FlagsOpt) + ")");
sb.AppendLine(" _, err = io.ReadFull(r, buf" + tempNum + ")");
sb.AppendLine(" if err != nil { return err }");
sb.AppendLine(" err = proto.Unmarshal(buf" + tempNum + ", d." + GetUpperName(node.Name) + ")");
tempNum++;
} else {
string type = EmitType(node.Type);
if (!String.IsNullOrEmpty(node.FlagsOpt)) {
sb.AppendLine(" err = binary.Read(r, binary.LittleEndian, d." + GetUpperName(node.Name) + ")");
} else if (!enumTypes.ContainsKey(type)) {
sb.AppendLine(" d." + GetUpperName(node.Name) + ", err = rwu.Read" + GetUpperName(type) + "(r)");
} else {
sb.AppendLine(" t" + tempNum + ", err := rwu.Read" + GetUpperName(enumTypes[type]) + "(r)");
if (node != cnode.childNodes[cnode.childNodes.Count - 1])
sb.AppendLine(" if err != nil { return err }");
sb.AppendLine(" d." + GetUpperName(node.Name) + " = " + type + "(t" + tempNum + ")");
tempNum++;
continue;
}
}
if (node != cnode.childNodes[cnode.childNodes.Count - 1])
sb.AppendLine(" if err != nil { return err }");
}
sb.AppendLine(" return err");
sb.AppendLine("}");
sb.AppendLine();
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using Microsoft.Azure.Commands.Compute.Automation.Models;
using Microsoft.Azure.Management.Compute;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute.Automation
{
public partial class InvokeAzureComputeMethodCmdlet : ComputeAutomationBaseCmdlet
{
protected object CreateVirtualMachineScaleSetVMGetDynamicParameters()
{
dynamicParameters = new RuntimeDefinedParameterDictionary();
var pResourceGroupName = new RuntimeDefinedParameter();
pResourceGroupName.Name = "ResourceGroupName";
pResourceGroupName.ParameterType = typeof(string);
pResourceGroupName.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 1,
Mandatory = true
});
pResourceGroupName.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("ResourceGroupName", pResourceGroupName);
var pVMScaleSetName = new RuntimeDefinedParameter();
pVMScaleSetName.Name = "VMScaleSetName";
pVMScaleSetName.ParameterType = typeof(string);
pVMScaleSetName.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 2,
Mandatory = true
});
pVMScaleSetName.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("VMScaleSetName", pVMScaleSetName);
var pInstanceId = new RuntimeDefinedParameter();
pInstanceId.Name = "InstanceId";
pInstanceId.ParameterType = typeof(string);
pInstanceId.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 3,
Mandatory = true
});
pInstanceId.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("InstanceId", pInstanceId);
var pArgumentList = new RuntimeDefinedParameter();
pArgumentList.Name = "ArgumentList";
pArgumentList.ParameterType = typeof(object[]);
pArgumentList.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByStaticParameters",
Position = 4,
Mandatory = true
});
pArgumentList.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("ArgumentList", pArgumentList);
return dynamicParameters;
}
protected void ExecuteVirtualMachineScaleSetVMGetMethod(object[] invokeMethodInputParameters)
{
string resourceGroupName = (string)ParseParameter(invokeMethodInputParameters[0]);
string vmScaleSetName = (string)ParseParameter(invokeMethodInputParameters[1]);
string instanceId = (string)ParseParameter(invokeMethodInputParameters[2]);
if (!string.IsNullOrEmpty(resourceGroupName) && !string.IsNullOrEmpty(vmScaleSetName) && !string.IsNullOrEmpty(instanceId))
{
var result = VirtualMachineScaleSetVMsClient.Get(resourceGroupName, vmScaleSetName, instanceId);
WriteObject(result);
}
else if (!string.IsNullOrEmpty(resourceGroupName) && !string.IsNullOrEmpty(vmScaleSetName))
{
var result = VirtualMachineScaleSetVMsClient.List(resourceGroupName, vmScaleSetName);
WriteObject(result);
}
}
}
public partial class NewAzureComputeArgumentListCmdlet : ComputeAutomationBaseCmdlet
{
protected PSArgument[] CreateVirtualMachineScaleSetVMGetParameters()
{
string resourceGroupName = string.Empty;
string vmScaleSetName = string.Empty;
string instanceId = string.Empty;
return ConvertFromObjectsToArguments(
new string[] { "ResourceGroupName", "VMScaleSetName", "InstanceId" },
new object[] { resourceGroupName, vmScaleSetName, instanceId });
}
}
[Cmdlet("Get", "AzureRmVmssVM", DefaultParameterSetName = "InvokeByDynamicParameters")]
public partial class GetAzureRmVmssVM : InvokeAzureComputeMethodCmdlet
{
public override string MethodName { get; set; }
protected override void ProcessRecord()
{
if (this.ParameterSetName == "InvokeByDynamicParameters")
{
this.MethodName = "VirtualMachineScaleSetVMGet";
}
else
{
this.MethodName = "VirtualMachineScaleSetVMGetInstanceView";
}
base.ProcessRecord();
}
public override object GetDynamicParameters()
{
dynamicParameters = new RuntimeDefinedParameterDictionary();
var pResourceGroupName = new RuntimeDefinedParameter();
pResourceGroupName.Name = "ResourceGroupName";
pResourceGroupName.ParameterType = typeof(string);
pResourceGroupName.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 1,
Mandatory = false,
ValueFromPipeline = false
});
pResourceGroupName.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParametersForFriendMethod",
Position = 1,
Mandatory = false,
ValueFromPipeline = false
});
pResourceGroupName.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("ResourceGroupName", pResourceGroupName);
var pVMScaleSetName = new RuntimeDefinedParameter();
pVMScaleSetName.Name = "VMScaleSetName";
pVMScaleSetName.ParameterType = typeof(string);
pVMScaleSetName.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 2,
Mandatory = false,
ValueFromPipeline = false
});
pVMScaleSetName.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParametersForFriendMethod",
Position = 2,
Mandatory = false,
ValueFromPipeline = false
});
pVMScaleSetName.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("VMScaleSetName", pVMScaleSetName);
var pInstanceId = new RuntimeDefinedParameter();
pInstanceId.Name = "InstanceId";
pInstanceId.ParameterType = typeof(string);
pInstanceId.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 3,
Mandatory = false,
ValueFromPipeline = false
});
pInstanceId.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParametersForFriendMethod",
Position = 3,
Mandatory = false,
ValueFromPipeline = false
});
pInstanceId.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("InstanceId", pInstanceId);
var pInstanceView = new RuntimeDefinedParameter();
pInstanceView.Name = "InstanceView";
pInstanceView.ParameterType = typeof(SwitchParameter);
pInstanceView.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParametersForFriendMethod",
Position = 4,
Mandatory = true
});
pInstanceView.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByStaticParametersForFriendMethod",
Position = 5,
Mandatory = true
});
pInstanceView.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("InstanceView", pInstanceView);
return dynamicParameters;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Umbraco.Core.Auditing;
using Umbraco.Core.Events;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.UnitOfWork;
using Umbraco.Core.PropertyEditors;
using umbraco.interfaces;
namespace Umbraco.Core.Services
{
/// <summary>
/// Represents the DataType Service, which is an easy access to operations involving <see cref="IDataTypeDefinition"/>
/// </summary>
public class DataTypeService : RepositoryService, IDataTypeService
{
public DataTypeService(IDatabaseUnitOfWorkProvider provider, RepositoryFactory repositoryFactory, ILogger logger, IEventMessagesFactory eventMessagesFactory)
: base(provider, repositoryFactory, logger, eventMessagesFactory)
{
}
/// <summary>
/// Gets a <see cref="IDataTypeDefinition"/> by its Name
/// </summary>
/// <param name="name">Name of the <see cref="IDataTypeDefinition"/></param>
/// <returns><see cref="IDataTypeDefinition"/></returns>
public IDataTypeDefinition GetDataTypeDefinitionByName(string name)
{
using (var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(UowProvider.GetUnitOfWork()))
{
return repository.GetByQuery(new Query<IDataTypeDefinition>().Where(x => x.Name == name)).FirstOrDefault();
}
}
/// <summary>
/// Gets a <see cref="IDataTypeDefinition"/> by its Id
/// </summary>
/// <param name="id">Id of the <see cref="IDataTypeDefinition"/></param>
/// <returns><see cref="IDataTypeDefinition"/></returns>
public IDataTypeDefinition GetDataTypeDefinitionById(int id)
{
using (var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(UowProvider.GetUnitOfWork()))
{
return repository.Get(id);
}
}
/// <summary>
/// Gets a <see cref="IDataTypeDefinition"/> by its unique guid Id
/// </summary>
/// <param name="id">Unique guid Id of the DataType</param>
/// <returns><see cref="IDataTypeDefinition"/></returns>
public IDataTypeDefinition GetDataTypeDefinitionById(Guid id)
{
using (var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(UowProvider.GetUnitOfWork()))
{
var query = Query<IDataTypeDefinition>.Builder.Where(x => x.Key == id);
var definitions = repository.GetByQuery(query);
return definitions.FirstOrDefault();
}
}
/// <summary>
/// Gets a <see cref="IDataTypeDefinition"/> by its control Id
/// </summary>
/// <param name="id">Id of the DataType control</param>
/// <returns>Collection of <see cref="IDataTypeDefinition"/> objects with a matching contorl id</returns>
[Obsolete("Property editor's are defined by a string alias from version 7 onwards, use the overload GetDataTypeDefinitionByPropertyEditorAlias instead")]
public IEnumerable<IDataTypeDefinition> GetDataTypeDefinitionByControlId(Guid id)
{
var alias = LegacyPropertyEditorIdToAliasConverter.GetAliasFromLegacyId(id, true);
return GetDataTypeDefinitionByPropertyEditorAlias(alias);
}
/// <summary>
/// Gets a <see cref="IDataTypeDefinition"/> by its control Id
/// </summary>
/// <param name="propertyEditorAlias">Alias of the property editor</param>
/// <returns>Collection of <see cref="IDataTypeDefinition"/> objects with a matching contorl id</returns>
public IEnumerable<IDataTypeDefinition> GetDataTypeDefinitionByPropertyEditorAlias(string propertyEditorAlias)
{
using (var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(UowProvider.GetUnitOfWork()))
{
var query = Query<IDataTypeDefinition>.Builder.Where(x => x.PropertyEditorAlias == propertyEditorAlias);
var definitions = repository.GetByQuery(query);
return definitions;
}
}
/// <summary>
/// Gets all <see cref="IDataTypeDefinition"/> objects or those with the ids passed in
/// </summary>
/// <param name="ids">Optional array of Ids</param>
/// <returns>An enumerable list of <see cref="IDataTypeDefinition"/> objects</returns>
public IEnumerable<IDataTypeDefinition> GetAllDataTypeDefinitions(params int[] ids)
{
using (var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(UowProvider.GetUnitOfWork()))
{
return repository.GetAll(ids);
}
}
/// <summary>
/// Gets all prevalues for an <see cref="IDataTypeDefinition"/>
/// </summary>
/// <param name="id">Id of the <see cref="IDataTypeDefinition"/> to retrieve prevalues from</param>
/// <returns>An enumerable list of string values</returns>
public IEnumerable<string> GetPreValuesByDataTypeId(int id)
{
using (var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(UowProvider.GetUnitOfWork()))
{
var collection = repository.GetPreValuesCollectionByDataTypeId(id);
//now convert the collection to a string list
var list = collection.FormatAsDictionary()
.Select(x => x.Value.Value)
.ToList();
return list;
}
}
/// <summary>
/// Returns the PreValueCollection for the specified data type
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public PreValueCollection GetPreValuesCollectionByDataTypeId(int id)
{
using (var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(UowProvider.GetUnitOfWork()))
{
return repository.GetPreValuesCollectionByDataTypeId(id);
}
}
/// <summary>
/// Gets a specific PreValue by its Id
/// </summary>
/// <param name="id">Id of the PreValue to retrieve the value from</param>
/// <returns>PreValue as a string</returns>
public string GetPreValueAsString(int id)
{
using (var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(UowProvider.GetUnitOfWork()))
{
return repository.GetPreValueAsString(id);
}
}
/// <summary>
/// Saves an <see cref="IDataTypeDefinition"/>
/// </summary>
/// <param name="dataTypeDefinition"><see cref="IDataTypeDefinition"/> to save</param>
/// <param name="userId">Id of the user issueing the save</param>
public void Save(IDataTypeDefinition dataTypeDefinition, int userId = 0)
{
if (Saving.IsRaisedEventCancelled(new SaveEventArgs<IDataTypeDefinition>(dataTypeDefinition), this))
return;
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow))
{
dataTypeDefinition.CreatorId = userId;
repository.AddOrUpdate(dataTypeDefinition);
uow.Commit();
Saved.RaiseEvent(new SaveEventArgs<IDataTypeDefinition>(dataTypeDefinition, false), this);
}
Audit(AuditType.Save, string.Format("Save DataTypeDefinition performed by user"), userId, dataTypeDefinition.Id);
}
/// <summary>
/// Saves a collection of <see cref="IDataTypeDefinition"/>
/// </summary>
/// <param name="dataTypeDefinitions"><see cref="IDataTypeDefinition"/> to save</param>
/// <param name="userId">Id of the user issueing the save</param>
public void Save(IEnumerable<IDataTypeDefinition> dataTypeDefinitions, int userId = 0)
{
Save(dataTypeDefinitions, userId, true);
}
/// <summary>
/// Saves a collection of <see cref="IDataTypeDefinition"/>
/// </summary>
/// <param name="dataTypeDefinitions"><see cref="IDataTypeDefinition"/> to save</param>
/// <param name="userId">Id of the user issueing the save</param>
/// <param name="raiseEvents">Boolean indicating whether or not to raise events</param>
public void Save(IEnumerable<IDataTypeDefinition> dataTypeDefinitions, int userId, bool raiseEvents)
{
if (raiseEvents)
{
if (Saving.IsRaisedEventCancelled(new SaveEventArgs<IDataTypeDefinition>(dataTypeDefinitions), this))
return;
}
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow))
{
foreach (var dataTypeDefinition in dataTypeDefinitions)
{
dataTypeDefinition.CreatorId = userId;
repository.AddOrUpdate(dataTypeDefinition);
}
uow.Commit();
if (raiseEvents)
Saved.RaiseEvent(new SaveEventArgs<IDataTypeDefinition>(dataTypeDefinitions, false), this);
}
Audit(AuditType.Save, string.Format("Save DataTypeDefinition performed by user"), userId, -1);
}
/// <summary>
/// Saves a list of PreValues for a given DataTypeDefinition
/// </summary>
/// <param name="dataTypeId">Id of the DataTypeDefinition to save PreValues for</param>
/// <param name="values">List of string values to save</param>
[Obsolete("This should no longer be used, use the alternative SavePreValues or SaveDataTypeAndPreValues methods instead. This will only insert pre-values without keys")]
public void SavePreValues(int dataTypeId, IEnumerable<string> values)
{
//TODO: Should we raise an event here since we are really saving values for the data type?
using (var uow = UowProvider.GetUnitOfWork())
{
using (var transaction = uow.Database.GetTransaction())
{
var sortOrderObj =
uow.Database.ExecuteScalar<object>(
"SELECT max(sortorder) FROM cmsDataTypePreValues WHERE datatypeNodeId = @DataTypeId", new { DataTypeId = dataTypeId });
int sortOrder;
if (sortOrderObj == null || int.TryParse(sortOrderObj.ToString(), out sortOrder) == false)
{
sortOrder = 1;
}
foreach (var value in values)
{
var dto = new DataTypePreValueDto { DataTypeNodeId = dataTypeId, Value = value, SortOrder = sortOrder };
uow.Database.Insert(dto);
sortOrder++;
}
transaction.Complete();
}
}
}
/// <summary>
/// Saves/updates the pre-values
/// </summary>
/// <param name="dataTypeId"></param>
/// <param name="values"></param>
/// <remarks>
/// We need to actually look up each pre-value and maintain it's id if possible - this is because of silly property editors
/// like 'dropdown list publishing keys'
/// </remarks>
public void SavePreValues(int dataTypeId, IDictionary<string, PreValue> values)
{
var dtd = this.GetDataTypeDefinitionById(dataTypeId);
if (dtd == null)
{
throw new InvalidOperationException("No data type found for id " + dataTypeId);
}
SavePreValues(dtd, values);
}
/// <summary>
/// Saves/updates the pre-values
/// </summary>
/// <param name="dataTypeDefinition"></param>
/// <param name="values"></param>
/// <remarks>
/// We need to actually look up each pre-value and maintain it's id if possible - this is because of silly property editors
/// like 'dropdown list publishing keys'
/// </remarks>
public void SavePreValues(IDataTypeDefinition dataTypeDefinition, IDictionary<string, PreValue> values)
{
//TODO: Should we raise an event here since we are really saving values for the data type?
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow))
{
repository.AddOrUpdatePreValues(dataTypeDefinition, values);
uow.Commit();
}
}
/// <summary>
/// This will save a data type and it's pre-values in one transaction
/// </summary>
/// <param name="dataTypeDefinition"></param>
/// <param name="values"></param>
/// <param name="userId"></param>
public void SaveDataTypeAndPreValues(IDataTypeDefinition dataTypeDefinition, IDictionary<string, PreValue> values, int userId = 0)
{
if (Saving.IsRaisedEventCancelled(new SaveEventArgs<IDataTypeDefinition>(dataTypeDefinition), this))
return;
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow))
{
dataTypeDefinition.CreatorId = userId;
//add/update the dtd
repository.AddOrUpdate(dataTypeDefinition);
//add/update the prevalues
repository.AddOrUpdatePreValues(dataTypeDefinition, values);
uow.Commit();
Saved.RaiseEvent(new SaveEventArgs<IDataTypeDefinition>(dataTypeDefinition, false), this);
}
Audit(AuditType.Save, string.Format("Save DataTypeDefinition performed by user"), userId, dataTypeDefinition.Id);
}
/// <summary>
/// Deletes an <see cref="IDataTypeDefinition"/>
/// </summary>
/// <remarks>
/// Please note that deleting a <see cref="IDataTypeDefinition"/> will remove
/// all the <see cref="PropertyType"/> data that references this <see cref="IDataTypeDefinition"/>.
/// </remarks>
/// <param name="dataTypeDefinition"><see cref="IDataTypeDefinition"/> to delete</param>
/// <param name="userId">Optional Id of the user issueing the deletion</param>
public void Delete(IDataTypeDefinition dataTypeDefinition, int userId = 0)
{
if (Deleting.IsRaisedEventCancelled(new DeleteEventArgs<IDataTypeDefinition>(dataTypeDefinition), this))
return;
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow))
{
repository.Delete(dataTypeDefinition);
uow.Commit();
Deleted.RaiseEvent(new DeleteEventArgs<IDataTypeDefinition>(dataTypeDefinition, false), this);
}
Audit(AuditType.Delete, string.Format("Delete DataTypeDefinition performed by user"), userId, dataTypeDefinition.Id);
}
/// <summary>
/// Gets the <see cref="IDataType"/> specified by it's unique ID
/// </summary>
/// <param name="id">Id of the DataType, which corresponds to the Guid Id of the control</param>
/// <returns><see cref="IDataType"/> object</returns>
[Obsolete("IDataType is obsolete and is no longer used, it will be removed from the codebase in future versions")]
public IDataType GetDataTypeById(Guid id)
{
return DataTypesResolver.Current.GetById(id);
}
/// <summary>
/// Gets a complete list of all registered <see cref="IDataType"/>'s
/// </summary>
/// <returns>An enumerable list of <see cref="IDataType"/> objects</returns>
[Obsolete("IDataType is obsolete and is no longer used, it will be removed from the codebase in future versions")]
public IEnumerable<IDataType> GetAllDataTypes()
{
return DataTypesResolver.Current.DataTypes;
}
private void Audit(AuditType type, string message, int userId, int objectId)
{
var uow = UowProvider.GetUnitOfWork();
using (var auditRepo = RepositoryFactory.CreateAuditRepository(uow))
{
auditRepo.AddOrUpdate(new AuditItem(objectId, message, type, userId));
uow.Commit();
}
}
#region Event Handlers
/// <summary>
/// Occurs before Delete
/// </summary>
public static event TypedEventHandler<IDataTypeService, DeleteEventArgs<IDataTypeDefinition>> Deleting;
/// <summary>
/// Occurs after Delete
/// </summary>
public static event TypedEventHandler<IDataTypeService, DeleteEventArgs<IDataTypeDefinition>> Deleted;
/// <summary>
/// Occurs before Save
/// </summary>
public static event TypedEventHandler<IDataTypeService, SaveEventArgs<IDataTypeDefinition>> Saving;
/// <summary>
/// Occurs after Save
/// </summary>
public static event TypedEventHandler<IDataTypeService, SaveEventArgs<IDataTypeDefinition>> Saved;
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using NSubstitute.Core;
using NSubstitute.Core.Arguments;
using NSubstitute.Routing;
using NSubstitute.Specs.Infrastructure;
using NUnit.Framework;
namespace NSubstitute.Specs
{
public class CallRouterSpecs
{
public abstract class Concern : ConcernFor<CallRouter>
{
protected readonly object _returnValueFromRecordReplayRoute = "value from record replay route";
protected ISubstitutionContext _context;
protected ICall _call;
protected IConfigureCall ConfigureCall;
protected IRouteFactory _routeFactory;
protected IReceivedCalls _receivedCalls;
protected ISubstituteState _state;
public override void Context()
{
_context = mock<ISubstitutionContext>();
_call = mock<ICall>();
_state = mock<ISubstituteState>();
_receivedCalls = mock<IReceivedCalls>();
ConfigureCall = mock<IConfigureCall>();
_routeFactory = mock<IRouteFactory>();
_state.stub(x => x.ReceivedCalls).Return(_receivedCalls);
_state.stub(x => x.ConfigureCall).Return(ConfigureCall);
var recordReplayRoute = CreateRouteThatReturns(_returnValueFromRecordReplayRoute);
recordReplayRoute.stub(x => x.IsRecordReplayRoute).Return(true);
_routeFactory.stub(x => x.RecordReplay(_state)).Return(recordReplayRoute);
}
public override CallRouter CreateSubjectUnderTest()
{
return new CallRouter(_state, _context, _routeFactory);
}
protected IRoute CreateRouteThatReturns(object returnValue)
{
var route = mock<IRoute>();
route.stub(x => x.Handle(_call)).Return(returnValue);
return route;
}
}
public class When_a_route_is_set_and_a_member_is_called : Concern
{
readonly object _returnValueFromRoute = new object();
object _result;
IRoute _route;
[Test]
public void Should_update_last_call_router_on_substitution_context()
{
_context.received(x => x.LastCallRouter(sut));
}
[Test]
public void Should_send_call_to_route_and_return_response()
{
Assert.That(_result, Is.SameAs(_returnValueFromRoute));
}
[Test]
public void Should_send_next_call_to_record_replay_route_by_default()
{
var nextResult = sut.Route(_call);
Assert.That(nextResult, Is.EqualTo(_returnValueFromRecordReplayRoute));
}
public override void Because()
{
sut.SetRoute(x => _route);
_result = sut.Route(_call);
}
public override void Context()
{
base.Context();
_route = CreateRouteThatReturns(_returnValueFromRoute);
}
}
public class When_using_default_route : Concern
{
readonly object _returnValueFromRecordCallSpecRoute = "value from call spec route";
IRoute _recordCallSpecRoute;
[Test]
public void Should_record_call_spec_if_argument_matchers_have_been_specified_and_the_call_takes_arguments()
{
_call.stub(x => x.GetArguments()).Return(new object[4]);
_call.stub(x => x.GetArgumentSpecifications()).Return(CreateArgSpecs(3));
var result = sut.Route(_call);
Assert.That(result, Is.SameAs(_returnValueFromRecordCallSpecRoute));
}
[Test]
public void Should_record_call_and_replay_configured_result_if_this_looks_like_a_regular_call()
{
_call.stub(x => x.GetArguments()).Return(new object[4]);
_call.stub(x => x.GetArgumentSpecifications()).Return(CreateArgSpecs(0));
var result = sut.Route(_call);
Assert.That(result, Is.SameAs(_returnValueFromRecordReplayRoute));
}
[Test]
public void Should_record_call_and_replay_configured_result_if_there_are_arg_matchers_but_the_call_does_not_take_args()
{
_call.stub(x => x.GetArguments()).Return(new object[0]);
_call.stub(x => x.GetArgumentSpecifications()).Return(CreateArgSpecs(2));
var result = sut.Route(_call);
Assert.That(result, Is.SameAs(_returnValueFromRecordReplayRoute));
}
public override void Context()
{
base.Context();
_recordCallSpecRoute = CreateRouteThatReturns(_returnValueFromRecordCallSpecRoute);
_routeFactory.stub(x => x.RecordCallSpecification(_state)).Return(_recordCallSpecRoute);
}
IList<IArgumentSpecification> CreateArgSpecs(int count)
{
return Enumerable.Range(1, count).Select(x => mock<IArgumentSpecification>()).ToList();
}
}
public class When_setting_result_of_last_call : Concern
{
readonly MatchArgs _argMatching = MatchArgs.AsSpecifiedInCall;
IReturn _returnValue;
[Test]
public void Should_set_result()
{
ConfigureCall.received(x => x.SetResultForLastCall(_returnValue, _argMatching));
}
public override void Because()
{
sut.LastCallShouldReturn(_returnValue, _argMatching);
}
public override void Context()
{
base.Context();
_returnValue = mock<IReturn>();
}
}
public class When_clearing_received_calls : Concern
{
[Test]
public void Should_clear_calls()
{
_receivedCalls.received(x => x.Clear());
}
public override void Because()
{
sut.ClearReceivedCalls();
}
}
public class When_getting_received_calls : Concern
{
private IEnumerable<ICall> _result;
private IEnumerable<ICall> _allCalls;
[Test]
public void Should_return_all_calls()
{
Assert.That(_result, Is.SameAs(_allCalls));
}
public override void Because()
{
_result = sut.ReceivedCalls();
}
public override void Context()
{
base.Context();
_allCalls = new ICall[0];
_receivedCalls.stub(x => x.AllCalls()).Return(_allCalls);
}
}
public class When_handling_a_call_while_querying : Concern
{
private readonly object _resultFromQueryRoute = new object();
private object _result;
public override void Context()
{
base.Context();
_context.stub(x => x.IsQuerying).Return(true);
_routeFactory.stub(x => x.CallQuery(_state)).Return(CreateRouteThatReturns(_resultFromQueryRoute));
}
public override void Because()
{
_result = sut.Route(_call);
}
[Test]
public void Should_handle_via_query_route()
{
Assert.That(_result, Is.EqualTo(_resultFromQueryRoute));
}
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using PrimerProObjects;
using PrimerProLocalization;
namespace PrimerProForms
{
/// <summary>
/// Summary description for FormVowelInventory.
/// </summary>
public class FormVowelFeatures : System.Windows.Forms.Form
{
private System.Windows.Forms.GroupBox gbBackness;
private System.Windows.Forms.GroupBox gbHeight;
private System.Windows.Forms.CheckBox ckRound;
private System.Windows.Forms.CheckBox ckATR;
private System.Windows.Forms.CheckBox ckLong;
private System.Windows.Forms.CheckBox ckNasal;
private System.Windows.Forms.RadioButton rbFront;
private System.Windows.Forms.RadioButton rbCentral;
private System.Windows.Forms.RadioButton rbBack;
private System.Windows.Forms.RadioButton rbHigh;
private System.Windows.Forms.RadioButton rbMid;
private System.Windows.Forms.RadioButton rbLow;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Button btnCancel;
private System.ComponentModel.Container components = null;
private CheckBox ckVoiceless;
private CheckBox ckDiphthong;
private VowelFeatures m_Features;
public FormVowelFeatures(VowelFeatures vf)
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
m_Features = vf;
}
public FormVowelFeatures(VowelFeatures vf, LocalizationTable table)
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
m_Features = vf;
this.UpdateFormForLocalization(table);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormVowelFeatures));
this.gbBackness = new System.Windows.Forms.GroupBox();
this.rbBack = new System.Windows.Forms.RadioButton();
this.rbCentral = new System.Windows.Forms.RadioButton();
this.rbFront = new System.Windows.Forms.RadioButton();
this.gbHeight = new System.Windows.Forms.GroupBox();
this.rbLow = new System.Windows.Forms.RadioButton();
this.rbMid = new System.Windows.Forms.RadioButton();
this.rbHigh = new System.Windows.Forms.RadioButton();
this.ckRound = new System.Windows.Forms.CheckBox();
this.ckATR = new System.Windows.Forms.CheckBox();
this.ckLong = new System.Windows.Forms.CheckBox();
this.ckNasal = new System.Windows.Forms.CheckBox();
this.btnCancel = new System.Windows.Forms.Button();
this.btnOK = new System.Windows.Forms.Button();
this.ckVoiceless = new System.Windows.Forms.CheckBox();
this.ckDiphthong = new System.Windows.Forms.CheckBox();
this.gbBackness.SuspendLayout();
this.gbHeight.SuspendLayout();
this.SuspendLayout();
//
// gbBackness
//
this.gbBackness.Controls.Add(this.rbBack);
this.gbBackness.Controls.Add(this.rbCentral);
this.gbBackness.Controls.Add(this.rbFront);
this.gbBackness.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.gbBackness.Location = new System.Drawing.Point(20, 14);
this.gbBackness.Name = "gbBackness";
this.gbBackness.Size = new System.Drawing.Size(167, 97);
this.gbBackness.TabIndex = 0;
this.gbBackness.TabStop = false;
this.gbBackness.Text = "Backness Feature";
//
// rbBack
//
this.rbBack.AutoSize = true;
this.rbBack.Location = new System.Drawing.Point(7, 62);
this.rbBack.Name = "rbBack";
this.rbBack.Size = new System.Drawing.Size(52, 19);
this.rbBack.TabIndex = 2;
this.rbBack.Text = "&Back";
//
// rbCentral
//
this.rbCentral.AutoSize = true;
this.rbCentral.Cursor = System.Windows.Forms.Cursors.Default;
this.rbCentral.Location = new System.Drawing.Point(7, 42);
this.rbCentral.Name = "rbCentral";
this.rbCentral.Size = new System.Drawing.Size(64, 19);
this.rbCentral.TabIndex = 1;
this.rbCentral.Text = "&Central";
//
// rbFront
//
this.rbFront.AutoSize = true;
this.rbFront.Location = new System.Drawing.Point(7, 21);
this.rbFront.Name = "rbFront";
this.rbFront.Size = new System.Drawing.Size(53, 19);
this.rbFront.TabIndex = 0;
this.rbFront.Text = "Fron&t";
//
// gbHeight
//
this.gbHeight.Controls.Add(this.rbLow);
this.gbHeight.Controls.Add(this.rbMid);
this.gbHeight.Controls.Add(this.rbHigh);
this.gbHeight.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.gbHeight.Location = new System.Drawing.Point(20, 125);
this.gbHeight.Name = "gbHeight";
this.gbHeight.Size = new System.Drawing.Size(167, 97);
this.gbHeight.TabIndex = 1;
this.gbHeight.TabStop = false;
this.gbHeight.Text = "Height Feature";
//
// rbLow
//
this.rbLow.AutoSize = true;
this.rbLow.Location = new System.Drawing.Point(7, 62);
this.rbLow.Name = "rbLow";
this.rbLow.Size = new System.Drawing.Size(48, 19);
this.rbLow.TabIndex = 2;
this.rbLow.Text = "Lo&w";
//
// rbMid
//
this.rbMid.AutoSize = true;
this.rbMid.Location = new System.Drawing.Point(7, 42);
this.rbMid.Name = "rbMid";
this.rbMid.Size = new System.Drawing.Size(46, 19);
this.rbMid.TabIndex = 1;
this.rbMid.Text = "&Mid";
//
// rbHigh
//
this.rbHigh.AutoSize = true;
this.rbHigh.Location = new System.Drawing.Point(7, 21);
this.rbHigh.Name = "rbHigh";
this.rbHigh.Size = new System.Drawing.Size(51, 19);
this.rbHigh.TabIndex = 0;
this.rbHigh.Text = "&High";
//
// ckRound
//
this.ckRound.AutoSize = true;
this.ckRound.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ckRound.Location = new System.Drawing.Point(208, 35);
this.ckRound.Name = "ckRound";
this.ckRound.Size = new System.Drawing.Size(63, 19);
this.ckRound.TabIndex = 2;
this.ckRound.Text = "&Round";
//
// ckATR
//
this.ckATR.AutoSize = true;
this.ckATR.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ckATR.Location = new System.Drawing.Point(208, 69);
this.ckATR.Name = "ckATR";
this.ckATR.Size = new System.Drawing.Size(56, 19);
this.ckATR.TabIndex = 3;
this.ckATR.Text = "&+ATR";
//
// ckLong
//
this.ckLong.AutoSize = true;
this.ckLong.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ckLong.Location = new System.Drawing.Point(208, 104);
this.ckLong.Name = "ckLong";
this.ckLong.Size = new System.Drawing.Size(54, 19);
this.ckLong.TabIndex = 4;
this.ckLong.Text = "Lon&g";
//
// ckNasal
//
this.ckNasal.AutoSize = true;
this.ckNasal.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ckNasal.Location = new System.Drawing.Point(208, 139);
this.ckNasal.Name = "ckNasal";
this.ckNasal.Size = new System.Drawing.Size(58, 19);
this.ckNasal.TabIndex = 5;
this.ckNasal.Text = "Nasa&l";
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnCancel.Location = new System.Drawing.Point(224, 246);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(83, 28);
this.btnCancel.TabIndex = 9;
this.btnCancel.Text = "Cancel";
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// btnOK
//
this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnOK.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnOK.Location = new System.Drawing.Point(124, 246);
this.btnOK.Name = "btnOK";
this.btnOK.Size = new System.Drawing.Size(83, 28);
this.btnOK.TabIndex = 8;
this.btnOK.Text = "OK";
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
//
// ckVoiceless
//
this.ckVoiceless.AutoSize = true;
this.ckVoiceless.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ckVoiceless.Location = new System.Drawing.Point(208, 173);
this.ckVoiceless.Name = "ckVoiceless";
this.ckVoiceless.Size = new System.Drawing.Size(78, 19);
this.ckVoiceless.TabIndex = 6;
this.ckVoiceless.Text = "Voiceless";
this.ckVoiceless.UseVisualStyleBackColor = true;
//
// ckDiphthong
//
this.ckDiphthong.AutoSize = true;
this.ckDiphthong.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ckDiphthong.Location = new System.Drawing.Point(208, 208);
this.ckDiphthong.Name = "ckDiphthong";
this.ckDiphthong.Size = new System.Drawing.Size(83, 19);
this.ckDiphthong.TabIndex = 7;
this.ckDiphthong.Text = "Diphthong";
this.ckDiphthong.UseVisualStyleBackColor = true;
//
// FormVowelFeatures
//
this.AcceptButton = this.btnOK;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.btnCancel;
this.ClientSize = new System.Drawing.Size(404, 330);
this.Controls.Add(this.ckVoiceless);
this.Controls.Add(this.ckDiphthong);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.ckNasal);
this.Controls.Add(this.ckLong);
this.Controls.Add(this.ckATR);
this.Controls.Add(this.ckRound);
this.Controls.Add(this.gbHeight);
this.Controls.Add(this.gbBackness);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "FormVowelFeatures";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Set Vowel Features";
this.gbBackness.ResumeLayout(false);
this.gbBackness.PerformLayout();
this.gbHeight.ResumeLayout(false);
this.gbHeight.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
public VowelFeatures Features
{
get {return m_Features;}
}
private void btnOK_Click(object sender, System.EventArgs e)
{
if (rbFront.Checked)
m_Features.Backness = VowelFeatures.kFront;
if (rbCentral.Checked)
m_Features.Backness = VowelFeatures.kCentral;
if (rbBack.Checked)
m_Features.Backness = VowelFeatures.kBack;
if (rbHigh.Checked)
m_Features.Height = VowelFeatures.kHigh;
if (rbMid.Checked)
m_Features.Height = VowelFeatures.kMid;
if (rbLow.Checked)
m_Features.Height = VowelFeatures.kLow;
m_Features.Round = ckRound.Checked;
m_Features.PlusAtr = ckATR.Checked;
m_Features.Long = ckLong.Checked;
m_Features.Nasal = ckNasal.Checked;
m_Features.Diphthong = ckDiphthong.Checked;
m_Features.Voiceless = ckVoiceless.Checked;
}
private void btnCancel_Click(object sender, System.EventArgs e)
{
m_Features = null;
this.Close();
}
private void UpdateFormForLocalization(LocalizationTable table)
{
string strText = "";
strText = table.GetForm("FormVowelFeaturesT");
if (strText != "")
this.Text = strText;
strText = table.GetForm("FormVowelFeatures0");
if (strText != "")
this.gbBackness.Text = strText;
strText = table.GetForm("FormVowelFeaturesB0");
if (strText != "")
this.rbFront.Text = strText;
strText = table.GetForm("FormVowelFeaturesB1");
if (strText != "")
this.rbCentral.Text = strText;
strText = table.GetForm("FormVowelFeaturesB2");
if (strText != "")
this.rbBack.Text = strText;
strText = table.GetForm("FormVowelFeatures1");
if (strText != "")
this.gbHeight.Text = strText;
strText = table.GetForm("FormVowelFeaturesH0");
if (strText != "")
this.rbHigh.Text = strText;
strText = table.GetForm("FormVowelFeaturesH1");
if (strText != "")
this.rbMid.Text = strText;
strText = table.GetForm("FormVowelFeaturesH2");
if (strText != "")
this.rbLow.Text = strText;
strText = table.GetForm("FormVowelFeatures2");
if (strText != "")
this.ckRound.Text = strText;
strText = table.GetForm("FormVowelFeatures3");
if (strText != "")
this.ckATR.Text = strText;
strText = table.GetForm("FormVowelFeatures4");
if (strText != "")
this.ckLong.Text = strText;
strText = table.GetForm("FormVowelFeatures5");
if (strText != "")
this.ckNasal.Text = strText;
strText = table.GetForm("FormVowelFeatures6");
if (strText != "")
this.ckVoiceless.Text = strText;
strText = table.GetForm("FormVowelFeatures7");
if (strText != "")
this.ckDiphthong.Text = strText;
strText = table.GetForm("FormVowelFeatures8");
if (strText != "")
this.btnOK.Text = strText;
strText = table.GetForm("FormVowelFeatures9");
if (strText != "")
this.btnCancel.Text = strText;
return;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Data.SqlClient;
namespace System.Data.Common
{
internal sealed class ReadOnlyCollection<T> : System.Collections.ICollection, ICollection<T>
{
private readonly T[] _items;
internal ReadOnlyCollection(T[] items)
{
_items = items;
#if DEBUG
for (int i = 0; i < items.Length; ++i)
{
Debug.Assert(null != items[i], "null item");
}
#endif
}
public void CopyTo(T[] array, int arrayIndex)
{
Array.Copy(_items, 0, array, arrayIndex, _items.Length);
}
void System.Collections.ICollection.CopyTo(Array array, int arrayIndex)
{
Array.Copy(_items, 0, array, arrayIndex, _items.Length);
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new Enumerator<T>(_items);
}
public System.Collections.IEnumerator GetEnumerator()
{
return new Enumerator<T>(_items);
}
bool System.Collections.ICollection.IsSynchronized
{
get { return false; }
}
object System.Collections.ICollection.SyncRoot
{
get { return _items; }
}
bool ICollection<T>.IsReadOnly
{
get { return true; }
}
void ICollection<T>.Add(T value)
{
throw new NotSupportedException();
}
void ICollection<T>.Clear()
{
throw new NotSupportedException();
}
bool ICollection<T>.Contains(T value)
{
return Array.IndexOf(_items, value) >= 0;
}
bool ICollection<T>.Remove(T value)
{
throw new NotSupportedException();
}
public int Count
{
get { return _items.Length; }
}
internal struct Enumerator<K> : IEnumerator<K>, System.Collections.IEnumerator
{ // based on List<T>.Enumerator
private readonly K[] _items;
private int _index;
internal Enumerator(K[] items)
{
_items = items;
_index = -1;
}
public void Dispose()
{
}
public bool MoveNext()
{
return (++_index < _items.Length);
}
public K Current
{
get
{
return _items[_index];
}
}
object System.Collections.IEnumerator.Current
{
get
{
return _items[_index];
}
}
void System.Collections.IEnumerator.Reset()
{
_index = -1;
}
}
}
internal static class DbConnectionStringBuilderUtil
{
internal static bool ConvertToBoolean(object value)
{
Debug.Assert(null != value, "ConvertToBoolean(null)");
string svalue = (value as string);
if (null != svalue)
{
if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "true") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "yes"))
return true;
else if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "false") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "no"))
return false;
else
{
string tmp = svalue.Trim(); // Remove leading & trailing white space.
if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "true") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "yes"))
return true;
else if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "false") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "no"))
return false;
}
return bool.Parse(svalue);
}
try
{
return ((IConvertible)value).ToBoolean(CultureInfo.InvariantCulture);
}
catch (InvalidCastException e)
{
throw ADP.ConvertFailed(value.GetType(), typeof(bool), e);
}
}
internal static int ConvertToInt32(object value)
{
try
{
return ((IConvertible)value).ToInt32(CultureInfo.InvariantCulture);
}
catch (InvalidCastException e)
{
throw ADP.ConvertFailed(value.GetType(), typeof(int), e);
}
}
internal static string ConvertToString(object value)
{
try
{
return ((IConvertible)value).ToString(CultureInfo.InvariantCulture);
}
catch (InvalidCastException e)
{
throw ADP.ConvertFailed(value.GetType(), typeof(string), e);
}
}
}
internal static class DbConnectionStringDefaults
{
// OleDb
internal const string FileName = "";
internal const int OleDbServices = ~(/*DBPROPVAL_OS_AGR_AFTERSESSION*/0x00000008 | /*DBPROPVAL_OS_CLIENTCURSOR*/0x00000004); // -13
internal const string Provider = "";
internal const int ConnectTimeout = 15;
internal const bool PersistSecurityInfo = false;
internal const string DataSource = "";
}
internal static class DbConnectionOptionKeywords
{
// Odbc
internal const string Driver = "driver";
internal const string Pwd = "pwd";
internal const string UID = "uid";
// OleDb
internal const string DataProvider = "data provider";
internal const string ExtendedProperties = "extended properties";
internal const string FileName = "file name";
internal const string Provider = "provider";
internal const string RemoteProvider = "remote provider";
// common keywords (OleDb, OracleClient, SqlClient)
internal const string Password = "password";
internal const string UserID = "user id";
}
internal static class DbConnectionStringKeywords
{
// Odbc
internal const string Driver = "Driver";
// OleDb
internal const string FileName = "File Name";
internal const string OleDbServices = "OLE DB Services";
internal const string Provider = "Provider";
internal const string DataSource = "Data Source";
internal const string PersistSecurityInfo = "Persist Security Info";
}
}
| |
// 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.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using MSBuild = Microsoft.Build.Evaluation;
using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants;
using VsCommands = Microsoft.VisualStudio.VSConstants.VSStd97CmdID;
using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID;
#if DEV14_OR_LATER
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
#endif
namespace Microsoft.VisualStudioTools.Project {
[ComVisible(true)]
internal class ReferenceContainerNode : HierarchyNode, IReferenceContainer {
private EventHandler<HierarchyNodeEventArgs> onChildAdded;
private EventHandler<HierarchyNodeEventArgs> onChildRemoved;
internal const string ReferencesNodeVirtualName = "References";
#region ctor
internal ReferenceContainerNode(ProjectNode root)
: base(root) {
this.ExcludeNodeFromScc = true;
}
#endregion
#region Properties
private static string[] supportedReferenceTypes = new string[] {
ProjectFileConstants.ProjectReference,
ProjectFileConstants.Reference,
ProjectFileConstants.COMReference,
ProjectFileConstants.WebPiReference
};
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
protected virtual string[] SupportedReferenceTypes {
get { return supportedReferenceTypes; }
}
#endregion
#region overridden properties
public override int SortPriority {
get {
return DefaultSortOrderNode.ReferenceContainerNode;
}
}
public override int MenuCommandId {
get { return VsMenus.IDM_VS_CTXT_REFERENCEROOT; }
}
public override Guid ItemTypeGuid {
get { return VSConstants.GUID_ItemType_VirtualFolder; }
}
public override string Url {
get { return ReferencesNodeVirtualName; }
}
public override string Caption {
get {
return SR.GetString(SR.ReferencesNodeName);
}
}
private Automation.OAReferences references;
internal override object Object {
get {
if (null == references) {
references = new Automation.OAReferences(this, ProjectMgr);
}
return references;
}
}
#endregion
#region overridden methods
/// <summary>
/// Returns an instance of the automation object for ReferenceContainerNode
/// </summary>
/// <returns>An intance of the Automation.OAReferenceFolderItem type if succeeeded</returns>
public override object GetAutomationObject() {
if (this.ProjectMgr == null || this.ProjectMgr.IsClosed) {
return null;
}
return new Automation.OAReferenceFolderItem(this.ProjectMgr.GetAutomationObject() as Automation.OAProject, this);
}
/// <summary>
/// Disable inline editing of Caption of a ReferendeContainerNode
/// </summary>
/// <returns>null</returns>
public override string GetEditLabel() {
return null;
}
#if DEV14_OR_LATER
protected override bool SupportsIconMonikers {
get { return true; }
}
protected override ImageMoniker GetIconMoniker(bool open) {
return KnownMonikers.Reference;
}
#else
public override int ImageIndex {
get {
return ProjectMgr.GetIconIndex(ProjectNode.ImageName.ReferenceFolder);
}
}
#endif
/// <summary>
/// References node cannot be dragged.
/// </summary>
/// <returns>A stringbuilder.</returns>
protected internal override string PrepareSelectedNodesForClipBoard() {
return null;
}
/// <summary>
/// Not supported.
/// </summary>
internal override int ExcludeFromProject() {
return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED;
}
internal override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result) {
if (cmdGroup == VsMenus.guidStandardCommandSet97) {
switch ((VsCommands)cmd) {
case VsCommands.AddNewItem:
case VsCommands.AddExistingItem:
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
} else if (cmdGroup == VsMenus.guidStandardCommandSet2K) {
if ((VsCommands2K)cmd == VsCommands2K.ADDREFERENCE) {
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
} else {
return (int)OleConstants.OLECMDERR_E_UNKNOWNGROUP;
}
return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result);
}
internal override int ExecCommandOnNode(Guid cmdGroup, uint cmd, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) {
if (cmdGroup == VsMenus.guidStandardCommandSet2K) {
switch ((VsCommands2K)cmd) {
case VsCommands2K.ADDREFERENCE:
return this.ProjectMgr.AddProjectReference();
#if FALSE
case VsCommands2K.ADDWEBREFERENCE:
return this.ProjectMgr.AddWebReference();
#endif
}
}
return base.ExecCommandOnNode(cmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut);
}
internal override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation) {
return false;
}
/// <summary>
/// Defines whether this node is valid node for painting the refererences icon.
/// </summary>
/// <returns></returns>
protected override bool CanShowDefaultIcon() {
return true;
}
#endregion
#region IReferenceContainer
public IList<ReferenceNode> EnumReferences() {
List<ReferenceNode> refs = new List<ReferenceNode>();
for (HierarchyNode node = this.FirstChild; node != null; node = node.NextSibling) {
ReferenceNode refNode = node as ReferenceNode;
if (refNode != null) {
refs.Add(refNode);
}
}
return refs;
}
/// <summary>
/// Adds references to this container from a MSBuild project.
/// </summary>
public void LoadReferencesFromBuildProject(MSBuild.Project buildProject) {
ProjectMgr.Site.GetUIThread().MustBeCalledFromUIThread();
foreach (string referenceType in SupportedReferenceTypes) {
IEnumerable<MSBuild.ProjectItem> referencesGroup = this.ProjectMgr.BuildProject.GetItems(referenceType);
bool isAssemblyReference = referenceType == ProjectFileConstants.Reference;
// If the project was loaded for browsing we should still create the nodes but as not resolved.
if (isAssemblyReference &&
(!ProjectMgr.BuildProject.Targets.ContainsKey(MsBuildTarget.ResolveAssemblyReferences) || this.ProjectMgr.Build(MsBuildTarget.ResolveAssemblyReferences) != MSBuildResult.Successful)) {
continue;
}
foreach (MSBuild.ProjectItem item in referencesGroup) {
ProjectElement element = new MsBuildProjectElement(this.ProjectMgr, item);
ReferenceNode node = CreateReferenceNode(referenceType, element);
if (node != null) {
// Make sure that we do not want to add the item twice to the ui hierarchy
// We are using here the UI representation of the Node namely the Caption to find that out, in order to
// avoid different representation problems.
// Example :<Reference Include="EnvDTE80, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
// <Reference Include="EnvDTE80" />
bool found = false;
for (HierarchyNode n = this.FirstChild; n != null && !found; n = n.NextSibling) {
if (String.Compare(n.Caption, node.Caption, StringComparison.OrdinalIgnoreCase) == 0) {
found = true;
}
}
if (!found) {
this.AddChild(node);
}
}
}
}
}
/// <summary>
/// Adds a reference to this container using the selector data structure to identify it.
/// </summary>
/// <param name="selectorData">data describing selected component</param>
/// <returns>Reference in case of a valid reference node has been created. Otherwise null</returns>
public ReferenceNode AddReferenceFromSelectorData(VSCOMPONENTSELECTORDATA selectorData) {
//Make sure we can edit the project file
if (!this.ProjectMgr.QueryEditProjectFile(false)) {
throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
}
//Create the reference node
ReferenceNode node = null;
try {
node = CreateReferenceNode(selectorData);
} catch (ArgumentException) {
// Some selector data was not valid.
}
//Add the reference node to the project if we have a valid reference node
if (node != null) {
// This call will find if the reference is in the project and, in this case
// will not add it again, so the parent node will not be set.
node.AddReference();
if (null == node.Parent) {
// The reference was not added, so we can not return this item because it
// is not inside the project.
return null;
}
var added = onChildAdded;
if (added != null) {
onChildAdded(this, new HierarchyNodeEventArgs(node));
}
}
return node;
}
#endregion
#region virtual methods
protected virtual ReferenceNode CreateReferenceNode(string referenceType, ProjectElement element) {
ReferenceNode node = null;
#if FALSE
if(referenceType == ProjectFileConstants.COMReference)
{
node = this.CreateComReferenceNode(element);
}
else
#endif
if (referenceType == ProjectFileConstants.Reference) {
node = this.CreateAssemblyReferenceNode(element);
} else if (referenceType == ProjectFileConstants.ProjectReference) {
node = this.CreateProjectReferenceNode(element);
}
return node;
}
protected virtual ReferenceNode CreateReferenceNode(VSCOMPONENTSELECTORDATA selectorData) {
ReferenceNode node = null;
switch (selectorData.type) {
case VSCOMPONENTTYPE.VSCOMPONENTTYPE_Project:
node = this.CreateProjectReferenceNode(selectorData);
break;
case VSCOMPONENTTYPE.VSCOMPONENTTYPE_File:
// This is the case for managed assembly
case VSCOMPONENTTYPE.VSCOMPONENTTYPE_ComPlus:
node = this.CreateFileComponent(selectorData);
break;
#if FALSE
case VSCOMPONENTTYPE.VSCOMPONENTTYPE_Com2:
node = this.CreateComReferenceNode(selectorData);
break;
#endif
}
return node;
}
#endregion
#region Helper functions to add references
/// <summary>
/// Creates a project reference node given an existing project element.
/// </summary>
protected virtual ProjectReferenceNode CreateProjectReferenceNode(ProjectElement element) {
return new ProjectReferenceNode(this.ProjectMgr, element);
}
/// <summary>
/// Create a Project to Project reference given a VSCOMPONENTSELECTORDATA structure
/// </summary>
protected virtual ProjectReferenceNode CreateProjectReferenceNode(VSCOMPONENTSELECTORDATA selectorData) {
return new ProjectReferenceNode(this.ProjectMgr, selectorData.bstrTitle, selectorData.bstrFile, selectorData.bstrProjRef);
}
/// <summary>
/// Creates an assemby or com reference node given a selector data.
/// </summary>
protected virtual ReferenceNode CreateFileComponent(VSCOMPONENTSELECTORDATA selectorData) {
if (null == selectorData.bstrFile) {
throw new ArgumentNullException("selectorData");
}
// We have a path to a file, it could be anything
// First see if it is a managed assembly
bool tryToCreateAnAssemblyReference = true;
if (File.Exists(selectorData.bstrFile)) {
try {
// We should not load the assembly in the current appdomain.
// If we do not do it like that and we load the assembly in the current appdomain then the assembly cannot be unloaded again.
// The following problems might arose in that case.
// 1. Assume that a user is extending the MPF and his project is creating a managed assembly dll.
// 2. The user opens VS and creates a project and builds it.
// 3. Then the user opens VS creates another project and adds a reference to the previously built assembly. This will load the assembly in the appdomain had we been using Assembly.ReflectionOnlyLoadFrom.
// 4. Then he goes back to the first project modifies it an builds it. A build error is issued that the assembly is used.
// GetAssemblyName is assured not to load the assembly.
tryToCreateAnAssemblyReference = (AssemblyName.GetAssemblyName(selectorData.bstrFile) != null);
} catch (BadImageFormatException) {
// We have found the file and it is not a .NET assembly; no need to try to
// load it again.
tryToCreateAnAssemblyReference = false;
} catch (FileLoadException) {
// We must still try to load from here because this exception is thrown if we want
// to add the same assembly refererence from different locations.
tryToCreateAnAssemblyReference = true;
}
}
ReferenceNode node = null;
if (tryToCreateAnAssemblyReference) {
// This might be a candidate for an assembly reference node. Try to load it.
// CreateAssemblyReferenceNode will suppress BadImageFormatException if the node cannot be created.
node = this.CreateAssemblyReferenceNode(selectorData.bstrFile);
}
// If no node has been created try to create a com reference node.
if (node == null) {
if (!File.Exists(selectorData.bstrFile)) {
return null;
}
node = ProjectMgr.CreateReferenceNodeForFile(selectorData.bstrFile);
}
return node;
}
/// <summary>
/// Creates an assembly refernce node from a project element.
/// </summary>
protected virtual AssemblyReferenceNode CreateAssemblyReferenceNode(ProjectElement element) {
AssemblyReferenceNode node = null;
try {
node = new AssemblyReferenceNode(this.ProjectMgr, element);
} catch (ArgumentNullException e) {
Trace.WriteLine("Exception : " + e.Message);
} catch (FileNotFoundException e) {
Trace.WriteLine("Exception : " + e.Message);
} catch (BadImageFormatException e) {
Trace.WriteLine("Exception : " + e.Message);
} catch (FileLoadException e) {
Trace.WriteLine("Exception : " + e.Message);
} catch (System.Security.SecurityException e) {
Trace.WriteLine("Exception : " + e.Message);
}
return node;
}
/// <summary>
/// Creates an assembly reference node from a file path.
/// </summary>
protected virtual AssemblyReferenceNode CreateAssemblyReferenceNode(string fileName) {
AssemblyReferenceNode node = null;
try {
node = new AssemblyReferenceNode(this.ProjectMgr, fileName);
} catch (ArgumentNullException e) {
Trace.WriteLine("Exception : " + e.Message);
} catch (FileNotFoundException e) {
Trace.WriteLine("Exception : " + e.Message);
} catch (BadImageFormatException e) {
Trace.WriteLine("Exception : " + e.Message);
} catch (FileLoadException e) {
Trace.WriteLine("Exception : " + e.Message);
} catch (System.Security.SecurityException e) {
Trace.WriteLine("Exception : " + e.Message);
}
return node;
}
#endregion
internal event EventHandler<HierarchyNodeEventArgs> OnChildAdded {
add { onChildAdded += value; }
remove { onChildAdded -= value; }
}
internal event EventHandler<HierarchyNodeEventArgs> OnChildRemoved {
add { onChildRemoved += value; }
remove { onChildRemoved -= value; }
}
internal void FireChildAdded(ReferenceNode referenceNode) {
var added = onChildAdded;
if (added != null) {
added(this, new HierarchyNodeEventArgs(referenceNode));
}
}
internal void FireChildRemoved(ReferenceNode referenceNode) {
var removed = onChildRemoved;
if (removed != null) {
removed(this, new HierarchyNodeEventArgs(referenceNode));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using Avalonia.Platform.Interop;
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable FieldCanBeMadeReadOnly.Global
// ReSharper disable CommentTypo
// ReSharper disable UnusedMember.Global
// ReSharper disable IdentifierTypo
// ReSharper disable NotAccessedField.Global
// ReSharper disable UnusedMethodReturnValue.Global
namespace Avalonia.X11
{
internal unsafe static class XLib
{
const string libX11 = "libX11.so.6";
const string libX11Randr = "libXrandr.so.2";
const string libX11Ext = "libXext.so.6";
const string libXInput = "libXi.so.6";
const string libXCursor = "libXcursor.so.1";
[DllImport(libX11)]
public static extern IntPtr XOpenDisplay(IntPtr display);
[DllImport(libX11)]
public static extern int XCloseDisplay(IntPtr display);
[DllImport(libX11)]
public static extern IntPtr XSynchronize(IntPtr display, bool onoff);
[DllImport(libX11)]
public static extern IntPtr XCreateWindow(IntPtr display, IntPtr parent, int x, int y, int width, int height,
int border_width, int depth, int xclass, IntPtr visual, UIntPtr valuemask,
ref XSetWindowAttributes attributes);
[DllImport(libX11)]
public static extern IntPtr XCreateSimpleWindow(IntPtr display, IntPtr parent, int x, int y, int width,
int height, int border_width, IntPtr border, IntPtr background);
[DllImport(libX11)]
public static extern int XMapWindow(IntPtr display, IntPtr window);
[DllImport(libX11)]
public static extern int XUnmapWindow(IntPtr display, IntPtr window);
[DllImport(libX11)]
public static extern int XMapSubindows(IntPtr display, IntPtr window);
[DllImport(libX11)]
public static extern int XUnmapSubwindows(IntPtr display, IntPtr window);
[DllImport(libX11)]
public static extern IntPtr XRootWindow(IntPtr display, int screen_number);
[DllImport(libX11)]
public static extern IntPtr XDefaultRootWindow(IntPtr display);
[DllImport(libX11)]
public static extern IntPtr XNextEvent(IntPtr display, out XEvent xevent);
[DllImport(libX11)]
public static extern IntPtr XNextEvent(IntPtr display, XEvent* xevent);
[DllImport(libX11)]
public static extern int XConnectionNumber(IntPtr diplay);
[DllImport(libX11)]
public static extern int XPending(IntPtr diplay);
[DllImport(libX11)]
public static extern IntPtr XSelectInput(IntPtr display, IntPtr window, IntPtr mask);
[DllImport(libX11)]
public static extern int XDestroyWindow(IntPtr display, IntPtr window);
[DllImport(libX11)]
public static extern int XReparentWindow(IntPtr display, IntPtr window, IntPtr parent, int x, int y);
[DllImport(libX11)]
public static extern int XMoveResizeWindow(IntPtr display, IntPtr window, int x, int y, int width, int height);
[DllImport(libX11)]
public static extern int XResizeWindow(IntPtr display, IntPtr window, int width, int height);
[DllImport(libX11)]
public static extern int XGetWindowAttributes(IntPtr display, IntPtr window, ref XWindowAttributes attributes);
[DllImport(libX11)]
public static extern int XFlush(IntPtr display);
[DllImport(libX11)]
public static extern int XSetWMName(IntPtr display, IntPtr window, ref XTextProperty text_prop);
[DllImport(libX11)]
public static extern int XStoreName(IntPtr display, IntPtr window, string window_name);
[DllImport(libX11)]
public static extern int XFetchName(IntPtr display, IntPtr window, ref IntPtr window_name);
[DllImport(libX11)]
public static extern int XSendEvent(IntPtr display, IntPtr window, bool propagate, IntPtr event_mask,
ref XEvent send_event);
[DllImport(libX11)]
public static extern int XQueryTree(IntPtr display, IntPtr window, out IntPtr root_return,
out IntPtr parent_return, out IntPtr children_return, out int nchildren_return);
[DllImport(libX11)]
public static extern int XFree(IntPtr data);
[DllImport(libX11)]
public static extern int XRaiseWindow(IntPtr display, IntPtr window);
[DllImport(libX11)]
public static extern uint XLowerWindow(IntPtr display, IntPtr window);
[DllImport(libX11)]
public static extern uint XConfigureWindow(IntPtr display, IntPtr window, ChangeWindowFlags value_mask,
ref XWindowChanges values);
public static uint XConfigureResizeWindow(IntPtr display, IntPtr window, PixelSize size)
=> XConfigureResizeWindow(display, window, size.Width, size.Height);
public static uint XConfigureResizeWindow(IntPtr display, IntPtr window, int width, int height)
{
var changes = new XWindowChanges
{
width = width,
height = height
};
return XConfigureWindow(display, window, ChangeWindowFlags.CWHeight | ChangeWindowFlags.CWWidth,
ref changes);
}
[DllImport(libX11)]
public static extern IntPtr XInternAtom(IntPtr display, string atom_name, bool only_if_exists);
[DllImport(libX11)]
public static extern int XInternAtoms(IntPtr display, string[] atom_names, int atom_count, bool only_if_exists,
IntPtr[] atoms);
[DllImport(libX11)]
public static extern IntPtr XGetAtomName(IntPtr display, IntPtr atom);
public static string GetAtomName(IntPtr display, IntPtr atom)
{
var ptr = XGetAtomName(display, atom);
if (ptr == IntPtr.Zero)
return null;
var s = Marshal.PtrToStringAnsi(ptr);
XFree(ptr);
return s;
}
[DllImport(libX11)]
public static extern int XSetWMProtocols(IntPtr display, IntPtr window, IntPtr[] protocols, int count);
[DllImport(libX11)]
public static extern int XGrabPointer(IntPtr display, IntPtr window, bool owner_events, EventMask event_mask,
GrabMode pointer_mode, GrabMode keyboard_mode, IntPtr confine_to, IntPtr cursor, IntPtr timestamp);
[DllImport(libX11)]
public static extern int XUngrabPointer(IntPtr display, IntPtr timestamp);
[DllImport(libX11)]
public static extern bool XQueryPointer(IntPtr display, IntPtr window, out IntPtr root, out IntPtr child,
out int root_x, out int root_y, out int win_x, out int win_y, out int keys_buttons);
[DllImport(libX11)]
public static extern bool XTranslateCoordinates(IntPtr display, IntPtr src_w, IntPtr dest_w, int src_x,
int src_y, out int intdest_x_return, out int dest_y_return, out IntPtr child_return);
[DllImport(libX11)]
public static extern bool XGetGeometry(IntPtr display, IntPtr window, out IntPtr root, out int x, out int y,
out int width, out int height, out int border_width, out int depth);
[DllImport(libX11)]
public static extern bool XGetGeometry(IntPtr display, IntPtr window, IntPtr root, out int x, out int y,
out int width, out int height, IntPtr border_width, IntPtr depth);
[DllImport(libX11)]
public static extern bool XGetGeometry(IntPtr display, IntPtr window, IntPtr root, out int x, out int y,
IntPtr width, IntPtr height, IntPtr border_width, IntPtr depth);
[DllImport(libX11)]
public static extern bool XGetGeometry(IntPtr display, IntPtr window, IntPtr root, IntPtr x, IntPtr y,
out int width, out int height, IntPtr border_width, IntPtr depth);
[DllImport(libX11)]
public static extern uint XWarpPointer(IntPtr display, IntPtr src_w, IntPtr dest_w, int src_x, int src_y,
uint src_width, uint src_height, int dest_x, int dest_y);
[DllImport(libX11)]
public static extern int XClearWindow(IntPtr display, IntPtr window);
[DllImport(libX11)]
public static extern int XClearArea(IntPtr display, IntPtr window, int x, int y, int width, int height,
bool exposures);
// Colormaps
[DllImport(libX11)]
public static extern IntPtr XDefaultScreenOfDisplay(IntPtr display);
[DllImport(libX11)]
public static extern int XScreenNumberOfScreen(IntPtr display, IntPtr Screen);
[DllImport(libX11)]
public static extern IntPtr XDefaultVisual(IntPtr display, int screen_number);
[DllImport(libX11)]
public static extern uint XDefaultDepth(IntPtr display, int screen_number);
[DllImport(libX11)]
public static extern int XDefaultScreen(IntPtr display);
[DllImport(libX11)]
public static extern IntPtr XDefaultColormap(IntPtr display, int screen_number);
[DllImport(libX11)]
public static extern int XLookupColor(IntPtr display, IntPtr Colormap, string Coloranem,
ref XColor exact_def_color, ref XColor screen_def_color);
[DllImport(libX11)]
public static extern int XAllocColor(IntPtr display, IntPtr Colormap, ref XColor colorcell_def);
[DllImport(libX11)]
public static extern int XSetTransientForHint(IntPtr display, IntPtr window, IntPtr parent);
[DllImport(libX11)]
public static extern int XChangeProperty(IntPtr display, IntPtr window, IntPtr property, IntPtr type,
int format, PropertyMode mode, ref MotifWmHints data, int nelements);
[DllImport(libX11)]
public static extern int XChangeProperty(IntPtr display, IntPtr window, IntPtr property, IntPtr type,
int format, PropertyMode mode, ref uint value, int nelements);
[DllImport(libX11)]
public static extern int XChangeProperty(IntPtr display, IntPtr window, IntPtr property, IntPtr type,
int format, PropertyMode mode, ref IntPtr value, int nelements);
[DllImport(libX11)]
public static extern int XChangeProperty(IntPtr display, IntPtr window, IntPtr property, IntPtr type,
int format, PropertyMode mode, byte[] data, int nelements);
[DllImport(libX11)]
public static extern int XChangeProperty(IntPtr display, IntPtr window, IntPtr property, IntPtr type,
int format, PropertyMode mode, uint[] data, int nelements);
[DllImport(libX11)]
public static extern int XChangeProperty(IntPtr display, IntPtr window, IntPtr property, IntPtr type,
int format, PropertyMode mode, int[] data, int nelements);
[DllImport(libX11)]
public static extern int XChangeProperty(IntPtr display, IntPtr window, IntPtr property, IntPtr type,
int format, PropertyMode mode, IntPtr[] data, int nelements);
[DllImport(libX11)]
public static extern int XChangeProperty(IntPtr display, IntPtr window, IntPtr property, IntPtr type,
int format, PropertyMode mode, void* data, int nelements);
[DllImport(libX11)]
public static extern int XChangeProperty(IntPtr display, IntPtr window, IntPtr property, IntPtr type,
int format, PropertyMode mode, IntPtr atoms, int nelements);
[DllImport(libX11, CharSet = CharSet.Ansi)]
public static extern int XChangeProperty(IntPtr display, IntPtr window, IntPtr property, IntPtr type,
int format, PropertyMode mode, string text, int text_length);
[DllImport(libX11)]
public static extern int XDeleteProperty(IntPtr display, IntPtr window, IntPtr property);
// Drawing
[DllImport(libX11)]
public static extern IntPtr XCreateGC(IntPtr display, IntPtr window, IntPtr valuemask, ref XGCValues values);
[DllImport(libX11)]
public static extern int XFreeGC(IntPtr display, IntPtr gc);
[DllImport(libX11)]
public static extern int XSetFunction(IntPtr display, IntPtr gc, GXFunction function);
[DllImport(libX11)]
internal static extern int XSetLineAttributes(IntPtr display, IntPtr gc, int line_width, GCLineStyle line_style,
GCCapStyle cap_style, GCJoinStyle join_style);
[DllImport(libX11)]
public static extern int XDrawLine(IntPtr display, IntPtr drawable, IntPtr gc, int x1, int y1, int x2, int y2);
[DllImport(libX11)]
public static extern int XDrawRectangle(IntPtr display, IntPtr drawable, IntPtr gc, int x1, int y1, int width,
int height);
[DllImport(libX11)]
public static extern int XFillRectangle(IntPtr display, IntPtr drawable, IntPtr gc, int x1, int y1, int width,
int height);
[DllImport(libX11)]
public static extern int XSetWindowBackground(IntPtr display, IntPtr window, IntPtr background);
[DllImport(libX11)]
public static extern int XCopyArea(IntPtr display, IntPtr src, IntPtr dest, IntPtr gc, int src_x, int src_y,
int width, int height, int dest_x, int dest_y);
[DllImport(libX11)]
public static extern int XGetWindowProperty(IntPtr display, IntPtr window, IntPtr atom, IntPtr long_offset,
IntPtr long_length, bool delete, IntPtr req_type, out IntPtr actual_type, out int actual_format,
out IntPtr nitems, out IntPtr bytes_after, out IntPtr prop);
[DllImport(libX11)]
public static extern int XSetInputFocus(IntPtr display, IntPtr window, RevertTo revert_to, IntPtr time);
[DllImport(libX11)]
public static extern int XIconifyWindow(IntPtr display, IntPtr window, int screen_number);
[DllImport(libX11)]
public static extern int XDefineCursor(IntPtr display, IntPtr window, IntPtr cursor);
[DllImport(libX11)]
public static extern int XUndefineCursor(IntPtr display, IntPtr window);
[DllImport(libX11)]
public static extern int XFreeCursor(IntPtr display, IntPtr cursor);
[DllImport(libX11)]
public static extern IntPtr XCreateFontCursor(IntPtr display, CursorFontShape shape);
[DllImport(libX11)]
public static extern IntPtr XCreatePixmapCursor(IntPtr display, IntPtr source, IntPtr mask,
ref XColor foreground_color, ref XColor background_color, int x_hot, int y_hot);
[DllImport(libX11)]
public static extern IntPtr XCreateBitmapFromData(IntPtr display, IntPtr drawable, byte[] data, int width, int height);
[DllImport(libX11)]
public static extern IntPtr XCreatePixmapFromBitmapData(IntPtr display, IntPtr drawable, byte[] data, int width,
int height, IntPtr fg, IntPtr bg, int depth);
[DllImport(libX11)]
public static extern IntPtr XCreatePixmap(IntPtr display, IntPtr d, int width, int height, int depth);
[DllImport(libX11)]
public static extern IntPtr XFreePixmap(IntPtr display, IntPtr pixmap);
[DllImport(libX11)]
public static extern int XQueryBestCursor(IntPtr display, IntPtr drawable, int width, int height,
out int best_width, out int best_height);
[DllImport(libX11)]
public static extern IntPtr XWhitePixel(IntPtr display, int screen_no);
[DllImport(libX11)]
public static extern IntPtr XBlackPixel(IntPtr display, int screen_no);
[DllImport(libX11)]
public static extern void XGrabServer(IntPtr display);
[DllImport(libX11)]
public static extern void XUngrabServer(IntPtr display);
[DllImport(libX11)]
public static extern void XGetWMNormalHints(IntPtr display, IntPtr window, ref XSizeHints hints,
out IntPtr supplied_return);
[DllImport(libX11)]
public static extern void XSetWMNormalHints(IntPtr display, IntPtr window, ref XSizeHints hints);
[DllImport(libX11)]
public static extern void XSetZoomHints(IntPtr display, IntPtr window, ref XSizeHints hints);
[DllImport(libX11)]
public static extern void XSetWMHints(IntPtr display, IntPtr window, ref XWMHints wmhints);
[DllImport(libX11)]
public static extern int XGetIconSizes(IntPtr display, IntPtr window, out IntPtr size_list, out int count);
[DllImport(libX11)]
public static extern IntPtr XSetErrorHandler(XErrorHandler error_handler);
[DllImport(libX11)]
public static extern IntPtr XGetErrorText(IntPtr display, byte code, StringBuilder buffer, int length);
[DllImport(libX11)]
public static extern int XInitThreads();
[DllImport(libX11)]
public static extern int XConvertSelection(IntPtr display, IntPtr selection, IntPtr target, IntPtr property,
IntPtr requestor, IntPtr time);
[DllImport(libX11)]
public static extern IntPtr XGetSelectionOwner(IntPtr display, IntPtr selection);
[DllImport(libX11)]
public static extern int XSetSelectionOwner(IntPtr display, IntPtr selection, IntPtr owner, IntPtr time);
[DllImport(libX11)]
public static extern int XSetPlaneMask(IntPtr display, IntPtr gc, IntPtr mask);
[DllImport(libX11)]
public static extern int XSetForeground(IntPtr display, IntPtr gc, UIntPtr foreground);
[DllImport(libX11)]
public static extern int XSetBackground(IntPtr display, IntPtr gc, UIntPtr background);
[DllImport(libX11)]
public static extern int XBell(IntPtr display, int percent);
[DllImport(libX11)]
public static extern int XChangeActivePointerGrab(IntPtr display, EventMask event_mask, IntPtr cursor,
IntPtr time);
[DllImport(libX11)]
public static extern bool XFilterEvent(ref XEvent xevent, IntPtr window);
[DllImport(libX11)]
public static extern bool XFilterEvent(XEvent* xevent, IntPtr window);
[DllImport(libX11)]
public static extern void XkbSetDetectableAutoRepeat(IntPtr display, bool detectable, IntPtr supported);
[DllImport(libX11)]
public static extern void XPeekEvent(IntPtr display, out XEvent xevent);
[DllImport(libX11)]
public static extern void XMatchVisualInfo(IntPtr display, int screen, int depth, int klass, out XVisualInfo info);
[DllImport(libX11)]
public static extern IntPtr XLockDisplay(IntPtr display);
[DllImport(libX11)]
public static extern IntPtr XUnlockDisplay(IntPtr display);
[DllImport(libX11)]
public static extern IntPtr XCreateGC(IntPtr display, IntPtr drawable, ulong valuemask, IntPtr values);
[DllImport(libX11)]
public static extern int XInitImage(ref XImage image);
[DllImport(libX11)]
public static extern int XDestroyImage(ref XImage image);
[DllImport(libX11)]
public static extern int XPutImage(IntPtr display, IntPtr drawable, IntPtr gc, ref XImage image,
int srcx, int srcy, int destx, int desty, uint width, uint height);
[DllImport(libX11)]
public static extern int XSync(IntPtr display, bool discard);
[DllImport(libX11)]
public static extern IntPtr XCreateColormap(IntPtr display, IntPtr window, IntPtr visual, int create);
public enum XLookupStatus : uint
{
XBufferOverflow = 0xffffffffu,
XLookupNone = 1,
XLookupChars = 2,
XLookupKeySym = 3,
XLookupBoth = 4
}
[DllImport (libX11)]
public static extern unsafe int XLookupString(ref XEvent xevent, void* buffer, int num_bytes, out IntPtr keysym, out IntPtr status);
[DllImport (libX11)]
public static extern unsafe int Xutf8LookupString(IntPtr xic, ref XEvent xevent, void* buffer, int num_bytes, out IntPtr keysym, out UIntPtr status);
[DllImport (libX11)]
public static extern unsafe int Xutf8LookupString(IntPtr xic, XEvent* xevent, void* buffer, int num_bytes, out IntPtr keysym, out IntPtr status);
[DllImport (libX11)]
public static extern unsafe IntPtr XKeycodeToKeysym(IntPtr display, int keycode, int index);
[DllImport (libX11)]
public static extern unsafe IntPtr XSetLocaleModifiers(string modifiers);
[DllImport (libX11)]
public static extern IntPtr XOpenIM (IntPtr display, IntPtr rdb, IntPtr res_name, IntPtr res_class);
[DllImport (libX11)]
public static extern IntPtr XGetIMValues (IntPtr xim, string name, out XIMStyles* value, IntPtr terminator);
[DllImport (libX11)]
public static extern IntPtr XCreateIC (IntPtr xim, string name, IntPtr value, string name2, IntPtr value2, string name3, IntPtr value3, IntPtr terminator);
[DllImport(libX11)]
public static extern IntPtr XCreateIC(IntPtr xim, string name, IntPtr value, string name2, IntPtr value2,
string name3, IntPtr value3, string name4, IntPtr value4, IntPtr terminator);
[DllImport(libX11)]
public static extern IntPtr XCreateIC(IntPtr xim, string xnClientWindow, IntPtr handle,
string xnInputStyle, IntPtr value3, string xnResourceName, string optionsWmClass,
string xnResourceClass, string wmClass, string xnPreeditAttributes, IntPtr list, IntPtr zero);
[DllImport(libX11)]
public static extern IntPtr XCreateIC(IntPtr xim, string xnClientWindow, IntPtr handle, string xnFocusWindow,
IntPtr value2, string xnInputStyle, IntPtr value3, string xnResourceName, string optionsWmClass,
string xnResourceClass, string wmClass, string xnPreeditAttributes, IntPtr list, IntPtr zero);
[DllImport(libX11)]
public static extern void XSetICFocus(IntPtr xic);
[DllImport(libX11)]
public static extern void XUnsetICFocus(IntPtr xic);
[DllImport(libX11)]
public static extern IntPtr XmbResetIC(IntPtr xic);
[DllImport(libX11)]
public static extern IntPtr XVaCreateNestedList(int unused, Utf8Buffer name, ref XPoint point, IntPtr terminator);
[DllImport(libX11)]
public static extern IntPtr XVaCreateNestedList(int unused, Utf8Buffer xnArea, XRectangle* point,
Utf8Buffer xnSpotLocation, XPoint* value2, Utf8Buffer xnFontSet, IntPtr fs, IntPtr zero);
[DllImport(libX11)]
public static extern IntPtr XVaCreateNestedList(int unused,
Utf8Buffer xnSpotLocation, XPoint* value2, Utf8Buffer xnFontSet, IntPtr fs, IntPtr zero);
[DllImport (libX11)]
public static extern IntPtr XCreateFontSet (IntPtr display, string name, out IntPtr list, out int count, IntPtr unused);
[DllImport(libX11)]
public static extern IntPtr XSetICValues(IntPtr ic, string name, IntPtr data, IntPtr terminator);
[DllImport (libX11)]
public static extern void XCloseIM (IntPtr xim);
[DllImport (libX11)]
public static extern void XDestroyIC (IntPtr xic);
[DllImport(libX11)]
public static extern bool XQueryExtension(IntPtr display, [MarshalAs(UnmanagedType.LPStr)] string name,
out int majorOpcode, out int firstEvent, out int firstError);
[DllImport(libX11)]
public static extern bool XGetEventData(IntPtr display, void* cookie);
[DllImport(libX11)]
public static extern void XFreeEventData(IntPtr display, void* cookie);
[DllImport(libX11Randr)]
public static extern int XRRQueryExtension (IntPtr dpy,
out int event_base_return,
out int error_base_return);
[DllImport(libX11Randr)]
public static extern int XRRQueryVersion(IntPtr dpy,
out int major_version_return,
out int minor_version_return);
[DllImport(libX11Randr)]
public static extern XRRMonitorInfo*
XRRGetMonitors(IntPtr dpy, IntPtr window, bool get_active, out int nmonitors);
[DllImport(libX11Randr)]
public static extern IntPtr* XRRListOutputProperties(IntPtr dpy, IntPtr output, out int count);
[DllImport(libX11Randr)]
public static extern int XRRGetOutputProperty(IntPtr dpy, IntPtr output, IntPtr atom, int offset, int length, bool _delete, bool pending, IntPtr req_type, out IntPtr actual_type, out int actual_format, out int nitems, out long bytes_after, out IntPtr prop);
[DllImport(libX11Randr)]
public static extern void XRRSelectInput(IntPtr dpy, IntPtr window, RandrEventMask mask);
[DllImport(libXInput)]
public static extern Status XIQueryVersion(IntPtr dpy, ref int major, ref int minor);
[DllImport(libXInput)]
public static extern IntPtr XIQueryDevice(IntPtr dpy, int deviceid, out int ndevices_return);
[DllImport(libXInput)]
public static extern void XIFreeDeviceInfo(XIDeviceInfo* info);
[DllImport(libXCursor)]
public static extern IntPtr XcursorImageLoadCursor(IntPtr display, IntPtr image);
[DllImport(libXCursor)]
public static extern IntPtr XcursorImageDestroy(IntPtr image);
public static void XISetMask(ref int mask, XiEventType ev)
{
mask |= (1 << (int)ev);
}
public static int XiEventMaskLen { get; } = 4;
public static bool XIMaskIsSet(void* ptr, int shift) =>
(((byte*)(ptr))[(shift) >> 3] & (1 << (shift & 7))) != 0;
[DllImport(libXInput)]
public static extern Status XISelectEvents(
IntPtr dpy,
IntPtr win,
XIEventMask* masks,
int num_masks
);
public static Status XiSelectEvents(IntPtr display, IntPtr window, Dictionary<int, List<XiEventType>> devices)
{
var masks = stackalloc int[devices.Count];
var emasks = stackalloc XIEventMask[devices.Count];
int c = 0;
foreach (var d in devices)
{
foreach (var ev in d.Value)
XISetMask(ref masks[c], ev);
emasks[c] = new XIEventMask
{
Mask = &masks[c],
Deviceid = d.Key,
MaskLen = XiEventMaskLen
};
c++;
}
return XISelectEvents(display, window, emasks, devices.Count);
}
public struct XGeometry
{
public IntPtr root;
public int x;
public int y;
public int width;
public int height;
public int bw;
public int d;
}
public static bool XGetGeometry(IntPtr display, IntPtr window, out XGeometry geo)
{
geo = new XGeometry();
return XGetGeometry(display, window, out geo.root, out geo.x, out geo.y, out geo.width, out geo.height,
out geo.bw, out geo.d);
}
public static void QueryPointer (IntPtr display, IntPtr w, out IntPtr root, out IntPtr child,
out int root_x, out int root_y, out int child_x, out int child_y,
out int mask)
{
IntPtr c;
XGrabServer (display);
XQueryPointer(display, w, out root, out c,
out root_x, out root_y, out child_x, out child_y,
out mask);
if (root != w)
c = root;
IntPtr child_last = IntPtr.Zero;
while (c != IntPtr.Zero) {
child_last = c;
XQueryPointer(display, c, out root, out c,
out root_x, out root_y, out child_x, out child_y,
out mask);
}
XUngrabServer (display);
XFlush (display);
child = child_last;
}
public static (int x, int y) GetCursorPos(X11Info x11, IntPtr? handle = null)
{
IntPtr root;
IntPtr child;
int root_x;
int root_y;
int win_x;
int win_y;
int keys_buttons;
QueryPointer(x11.Display, handle ?? x11.RootWindow, out root, out child, out root_x, out root_y, out win_x, out win_y,
out keys_buttons);
if (handle != null)
{
return (win_x, win_y);
}
else
{
return (root_x, root_y);
}
}
public static IntPtr CreateEventWindow(AvaloniaX11Platform plat, X11PlatformThreading.EventHandler handler)
{
var win = XCreateSimpleWindow(plat.Display, plat.Info.DefaultRootWindow,
0, 0, 1, 1, 0, IntPtr.Zero, IntPtr.Zero);
plat.Windows[win] = handler;
return win;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.Extensions.FileSystemGlobbing;
namespace MagicOnion.GeneratorCore.Utils
{
internal static class PseudoCompilation
{
public static Task<CSharpCompilation> CreateFromProjectAsync(string[] csprojs, string[] preprocessorSymbols, CancellationToken cancellationToken)
{
var parseOption = new CSharpParseOptions(LanguageVersion.Latest, DocumentationMode.Parse, SourceCodeKind.Regular, CleanPreprocessorSymbols(preprocessorSymbols));
var syntaxTrees = new List<SyntaxTree>();
var sources = new HashSet<string>();
var locations = new List<string>();
foreach (var csproj in csprojs)
{
CollectDocument(csproj, sources, locations);
}
foreach (var file in sources.Select(Path.GetFullPath).Distinct())
{
var text = File.ReadAllText(NormalizeDirectorySeparators(file), Encoding.UTF8);
var syntax = CSharpSyntaxTree.ParseText(text, parseOption);
syntaxTrees.Add(syntax);
}
// ignore Unity's default metadatas(to avoid conflict .NET Core runtime import)
// MonoBleedingEdge = .NET 4.x Unity metadata
// 2.0.0 = .NET Standard 2.0 Unity metadata
var metadata = new List<PortableExecutableReference>();
var targetMetadataLocations = locations.Select(Path.GetFullPath).Concat(GetStandardReferences()).Distinct().Where(x => !(x.Contains("MonoBleedingEdge") || x.Contains("2.0.0")));
foreach (var item in targetMetadataLocations)
{
if (File.Exists(item))
{
metadata.Add(MetadataReference.CreateFromFile(item));
}
}
var compilation = CSharpCompilation.Create(
"CodeGenTemp",
syntaxTrees,
metadata,
new CSharpCompilationOptions(
OutputKind.DynamicallyLinkedLibrary,
allowUnsafe: true,
metadataImportOptions: MetadataImportOptions.All));
return Task.FromResult(compilation);
}
public static async Task<CSharpCompilation> CreateFromDirectoryAsync(string directoryRoot, string[] preprocessorSymbols, string dummyAnnotation, CancellationToken cancellationToken)
{
var parseOption = new CSharpParseOptions(LanguageVersion.Latest, DocumentationMode.Parse, SourceCodeKind.Regular, CleanPreprocessorSymbols(preprocessorSymbols));
var syntaxTrees = new List<SyntaxTree>();
foreach (var file in IterateCsFileWithoutBinObj(directoryRoot))
{
var text = File.ReadAllText(NormalizeDirectorySeparators(file), Encoding.UTF8);
var syntax = CSharpSyntaxTree.ParseText(text, parseOption);
syntaxTrees.Add(syntax);
if (Path.GetFileNameWithoutExtension(file) == "Attributes")
{
var root = await syntax.GetRootAsync(cancellationToken).ConfigureAwait(false);
}
}
syntaxTrees.Add(CSharpSyntaxTree.ParseText(dummyAnnotation, parseOption));
var metadata = GetStandardReferences().Select(x => MetadataReference.CreateFromFile(x)).ToArray();
var compilation = CSharpCompilation.Create(
"CodeGenTemp",
syntaxTrees,
metadata,
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true));
return compilation;
}
private static List<string> GetStandardReferences()
{
var standardMetadataType = new[]
{
typeof(object),
typeof(Attribute),
typeof(Enumerable),
typeof(Task<>),
typeof(IgnoreDataMemberAttribute),
typeof(System.Collections.Hashtable),
typeof(System.Collections.Generic.List<>),
typeof(System.Collections.Generic.HashSet<>),
typeof(System.Collections.Immutable.IImmutableList<>),
typeof(System.Linq.ILookup<,>),
typeof(System.Tuple<>),
typeof(System.ValueTuple<>),
typeof(System.Collections.Concurrent.ConcurrentDictionary<,>),
typeof(System.Collections.ObjectModel.ObservableCollection<>),
};
var metadata = standardMetadataType
.Select(x => x.Assembly.Location)
.Distinct()
.ToList();
var dir = new FileInfo(typeof(object).Assembly.Location).Directory;
{
var path = Path.Combine(dir.FullName, "netstandard.dll");
if (File.Exists(path))
{
metadata.Add(path);
}
}
{
var path = Path.Combine(dir.FullName, "System.Runtime.dll");
if (File.Exists(path))
{
metadata.Add(path);
}
}
return metadata;
}
private static IEnumerable<string> CleanPreprocessorSymbols(string[] preprocessorSymbols)
{
if (preprocessorSymbols == null)
{
return null;
}
return preprocessorSymbols.Where(x => !string.IsNullOrWhiteSpace(x));
}
private static void CollectDocument(string csproj, HashSet<string> source, List<string> metadataLocations)
{
XDocument document;
using (var sr = new StreamReader(csproj, true))
{
var reader = new XmlTextReader(sr);
reader.Namespaces = false;
document = XDocument.Load(reader, LoadOptions.None);
}
var csProjRoot = Path.GetDirectoryName(csproj);
// .NET Core root
var framworkRoot = Path.GetDirectoryName(typeof(object).Assembly.Location);
// Legacy
// <Project ToolsVersion=...>
// New
// <Project Sdk="Microsoft.NET.Sdk">
var proj = document.Element("Project");
var legacyFormat = !(proj.Attribute("Sdk")?.Value?.StartsWith("Microsoft.NET.Sdk") ?? false);
if (!legacyFormat)
{
// try to find EnableDefaultCompileItems
if (document.Descendants("EnableDefaultCompileItems")?.FirstOrDefault()?.Value == "false"
|| document.Descendants("EnableDefaultItems")?.FirstOrDefault()?.Value == "false")
{
legacyFormat = true;
}
}
{
// compile files
{
// default include
if (!legacyFormat)
{
foreach (var path in GetCompileFullPaths(null, "**/*.cs", csProjRoot))
{
source.Add(path);
}
}
// custom elements
foreach (var item in document.Descendants("Compile"))
{
var include = item.Attribute("Include")?.Value;
if (include != null)
{
foreach (var path in GetCompileFullPaths(item, include, csProjRoot))
{
source.Add(path);
}
}
var remove = item.Attribute("Remove")?.Value;
if (remove != null)
{
foreach (var path in GetCompileFullPaths(item, remove, csProjRoot))
{
source.Remove(path);
}
}
}
// default remove
if (!legacyFormat)
{
foreach (var path in GetCompileFullPaths(null, "./bin/**;./obj/**", csProjRoot))
{
source.Remove(path);
}
}
}
// shared
foreach (var item in document.Descendants("Import"))
{
if (item.Attribute("Label")?.Value == "Shared")
{
var sharedRoot = Path.GetDirectoryName(Path.Combine(csProjRoot, item.Attribute("Project").Value));
foreach (var file in IterateCsFileWithoutBinObj(Path.GetDirectoryName(sharedRoot)))
{
source.Add(file);
}
}
}
// proj-ref
foreach (var item in document.Descendants("ProjectReference"))
{
var refCsProjPath = item.Attribute("Include")?.Value;
if (refCsProjPath != null)
{
CollectDocument(Path.Combine(csProjRoot, NormalizeDirectorySeparators(refCsProjPath)), source, metadataLocations);
}
}
// metadata
foreach (var item in document.Descendants("Reference"))
{
var hintPath = item.Element("HintPath")?.Value;
if (hintPath == null)
{
var path = Path.Combine(framworkRoot, item.Attribute("Include").Value + ".dll");
metadataLocations.Add(path);
}
else
{
var path = Path.Combine(csProjRoot, NormalizeDirectorySeparators(hintPath));
metadataLocations.Add(path);
}
}
// resolve NuGet reference
var nugetPackagesPath = Environment.GetEnvironmentVariable("NUGET_PACKAGES");
if (nugetPackagesPath == null)
{
// Try default
// Windows: %userprofile%\.nuget\packages
// Mac/Linux: ~/.nuget/packages
nugetPackagesPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".nuget", "packages");
}
var resolvedDllPaths = new HashSet<string>();
void CollectNugetPackages(string id, string packageVersion, string originalTargetFramework)
{
foreach (var targetFramework in NetstandardFallBack(originalTargetFramework).Distinct())
{
var pathpath = Path.Combine(nugetPackagesPath, id, packageVersion, "lib", targetFramework);
if (!Directory.Exists(pathpath))
{
pathpath = pathpath.ToLower(); // try all lower.
}
if (Directory.Exists(pathpath))
{
if (resolvedDllPaths.Add(pathpath))
{
foreach (var dependency in ResolveNuGetDependency(nugetPackagesPath, id, packageVersion, targetFramework))
{
CollectNugetPackages(dependency.id, dependency.version, originalTargetFramework);
}
}
break;
}
}
}
foreach (var item in document.Descendants("PackageReference"))
{
var originalTargetFramework = document.Descendants("TargetFramework").FirstOrDefault()?.Value ?? document.Descendants("TargetFrameworks").First().Value.Split(';').First();
var includePath = item.Attribute("Include")?.Value.Trim().ToLower(); // maybe lower
if (includePath == null) continue;
var packageVersion = item.Attribute("Version").Value.Trim();
CollectNugetPackages(includePath, packageVersion, originalTargetFramework);
}
foreach (var item in resolvedDllPaths)
{
foreach (var dllPath in Directory.GetFiles(item, "*.dll"))
{
metadataLocations.Add(Path.GetFullPath(dllPath));
}
}
}
}
private static IEnumerable<string> NetstandardFallBack(string originalTargetFramework)
{
yield return originalTargetFramework;
if (originalTargetFramework.Contains("netcoreapp"))
{
yield return "netcoreapp3.1";
yield return "netcoreapp3.0";
yield return "netcoreapp2.1";
yield return "netcoreapp2.0";
}
yield return "netstandard2.1";
yield return "netstandard2.0";
yield return "netstandard1.6";
}
private static IEnumerable<(string id, string version)> ResolveNuGetDependency(string nugetPackagesPath, string includePath, string packageVersion, string targetFramework)
{
var dirPath = Path.Combine(nugetPackagesPath, includePath, packageVersion);
if (!Directory.Exists(dirPath))
{
dirPath = dirPath.ToLower(); // try all lower.
}
var filePath = Path.Combine(dirPath, includePath.ToLower() + ".nuspec");
if (File.Exists(filePath))
{
XDocument document;
using (var sr = new StreamReader(filePath, true))
{
var reader = new XmlTextReader(sr);
reader.Namespaces = false;
document = XDocument.Load(reader, LoadOptions.None);
}
foreach (var item in document.Descendants().Where(x => x.Name == "dependencies"))
{
foreach (var tf in NetstandardFallBack(targetFramework))
{
foreach (var item2 in item.Elements().Where(x => x.Name == "group" && x.Attributes().Any(a => a.Name == "targetFramework" && (a.Value?.Trim('.')?.Equals(tf, StringComparison.OrdinalIgnoreCase) ?? false))))
{
foreach (var item3 in item2.Descendants().Where(x => x.Name == "dependency"))
{
yield return (item3.Attribute("id").Value, item3.Attribute("version").Value);
}
// found, stop search.
yield break;
}
}
}
}
}
private static IEnumerable<string> IterateCsFileWithoutBinObj(string root)
{
foreach (var item in Directory.EnumerateFiles(root, "*.cs", SearchOption.TopDirectoryOnly))
{
yield return item;
}
foreach (var dir in Directory.GetDirectories(root, "*", SearchOption.TopDirectoryOnly))
{
var dirName = new DirectoryInfo(dir).Name;
if (dirName == "bin" || dirName == "obj")
{
continue;
}
foreach (var item in IterateCsFileWithoutBinObj(dir))
{
yield return item;
}
}
}
private static string NormalizeDirectorySeparators(string path)
{
return path.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar);
}
private static IEnumerable<string> GetCompileFullPaths(XElement compile, string includeOrRemovePattern, string csProjRoot)
{
// solve macro
includeOrRemovePattern = includeOrRemovePattern.Replace("$(ProjectDir)", csProjRoot);
var matcher = new Matcher(StringComparison.OrdinalIgnoreCase);
matcher.AddIncludePatterns(includeOrRemovePattern.Split(';'));
var exclude = compile?.Attribute("Exclude")?.Value;
if (exclude != null)
{
matcher.AddExcludePatterns(exclude.Split(';'));
}
foreach (var path in matcher.GetResultsInFullPath(csProjRoot))
{
yield return path;
}
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type WorkbookWorksheetProtectionRequest.
/// </summary>
public partial class WorkbookWorksheetProtectionRequest : BaseRequest, IWorkbookWorksheetProtectionRequest
{
/// <summary>
/// Constructs a new WorkbookWorksheetProtectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public WorkbookWorksheetProtectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified WorkbookWorksheetProtection using POST.
/// </summary>
/// <param name="workbookWorksheetProtectionToCreate">The WorkbookWorksheetProtection to create.</param>
/// <returns>The created WorkbookWorksheetProtection.</returns>
public System.Threading.Tasks.Task<WorkbookWorksheetProtection> CreateAsync(WorkbookWorksheetProtection workbookWorksheetProtectionToCreate)
{
return this.CreateAsync(workbookWorksheetProtectionToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified WorkbookWorksheetProtection using POST.
/// </summary>
/// <param name="workbookWorksheetProtectionToCreate">The WorkbookWorksheetProtection to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created WorkbookWorksheetProtection.</returns>
public async System.Threading.Tasks.Task<WorkbookWorksheetProtection> CreateAsync(WorkbookWorksheetProtection workbookWorksheetProtectionToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<WorkbookWorksheetProtection>(workbookWorksheetProtectionToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified WorkbookWorksheetProtection.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified WorkbookWorksheetProtection.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<WorkbookWorksheetProtection>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified WorkbookWorksheetProtection.
/// </summary>
/// <returns>The WorkbookWorksheetProtection.</returns>
public System.Threading.Tasks.Task<WorkbookWorksheetProtection> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified WorkbookWorksheetProtection.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The WorkbookWorksheetProtection.</returns>
public async System.Threading.Tasks.Task<WorkbookWorksheetProtection> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<WorkbookWorksheetProtection>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified WorkbookWorksheetProtection using PATCH.
/// </summary>
/// <param name="workbookWorksheetProtectionToUpdate">The WorkbookWorksheetProtection to update.</param>
/// <returns>The updated WorkbookWorksheetProtection.</returns>
public System.Threading.Tasks.Task<WorkbookWorksheetProtection> UpdateAsync(WorkbookWorksheetProtection workbookWorksheetProtectionToUpdate)
{
return this.UpdateAsync(workbookWorksheetProtectionToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified WorkbookWorksheetProtection using PATCH.
/// </summary>
/// <param name="workbookWorksheetProtectionToUpdate">The WorkbookWorksheetProtection to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated WorkbookWorksheetProtection.</returns>
public async System.Threading.Tasks.Task<WorkbookWorksheetProtection> UpdateAsync(WorkbookWorksheetProtection workbookWorksheetProtectionToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<WorkbookWorksheetProtection>(workbookWorksheetProtectionToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookWorksheetProtectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookWorksheetProtectionRequest Expand(Expression<Func<WorkbookWorksheetProtection, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookWorksheetProtectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookWorksheetProtectionRequest Select(Expression<Func<WorkbookWorksheetProtection, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="workbookWorksheetProtectionToInitialize">The <see cref="WorkbookWorksheetProtection"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(WorkbookWorksheetProtection workbookWorksheetProtectionToInitialize)
{
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Logic
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for IntegrationAccountMapsOperations.
/// </summary>
public static partial class IntegrationAccountMapsOperationsExtensions
{
/// <summary>
/// Gets a list of integration account maps.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<IntegrationAccountMap> List(this IIntegrationAccountMapsOperations operations, string resourceGroupName, string integrationAccountName, ODataQuery<IntegrationAccountMapFilter> odataQuery = default(ODataQuery<IntegrationAccountMapFilter>))
{
return Task.Factory.StartNew(s => ((IIntegrationAccountMapsOperations)s).ListAsync(resourceGroupName, integrationAccountName, odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of integration account maps.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<IntegrationAccountMap>> ListAsync(this IIntegrationAccountMapsOperations operations, string resourceGroupName, string integrationAccountName, ODataQuery<IntegrationAccountMapFilter> odataQuery = default(ODataQuery<IntegrationAccountMapFilter>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, integrationAccountName, odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets an integration account map.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='mapName'>
/// The integration account map name.
/// </param>
public static IntegrationAccountMap Get(this IIntegrationAccountMapsOperations operations, string resourceGroupName, string integrationAccountName, string mapName)
{
return Task.Factory.StartNew(s => ((IIntegrationAccountMapsOperations)s).GetAsync(resourceGroupName, integrationAccountName, mapName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets an integration account map.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='mapName'>
/// The integration account map name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IntegrationAccountMap> GetAsync(this IIntegrationAccountMapsOperations operations, string resourceGroupName, string integrationAccountName, string mapName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, integrationAccountName, mapName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates an integration account map.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='mapName'>
/// The integration account map name.
/// </param>
/// <param name='map'>
/// The integration account map.
/// </param>
public static IntegrationAccountMap CreateOrUpdate(this IIntegrationAccountMapsOperations operations, string resourceGroupName, string integrationAccountName, string mapName, IntegrationAccountMap map)
{
return Task.Factory.StartNew(s => ((IIntegrationAccountMapsOperations)s).CreateOrUpdateAsync(resourceGroupName, integrationAccountName, mapName, map), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates an integration account map.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='mapName'>
/// The integration account map name.
/// </param>
/// <param name='map'>
/// The integration account map.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IntegrationAccountMap> CreateOrUpdateAsync(this IIntegrationAccountMapsOperations operations, string resourceGroupName, string integrationAccountName, string mapName, IntegrationAccountMap map, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, integrationAccountName, mapName, map, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes an integration account map.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='mapName'>
/// The integration account map name.
/// </param>
public static void Delete(this IIntegrationAccountMapsOperations operations, string resourceGroupName, string integrationAccountName, string mapName)
{
Task.Factory.StartNew(s => ((IIntegrationAccountMapsOperations)s).DeleteAsync(resourceGroupName, integrationAccountName, mapName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an integration account map.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='mapName'>
/// The integration account map name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IIntegrationAccountMapsOperations operations, string resourceGroupName, string integrationAccountName, string mapName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, integrationAccountName, mapName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets a list of integration account maps.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<IntegrationAccountMap> ListNext(this IIntegrationAccountMapsOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IIntegrationAccountMapsOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of integration account maps.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<IntegrationAccountMap>> ListNextAsync(this IIntegrationAccountMapsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using Android.OS;
using Android.App;
using Android.Views;
using Android.Widget;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.MobileServices;
namespace androidsample
{
[Activity (MainLauncher = true,
Icon="@drawable/ic_launcher", Label="@string/app_name",
Theme="@style/AppTheme")]
public class ToDoActivity : Activity
{
//Mobile Service Client reference
private MobileServiceClient client;
//Mobile Service Table used to access data
private IMobileServiceTable<ToDoItem> toDoTable;
//Adapter to sync the items list with the view
private ToDoItemAdapter adapter;
//EditText containing the "New ToDo" text
private EditText textNewToDo;
//Progress spinner to use for table operations
private ProgressBar progressBar;
const string applicationURL = @"MOBILE SERVICE URL";
const string applicationKey = @"APPLICATION KEY";
protected override async void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Activity_To_Do);
progressBar = FindViewById<ProgressBar> (Resource.Id.loadingProgressBar);
// Initialize the progress bar
progressBar.Visibility = ViewStates.Gone;
// Create ProgressFilter to handle busy state
var progressHandler = new ProgressHandler ();
progressHandler.BusyStateChange += (busy) => {
if (progressBar != null)
progressBar.Visibility = busy ? ViewStates.Visible : ViewStates.Gone;
};
try {
CurrentPlatform.Init ();
// Create the Mobile Service Client instance, using the provided
// Mobile Service URL and key
client = new MobileServiceClient (
applicationURL,
applicationKey, progressHandler);
// Get the Mobile Service Table instance to use
toDoTable = client.GetTable <ToDoItem> ();
textNewToDo = FindViewById<EditText> (Resource.Id.textNewToDo);
// Create an adapter to bind the items with the view
adapter = new ToDoItemAdapter (this, Resource.Layout.Row_List_To_Do);
var listViewToDo = FindViewById<ListView> (Resource.Id.listViewToDo);
listViewToDo.Adapter = adapter;
// Load the items from the Mobile Service
await RefreshItemsFromTableAsync ();
} catch (Java.Net.MalformedURLException) {
CreateAndShowDialog (new Exception ("There was an error creating the Mobile Service. Verify the URL"), "Error");
} catch (Exception e) {
CreateAndShowDialog (e, "Error");
}
}
//Initializes the activity menu
public override bool OnCreateOptionsMenu (IMenu menu)
{
MenuInflater.Inflate (Resource.Menu.activity_main, menu);
return true;
}
//Select an option from the menu
public override bool OnOptionsItemSelected (IMenuItem item)
{
if (item.ItemId == Resource.Id.menu_refresh) {
OnRefreshItemsSelected ();
}
return true;
}
// Called when the refresh menu opion is selected
async void OnRefreshItemsSelected ()
{
await RefreshItemsFromTableAsync ();
}
//Refresh the list with the items in the Mobile Service Table
async Task RefreshItemsFromTableAsync ()
{
try {
// Get the items that weren't marked as completed and add them in the
// adapter
var list = await toDoTable.Where (item => item.Complete == false).ToListAsync ();
adapter.Clear ();
foreach (ToDoItem current in list)
adapter.Add (current);
} catch (Exception e) {
CreateAndShowDialog (e, "Error");
}
}
public async Task CheckItem (ToDoItem item)
{
if (client == null) {
return;
}
// Set the item as completed and update it in the table
item.Complete = true;
try {
await toDoTable.UpdateAsync (item);
if (item.Complete)
adapter.Remove (item);
} catch (Exception e) {
CreateAndShowDialog (e, "Error");
}
}
[Java.Interop.Export()]
public async void AddItem (View view)
{
if (client == null || string.IsNullOrWhiteSpace (textNewToDo.Text)) {
return;
}
// Create a new item
var item = new ToDoItem {
Text = textNewToDo.Text,
Complete = false
};
try {
// Insert the new item
await toDoTable.InsertAsync (item);
if (!item.Complete) {
adapter.Add (item);
}
} catch (Exception e) {
CreateAndShowDialog (e, "Error");
}
textNewToDo.Text = "";
}
void CreateAndShowDialog (Exception exception, String title)
{
CreateAndShowDialog (exception.Message, title);
}
void CreateAndShowDialog (string message, string title)
{
AlertDialog.Builder builder = new AlertDialog.Builder (this);
builder.SetMessage (message);
builder.SetTitle (title);
builder.Create ().Show ();
}
class ProgressHandler : DelegatingHandler
{
int busyCount = 0;
public event Action<bool> BusyStateChange;
#region implemented abstract members of HttpMessageHandler
protected override async Task<HttpResponseMessage> SendAsync (HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
//assumes always executes on UI thread
if (busyCount++ == 0 && BusyStateChange != null)
BusyStateChange (true);
var response = await base.SendAsync (request, cancellationToken);
// assumes always executes on UI thread
if (--busyCount == 0 && BusyStateChange != null)
BusyStateChange (false);
return response;
}
#endregion
}
}
}
| |
// Copyright (c) 2017-2021 Ubisoft Entertainment
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.Serialization;
namespace Sharpmake
{
/// <summary>
/// Generates debug projects and solutions
/// </summary>
public static class DebugProjectGenerator
{
internal static string RootPath { get; private set; }
internal static string[] MainSources { get; private set; }
public interface IDebugProjectExtension
{
void AddSharpmakePackage(Project.Configuration config);
void AddReferences(Project.Configuration config, IEnumerable<string> additionalReferences = null);
string GetSharpmakeExecutableFullPath();
}
public class DefaultDebugProjectExtension : IDebugProjectExtension
{
public virtual void AddSharpmakePackage(Project.Configuration conf)
{
if (!ShouldUseLocalSharpmakeDll())
{
return;
}
string sharpmakeDllPath;
string sharpmakeGeneratorDllPath;
GetSharpmakeLocalDlls(out sharpmakeDllPath, out sharpmakeGeneratorDllPath);
conf.ReferencesByPath.Add(sharpmakeDllPath);
conf.ReferencesByPath.Add(sharpmakeGeneratorDllPath);
}
protected static void GetSharpmakeLocalDlls(out string sharpmakeDllPath, out string sharpmakeGeneratorDllPath)
{
sharpmakeDllPath = Assembly.GetExecutingAssembly().Location;
sharpmakeGeneratorDllPath = Assembly.Load("Sharpmake.Generators")?.Location;
}
public virtual void AddReferences(Project.Configuration conf, IEnumerable<string> additionalReferences = null)
{
conf.ReferencesByPath.Add(Assembler.DefaultReferences);
if (additionalReferences != null)
{
conf.ReferencesByPath.AddRange(additionalReferences);
}
}
public virtual bool ShouldUseLocalSharpmakeDll()
{
return true;
}
public virtual string GetSharpmakeExecutableFullPath()
{
string sharpmakeApplicationExePath = Process.GetCurrentProcess().MainModule.FileName;
if (Util.IsRunningInMono())
{
// When running within Mono, sharpmakeApplicationExePath will at this point wrongly refer to the
// mono (or mono-sgen) executable. Fix it so that it points to Sharpmake.Application.exe.
sharpmakeApplicationExePath = $"{AppDomain.CurrentDomain.BaseDirectory}{AppDomain.CurrentDomain.FriendlyName}";
}
return sharpmakeApplicationExePath;
}
}
public static IDebugProjectExtension DebugProjectExtension { get; set; } = new DefaultDebugProjectExtension();
/// <summary>
/// Generates debug projects and solutions
/// </summary>
/// <param name="sources"></param>
/// <param name="arguments"></param>
/// <param name="startArguments"></param>
public static void GenerateDebugSolution(string[] sources, Arguments arguments, string startArguments)
{
GenerateDebugSolution(sources, arguments, startArguments, null);
}
/// <summary>
/// Generates debug projects and solutions
/// </summary>
/// <param name="sources"></param>
/// <param name="arguments"></param>
/// <param name="startArguments"></param>
/// <param name="defines"></param>
public static void GenerateDebugSolution(string[] sources, Arguments arguments, string startArguments, string[] defines)
{
FindAllSources(sources, arguments, startArguments, defines);
arguments.Generate<DebugSolution>();
}
internal class ProjectContent
{
public string DisplayName;
public string ProjectFolder;
public readonly HashSet<string> ProjectFiles = new HashSet<string>();
public readonly List<string> References = new List<string>();
public readonly List<Type> ProjectReferences = new List<Type>();
public readonly List<string> Defines = new List<string>();
public bool IsSetupProject;
public string StartArguments;
}
internal static readonly Dictionary<Type, ProjectContent> DebugProjects = new Dictionary<Type, ProjectContent>();
private static void FindAllSources(string[] sourcesArguments, Sharpmake.Arguments sharpmakeArguments, string startArguments, string[] defines)
{
MainSources = sourcesArguments;
RootPath = Path.GetDirectoryName(sourcesArguments[0]);
Assembler assembler = new Assembler(sharpmakeArguments.Builder.Defines);
assembler.AttributeParsers.Add(new DebugProjectNameAttributeParser());
IAssemblyInfo assemblyInfo = assembler.LoadUncompiledAssemblyInfo(Builder.Instance.CreateContext(BuilderCompileErrorBehavior.ReturnNullAssembly), MainSources);
GenerateDebugProject(assemblyInfo, true, startArguments, new Dictionary<string, Type>(), defines);
}
private static Type GenerateDebugProject(IAssemblyInfo assemblyInfo, bool isSetupProject, string startArguments, IDictionary<string, Type> visited, string[] defines)
{
string displayName = assemblyInfo.DebugProjectName;
if (string.IsNullOrEmpty(displayName))
displayName = isSetupProject ? "sharpmake_debug" : $"sharpmake_package_{assemblyInfo.Id.GetHashCode():X8}";
Type generatedProject;
if (visited.TryGetValue(assemblyInfo.Id, out generatedProject))
{
if (generatedProject == null)
throw new Error($"Circular sharpmake package dependency on {displayName}");
return generatedProject;
}
visited[assemblyInfo.Id] = null;
ProjectContent project = new ProjectContent
{
ProjectFolder = RootPath,
IsSetupProject = isSetupProject,
DisplayName = displayName,
StartArguments = startArguments
};
generatedProject = CreateProject(displayName);
DebugProjects.Add(generatedProject, project);
// Add sources
foreach (var source in assemblyInfo.SourceFiles)
{
project.ProjectFiles.Add(source);
}
// Add references
var references = new HashSet<string>();
if (assemblyInfo.UseDefaultReferences)
{
foreach (string defaultReference in Assembler.DefaultReferences)
references.Add(Assembler.GetAssemblyDllPath(defaultReference));
}
foreach (var assemblerRef in assemblyInfo.References)
{
if (!assemblyInfo.SourceReferences.ContainsKey(assemblerRef))
{
references.Add(assemblerRef);
}
}
project.References.AddRange(references);
foreach (var refInfo in assemblyInfo.SourceReferences.Values)
{
project.ProjectReferences.Add(GenerateDebugProject(refInfo, false, string.Empty, visited, defines));
}
if (defines != null)
{
project.Defines.AddRange(defines);
}
visited[assemblyInfo.Id] = generatedProject;
return generatedProject;
}
private static Type CreateProject(string typeSignature)
{
// define class type
var assemblyName = new AssemblyName(typeSignature);
AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("DebugSharpmakeModule");
TypeBuilder typeBuilder = moduleBuilder.DefineType(typeSignature,
TypeAttributes.Public | TypeAttributes.Class |
TypeAttributes.AnsiClass | TypeAttributes.AutoClass |
TypeAttributes.BeforeFieldInit | TypeAttributes.AutoLayout,
typeof(DebugProject));
// add attribute [Sharpmake.Generate]
Type[] generateAttrParams = { };
ConstructorInfo generateAttrCtorInfo = typeof(Sharpmake.Generate).GetConstructor(generateAttrParams);
CustomAttributeBuilder generateAttrBuilder = new CustomAttributeBuilder(generateAttrCtorInfo, new object[] { });
typeBuilder.SetCustomAttribute(generateAttrBuilder);
return typeBuilder.CreateType();
}
internal static Target GetTargets()
{
return new Target(
Platform.anycpu,
DevEnv.vs2019,
Optimization.Debug | Optimization.Release,
OutputType.Dll,
Blob.NoBlob,
BuildSystem.MSBuild,
Assembler.SharpmakeDotNetFramework
);
}
/// <summary>
/// Set up debug configuration in user file
/// </summary>
/// <param name="conf"></param>
/// <param name="startArguments"></param>
public static void SetupProjectOptions(this Project.Configuration conf, string startArguments)
{
conf.CsprojUserFile = new Project.Configuration.CsprojUserFileSettings();
conf.CsprojUserFile.StartAction = Project.Configuration.CsprojUserFileSettings.StartActionSetting.Program;
string quote = "\'"; // Use single quote that is cross platform safe
conf.CsprojUserFile.StartArguments = $@"/sources(@{quote}{string.Join($"{quote},@{quote}", MainSources)}{quote}) {startArguments}";
conf.CsprojUserFile.StartProgram = DebugProjectExtension.GetSharpmakeExecutableFullPath();
conf.CsprojUserFile.WorkingDirectory = Directory.GetCurrentDirectory();
}
}
[Sharpmake.Generate]
public class DebugSolution : Solution
{
public DebugSolution()
: base(typeof(Target))
{
Name = "Sharpmake_DebugSolution";
AddTargets(DebugProjectGenerator.GetTargets());
}
[Configure]
public virtual void Configure(Configuration conf, Target target)
{
conf.SolutionPath = DebugProjectGenerator.RootPath;
conf.SolutionFileName = "[solution.Name].[target.DevEnv]";
foreach (var project in DebugProjectGenerator.DebugProjects)
conf.AddProject(project.Key, target);
}
}
[Sharpmake.Generate]
public class DebugProject : CSharpProject
{
private readonly DebugProjectGenerator.ProjectContent _projectInfo;
public DebugProject()
: base(typeof(Target), typeof(Configuration), isInternal: true)
{
_projectInfo = DebugProjectGenerator.DebugProjects[GetType()];
// set paths
RootPath = _projectInfo.ProjectFolder;
SourceRootPath = RootPath;
// add selected source files
SourceFiles.AddRange(_projectInfo.ProjectFiles);
// ensure that no file will be automagically added
SourceFilesExtensions.Clear();
ResourceFilesExtensions.Clear();
PRIFilesExtensions.Clear();
ResourceFiles.Clear();
NoneExtensions.Clear();
VsctExtension.Clear();
Name = _projectInfo.DisplayName;
// Use the new csproj style
ProjectSchema = CSharpProjectSchema.NetCore;
// prevents output dir to have a framework subfolder
CustomProperties.Add("AppendTargetFrameworkToOutputPath", "false");
// we need to disable determinism while because we are using wildcards in assembly versions
// error CS8357: The specified version string contains wildcards, which are not compatible with determinism
CustomProperties.Add("Deterministic", "false");
AddTargets(DebugProjectGenerator.GetTargets());
}
[Configure]
public void ConfigureAll(Configuration conf, Target target)
{
conf.ProjectPath = RootPath;
conf.ProjectFileName = "[project.Name].[target.DevEnv]";
conf.Output = Configuration.OutputType.DotNetClassLibrary;
conf.DefaultOption = target.Optimization == Optimization.Debug ? Options.DefaultTarget.Debug : Options.DefaultTarget.Release;
conf.Options.Add(Assembler.SharpmakeScriptsCSharpVersion);
conf.Defines.Add(_projectInfo.Defines.ToArray());
foreach (var projectReference in _projectInfo.ProjectReferences)
{
conf.AddPrivateDependency(target, projectReference);
}
DebugProjectGenerator.DebugProjectExtension.AddReferences(conf, _projectInfo.References);
DebugProjectGenerator.DebugProjectExtension.AddSharpmakePackage(conf);
// set up custom configuration only to setup project
if (_projectInfo.IsSetupProject &&
FileSystemStringComparer.Default.Equals(conf.ProjectPath, RootPath))
{
conf.SetupProjectOptions(_projectInfo.StartArguments);
}
}
}
[Serializable]
public class AssemblyVersionException : Exception
{
public AssemblyVersionException() : base() { }
public AssemblyVersionException(string msg) : base(msg) { }
protected AssemblyVersionException(SerializationInfo info, StreamingContext context)
: base(info, context)
{ }
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WebsitePanel.Portal.ExchangeServer {
public partial class ExchangeMailboxMailFlowSettings {
/// <summary>
/// asyncTasks control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.EnableAsyncTasksSupport asyncTasks;
/// <summary>
/// Image1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Image Image1;
/// <summary>
/// locTitle control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locTitle;
/// <summary>
/// litDisplayName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal litDisplayName;
/// <summary>
/// tabs control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.ExchangeServer.UserControls.MailboxTabs tabs;
/// <summary>
/// messageBox control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.UserControls.SimpleMessageBox messageBox;
/// <summary>
/// secForwarding control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secForwarding;
/// <summary>
/// Forwarding control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel Forwarding;
/// <summary>
/// ForwardingUpdatePanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.UpdatePanel ForwardingUpdatePanel;
/// <summary>
/// chkEnabledForwarding control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkEnabledForwarding;
/// <summary>
/// ForwardSettingsPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTable ForwardSettingsPanel;
/// <summary>
/// locForwardTo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locForwardTo;
/// <summary>
/// forwardingAddress control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.ExchangeServer.UserControls.MailboxSelector forwardingAddress;
/// <summary>
/// chkDoNotDeleteOnForward control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkDoNotDeleteOnForward;
/// <summary>
/// secSendOnBehalf control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secSendOnBehalf;
/// <summary>
/// SendOnBehalf control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel SendOnBehalf;
/// <summary>
/// locGrantAccess control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locGrantAccess;
/// <summary>
/// accessAccounts control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.ExchangeServer.UserControls.AccountsList accessAccounts;
/// <summary>
/// secAcceptMessagesFrom control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secAcceptMessagesFrom;
/// <summary>
/// AcceptMessagesFrom control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel AcceptMessagesFrom;
/// <summary>
/// acceptAccounts control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.ExchangeServer.UserControls.AcceptedSenders acceptAccounts;
/// <summary>
/// chkSendersAuthenticated control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkSendersAuthenticated;
/// <summary>
/// secRejectMessagesFrom control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secRejectMessagesFrom;
/// <summary>
/// RejectMessagesFrom control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel RejectMessagesFrom;
/// <summary>
/// rejectAccounts control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.ExchangeServer.UserControls.RejectedSenders rejectAccounts;
/// <summary>
/// chkPmmAllowed control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkPmmAllowed;
/// <summary>
/// buttonPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.ItemButtonPanel buttonPanel;
/// <summary>
/// ValidationSummary1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.ValidationSummary ValidationSummary1;
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Content.Server.Administration.Logs;
using Content.Server.IP;
using Content.Server.Preferences.Managers;
using Content.Shared.CCVar;
using Microsoft.EntityFrameworkCore;
using Robust.Shared.Configuration;
using Robust.Shared.IoC;
using Robust.Shared.Network;
using Robust.Shared.Utility;
namespace Content.Server.Database
{
/// <summary>
/// Provides methods to retrieve and update character preferences.
/// Don't use this directly, go through <see cref="ServerPreferencesManager" /> instead.
/// </summary>
public sealed class ServerDbSqlite : ServerDbBase
{
// For SQLite we use a single DB context via SQLite.
// This doesn't allow concurrent access so that's what the semaphore is for.
// That said, this is bloody SQLite, I don't even think EFCore bothers to truly async it.
private readonly SemaphoreSlim _prefsSemaphore = new(1, 1);
private readonly Task _dbReadyTask;
private readonly SqliteServerDbContext _prefsCtx;
private int _msDelay;
public ServerDbSqlite(DbContextOptions<SqliteServerDbContext> options)
{
_prefsCtx = new SqliteServerDbContext(options);
var cfg = IoCManager.Resolve<IConfigurationManager>();
if (cfg.GetCVar(CCVars.DatabaseSynchronous))
{
_prefsCtx.Database.Migrate();
_dbReadyTask = Task.CompletedTask;
}
else
{
_dbReadyTask = Task.Run(() => _prefsCtx.Database.Migrate());
}
cfg.OnValueChanged(CCVars.DatabaseSqliteDelay, v => _msDelay = v, true);
}
#region Ban
public override async Task<ServerBanDef?> GetServerBanAsync(int id)
{
await using var db = await GetDbImpl();
var ban = await db.SqliteDbContext.Ban
.Include(p => p.Unban)
.Where(p => p.Id == id)
.SingleOrDefaultAsync();
return ConvertBan(ban);
}
public override async Task<ServerBanDef?> GetServerBanAsync(
IPAddress? address,
NetUserId? userId,
ImmutableArray<byte>? hwId)
{
await using var db = await GetDbImpl();
// SQLite can't do the net masking stuff we need to match IP address ranges.
// So just pull down the whole list into memory.
var bans = await GetAllBans(db.SqliteDbContext, includeUnbanned: false);
return bans.FirstOrDefault(b => BanMatches(b, address, userId, hwId)) is { } foundBan
? ConvertBan(foundBan)
: null;
}
public override async Task<List<ServerBanDef>> GetServerBansAsync(IPAddress? address,
NetUserId? userId,
ImmutableArray<byte>? hwId, bool includeUnbanned)
{
await using var db = await GetDbImpl();
// SQLite can't do the net masking stuff we need to match IP address ranges.
// So just pull down the whole list into memory.
var queryBans = await GetAllBans(db.SqliteDbContext, includeUnbanned);
return queryBans
.Where(b => BanMatches(b, address, userId, hwId))
.Select(ConvertBan)
.ToList()!;
}
private static async Task<List<ServerBan>> GetAllBans(
SqliteServerDbContext db,
bool includeUnbanned)
{
IQueryable<ServerBan> query = db.Ban.Include(p => p.Unban);
if (!includeUnbanned)
{
query = query.Where(p =>
p.Unban == null && (p.ExpirationTime == null || p.ExpirationTime.Value > DateTime.UtcNow));
}
return await query.ToListAsync();
}
private static bool BanMatches(
ServerBan ban,
IPAddress? address,
NetUserId? userId,
ImmutableArray<byte>? hwId)
{
if (address != null && ban.Address is not null && IPAddressExt.IsInSubnet(address, ban.Address.Value))
{
return true;
}
if (userId is { } id && ban.UserId == id.UserId)
{
return true;
}
if (hwId is { } hwIdVar && hwIdVar.AsSpan().SequenceEqual(ban.HWId))
{
return true;
}
return false;
}
public override async Task AddServerBanAsync(ServerBanDef serverBan)
{
await using var db = await GetDbImpl();
db.SqliteDbContext.Ban.Add(new ServerBan
{
Address = serverBan.Address,
Reason = serverBan.Reason,
BanningAdmin = serverBan.BanningAdmin?.UserId,
HWId = serverBan.HWId?.ToArray(),
BanTime = serverBan.BanTime.UtcDateTime,
ExpirationTime = serverBan.ExpirationTime?.UtcDateTime,
UserId = serverBan.UserId?.UserId
});
await db.SqliteDbContext.SaveChangesAsync();
}
public override async Task AddServerUnbanAsync(ServerUnbanDef serverUnban)
{
await using var db = await GetDbImpl();
db.SqliteDbContext.Unban.Add(new ServerUnban
{
BanId = serverUnban.BanId,
UnbanningAdmin = serverUnban.UnbanningAdmin?.UserId,
UnbanTime = serverUnban.UnbanTime.UtcDateTime
});
await db.SqliteDbContext.SaveChangesAsync();
}
#endregion
#region Role Ban
public override async Task<ServerRoleBanDef?> GetServerRoleBanAsync(int id)
{
await using var db = await GetDbImpl();
var ban = await db.SqliteDbContext.RoleBan
.Include(p => p.Unban)
.Where(p => p.Id == id)
.SingleOrDefaultAsync();
return ConvertRoleBan(ban);
}
public override async Task<List<ServerRoleBanDef>> GetServerRoleBansAsync(IPAddress? address,
NetUserId? userId,
ImmutableArray<byte>? hwId,
bool includeUnbanned)
{
await using var db = await GetDbImpl();
// SQLite can't do the net masking stuff we need to match IP address ranges.
// So just pull down the whole list into memory.
var queryBans = await GetAllRoleBans(db.SqliteDbContext, includeUnbanned);
return queryBans
.Where(b => RoleBanMatches(b, address, userId, hwId))
.Select(ConvertRoleBan)
.ToList()!;
}
private static async Task<List<ServerRoleBan>> GetAllRoleBans(
SqliteServerDbContext db,
bool includeUnbanned)
{
IQueryable<ServerRoleBan> query = db.RoleBan.Include(p => p.Unban);
if (!includeUnbanned)
{
query = query.Where(p =>
p.Unban == null && (p.ExpirationTime == null || p.ExpirationTime.Value > DateTime.UtcNow));
}
return await query.ToListAsync();
}
private static bool RoleBanMatches(
ServerRoleBan ban,
IPAddress? address,
NetUserId? userId,
ImmutableArray<byte>? hwId)
{
if (address != null && ban.Address is not null && IPAddressExt.IsInSubnet(address, ban.Address.Value))
{
return true;
}
if (userId is { } id && ban.UserId == id.UserId)
{
return true;
}
if (hwId is { } hwIdVar && hwIdVar.AsSpan().SequenceEqual(ban.HWId))
{
return true;
}
return false;
}
public override async Task AddServerRoleBanAsync(ServerRoleBanDef serverBan)
{
await using var db = await GetDbImpl();
db.SqliteDbContext.RoleBan.Add(new ServerRoleBan
{
Address = serverBan.Address,
Reason = serverBan.Reason,
BanningAdmin = serverBan.BanningAdmin?.UserId,
HWId = serverBan.HWId?.ToArray(),
BanTime = serverBan.BanTime.UtcDateTime,
ExpirationTime = serverBan.ExpirationTime?.UtcDateTime,
UserId = serverBan.UserId?.UserId,
RoleId = serverBan.Role,
});
await db.SqliteDbContext.SaveChangesAsync();
}
public override async Task AddServerRoleUnbanAsync(ServerRoleUnbanDef serverUnban)
{
await using var db = await GetDbImpl();
db.SqliteDbContext.RoleUnban.Add(new ServerRoleUnban
{
BanId = serverUnban.BanId,
UnbanningAdmin = serverUnban.UnbanningAdmin?.UserId,
UnbanTime = serverUnban.UnbanTime.UtcDateTime
});
await db.SqliteDbContext.SaveChangesAsync();
}
private static ServerRoleBanDef? ConvertRoleBan(ServerRoleBan? ban)
{
if (ban == null)
{
return null;
}
NetUserId? uid = null;
if (ban.UserId is { } guid)
{
uid = new NetUserId(guid);
}
NetUserId? aUid = null;
if (ban.BanningAdmin is { } aGuid)
{
aUid = new NetUserId(aGuid);
}
var unban = ConvertRoleUnban(ban.Unban);
return new ServerRoleBanDef(
ban.Id,
uid,
ban.Address,
ban.HWId == null ? null : ImmutableArray.Create(ban.HWId),
ban.BanTime,
ban.ExpirationTime,
ban.Reason,
aUid,
unban,
ban.RoleId);
}
private static ServerRoleUnbanDef? ConvertRoleUnban(ServerRoleUnban? unban)
{
if (unban == null)
{
return null;
}
NetUserId? aUid = null;
if (unban.UnbanningAdmin is { } aGuid)
{
aUid = new NetUserId(aGuid);
}
return new ServerRoleUnbanDef(
unban.Id,
aUid,
unban.UnbanTime);
}
#endregion
protected override PlayerRecord MakePlayerRecord(Player record)
{
return new PlayerRecord(
new NetUserId(record.UserId),
new DateTimeOffset(record.FirstSeenTime, TimeSpan.Zero),
record.LastSeenUserName,
new DateTimeOffset(record.LastSeenTime, TimeSpan.Zero),
record.LastSeenAddress,
record.LastSeenHWId?.ToImmutableArray());
}
private static ServerBanDef? ConvertBan(ServerBan? ban)
{
if (ban == null)
{
return null;
}
NetUserId? uid = null;
if (ban.UserId is { } guid)
{
uid = new NetUserId(guid);
}
NetUserId? aUid = null;
if (ban.BanningAdmin is { } aGuid)
{
aUid = new NetUserId(aGuid);
}
var unban = ConvertUnban(ban.Unban);
return new ServerBanDef(
ban.Id,
uid,
ban.Address,
ban.HWId == null ? null : ImmutableArray.Create(ban.HWId),
ban.BanTime,
ban.ExpirationTime,
ban.Reason,
aUid,
unban);
}
private static ServerUnbanDef? ConvertUnban(ServerUnban? unban)
{
if (unban == null)
{
return null;
}
NetUserId? aUid = null;
if (unban.UnbanningAdmin is { } aGuid)
{
aUid = new NetUserId(aGuid);
}
return new ServerUnbanDef(
unban.Id,
aUid,
unban.UnbanTime);
}
public override async Task<int> AddConnectionLogAsync(
NetUserId userId,
string userName,
IPAddress address,
ImmutableArray<byte> hwId,
ConnectionDenyReason? denied)
{
await using var db = await GetDbImpl();
var connectionLog = new ConnectionLog
{
Address = address,
Time = DateTime.UtcNow,
UserId = userId.UserId,
UserName = userName,
HWId = hwId.ToArray(),
Denied = denied
};
db.SqliteDbContext.ConnectionLog.Add(connectionLog);
await db.SqliteDbContext.SaveChangesAsync();
return connectionLog.Id;
}
public override async Task<((Admin, string? lastUserName)[] admins, AdminRank[])> GetAllAdminAndRanksAsync(
CancellationToken cancel)
{
await using var db = await GetDbImpl();
var admins = await db.SqliteDbContext.Admin
.Include(a => a.Flags)
.GroupJoin(db.SqliteDbContext.Player, a => a.UserId, p => p.UserId, (a, grouping) => new {a, grouping})
.SelectMany(t => t.grouping.DefaultIfEmpty(), (t, p) => new {t.a, p!.LastSeenUserName})
.ToArrayAsync(cancel);
var adminRanks = await db.DbContext.AdminRank.Include(a => a.Flags).ToArrayAsync(cancel);
return (admins.Select(p => (p.a, p.LastSeenUserName)).ToArray(), adminRanks)!;
}
public override async Task<int> AddNewRound(params Guid[] playerIds)
{
await using var db = await GetDb();
var players = await db.DbContext.Player
.Where(player => playerIds.Contains(player.UserId))
.ToListAsync();
var nextId = 1;
if (await db.DbContext.Round.AnyAsync())
{
nextId = db.DbContext.Round.Max(round => round.Id) + 1;
}
var round = new Round
{
Id = nextId,
Players = players
};
db.DbContext.Round.Add(round);
await db.DbContext.SaveChangesAsync();
return round.Id;
}
public override async Task AddAdminLogs(List<QueuedLog> logs)
{
await using var db = await GetDb();
var nextId = 1;
if (await db.DbContext.AdminLog.AnyAsync())
{
nextId = db.DbContext.AdminLog.Max(round => round.Id) + 1;
}
var entities = new Dictionary<int, AdminLogEntity>();
foreach (var (log, entityData) in logs)
{
log.Id = nextId++;
var logEntities = new List<AdminLogEntity>(entityData.Count);
foreach (var (id, name) in entityData)
{
var entity = entities.GetOrNew(id);
entity.Name = name;
logEntities.Add(entity);
}
foreach (var player in log.Players)
{
player.LogId = log.Id;
}
log.Entities = logEntities;
db.DbContext.AdminLog.Add(log);
}
await db.DbContext.SaveChangesAsync();
}
private async Task<DbGuardImpl> GetDbImpl()
{
await _dbReadyTask;
if (_msDelay > 0)
await Task.Delay(_msDelay);
await _prefsSemaphore.WaitAsync();
return new DbGuardImpl(this);
}
protected override async Task<DbGuard> GetDb()
{
return await GetDbImpl();
}
private sealed class DbGuardImpl : DbGuard
{
private readonly ServerDbSqlite _db;
public DbGuardImpl(ServerDbSqlite db)
{
_db = db;
}
public override ServerDbContext DbContext => _db._prefsCtx;
public SqliteServerDbContext SqliteDbContext => _db._prefsCtx;
public override ValueTask DisposeAsync()
{
_db._prefsSemaphore.Release();
return default;
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.HSSF.Record.CF
{
using System;
using System.Text;
using System.Collections;
using NPOI.SS.Util;
/**
*
* @author Dmitriy Kumshayev
*/
internal class CellRangeUtil
{
private CellRangeUtil()
{
// no instance of this class
}
public const int NO_INTERSECTION = 1;
public const int OVERLAP = 2;
/** first range is within the second range */
public const int INSIDE = 3;
/** first range encloses or is equal to the second */
public const int ENCLOSES = 4;
/**
* Intersect this range with the specified range.
*
* @param crB - the specified range
* @return code which reflects how the specified range is related to this range.<br/>
* Possible return codes are:
* NO_INTERSECTION - the specified range is outside of this range;<br/>
* OVERLAP - both ranges partially overlap;<br/>
* INSIDE - the specified range is inside of this one<br/>
* ENCLOSES - the specified range encloses (possibly exactly the same as) this range<br/>
*/
public static int Intersect(CellRangeAddress crA, CellRangeAddress crB)
{
int firstRow = crB.FirstRow;
int lastRow = crB.LastRow;
int firstCol = crB.FirstColumn;
int lastCol = crB.LastColumn;
if
(
gt(crA.FirstRow, lastRow) ||
lt(crA.LastRow, firstRow) ||
gt(crA.FirstColumn, lastCol) ||
lt(crA.LastColumn, firstCol)
)
{
return NO_INTERSECTION;
}
else if (Contains(crA, crB))
{
return INSIDE;
}
else if (Contains(crB, crA))
{
return ENCLOSES;
}
else
{
return OVERLAP;
}
}
/**
* Do all possible cell merges between cells of the list so that:
* if a cell range is completely inside of another cell range, it s removed from the list
* if two cells have a shared border, merge them into one bigger cell range
* @param cellRangeList
* @return updated List of cell ranges
*/
public static CellRangeAddress[] MergeCellRanges(CellRangeAddress[] cellRanges)
{
if (cellRanges.Length < 1)
{
return cellRanges;
}
ArrayList temp = MergeCellRanges(NPOI.Util.Arrays.AsList(cellRanges));
return ToArray(temp);
}
private static ArrayList MergeCellRanges(ArrayList cellRangeList)
{
while(cellRangeList.Count > 1)
{
bool somethingGotMerged = false;
for( int i=0; i<cellRangeList.Count; i++)
{
CellRangeAddress range1 = (CellRangeAddress)cellRangeList[i];
for( int j=i+1; j<cellRangeList.Count; j++)
{
CellRangeAddress range2 = (CellRangeAddress)cellRangeList[j];
CellRangeAddress[] mergeResult = MergeRanges(range1, range2);
if(mergeResult == null) {
continue;
}
somethingGotMerged = true;
// overwrite range1 with first result
cellRangeList[i]= mergeResult[0];
// remove range2
cellRangeList.RemoveAt(j--);
// Add any extra results beyond the first
for(int k=1; k<mergeResult.Length; k++) {
j++;
cellRangeList.Insert(j, mergeResult[k]);
}
}
}
if(!somethingGotMerged) {
break;
}
}
return cellRangeList;
}
/**
* @return the new range(s) to replace the supplied ones. <c>null</c> if no merge is possible
*/
private static CellRangeAddress[] MergeRanges(CellRangeAddress range1, CellRangeAddress range2)
{
int x = Intersect(range1, range2);
switch (x)
{
case CellRangeUtil.NO_INTERSECTION:
if (HasExactSharedBorder(range1, range2))
{
return new CellRangeAddress[] { CreateEnclosingCellRange(range1, range2), };
}
// else - No intersection and no shared border: do nothing
return null;
case CellRangeUtil.OVERLAP:
return ResolveRangeOverlap(range1, range2);
case CellRangeUtil.INSIDE:
// Remove range2, since it is completely inside of range1
return new CellRangeAddress[] { range1, };
case CellRangeUtil.ENCLOSES:
// range2 encloses range1, so replace it with the enclosing one
return new CellRangeAddress[] { range2, };
}
throw new InvalidOperationException("unexpected intersection result (" + x + ")");
}
// TODO - write junit test for this
static CellRangeAddress[] ResolveRangeOverlap(CellRangeAddress rangeA, CellRangeAddress rangeB)
{
if (rangeA.IsFullColumnRange)
{
if (rangeA.IsFullRowRange)
{
// Excel seems to leave these unresolved
return null;
}
return SliceUp(rangeA, rangeB);
}
if (rangeA.IsFullRowRange)
{
if (rangeB.IsFullColumnRange)
{
// Excel seems to leave these unresolved
return null;
}
return SliceUp(rangeA, rangeB);
}
if (rangeB.IsFullColumnRange)
{
return SliceUp(rangeB, rangeA);
}
if (rangeB.IsFullRowRange)
{
return SliceUp(rangeB, rangeA);
}
return SliceUp(rangeA, rangeB);
}
/**
* @param crB never a full row or full column range
* @return an array including <b>this</b> <c>CellRange</c> and all parts of <c>range</c>
* outside of this range
*/
private static CellRangeAddress[] SliceUp(CellRangeAddress crA, CellRangeAddress crB)
{
ArrayList temp = new ArrayList();
// Chop up range horizontally and vertically
temp.Add(crB);
if (!crA.IsFullColumnRange)
{
temp = CutHorizontally(crA.FirstRow, temp);
temp = CutHorizontally(crA.LastRow + 1, temp);
}
if (!crA.IsFullRowRange)
{
temp = CutVertically(crA.FirstColumn, temp);
temp = CutVertically(crA.LastColumn + 1, temp);
}
CellRangeAddress[] crParts = ToArray(temp);
// form result array
temp.Clear();
temp.Add(crA);
for (int i = 0; i < crParts.Length; i++)
{
CellRangeAddress crPart = crParts[i];
// only include parts that are not enclosed by this
if (Intersect(crA, crPart) != ENCLOSES)
{
temp.Add(crPart);
}
}
return ToArray(temp);
}
private static ArrayList CutHorizontally(int cutRow, ArrayList input)
{
ArrayList result = new ArrayList();
CellRangeAddress[] crs = ToArray(input);
for (int i = 0; i < crs.Length; i++)
{
CellRangeAddress cr = crs[i];
if (cr.FirstRow < cutRow && cutRow < cr.LastRow)
{
result.Add(new CellRangeAddress(cr.FirstRow, cutRow, cr.FirstColumn, cr.LastColumn));
result.Add(new CellRangeAddress(cutRow + 1, cr.LastRow, cr.FirstColumn, cr.LastColumn));
}
else
{
result.Add(cr);
}
}
return result;
}
private static ArrayList CutVertically(int cutColumn, ArrayList input)
{
ArrayList result = new ArrayList();
CellRangeAddress[] crs = ToArray(input);
for (int i = 0; i < crs.Length; i++)
{
CellRangeAddress cr = crs[i];
if (cr.FirstColumn < cutColumn && cutColumn < cr.LastColumn)
{
result.Add(new CellRangeAddress(cr.FirstRow, cr.LastRow, cr.FirstColumn, cutColumn));
result.Add(new CellRangeAddress(cr.FirstRow, cr.LastRow, cutColumn + 1, cr.LastColumn));
}
else
{
result.Add(cr);
}
}
return result;
}
private static CellRangeAddress[] ToArray(ArrayList temp)
{
CellRangeAddress[] result = new CellRangeAddress[temp.Count];
result = (CellRangeAddress[])temp.ToArray(typeof(CellRangeAddress));
return result;
}
/**
* Check if the specified range is located inside of this cell range.
*
* @param crB
* @return true if this cell range Contains the argument range inside if it's area
*/
public static bool Contains(CellRangeAddress crA, CellRangeAddress crB)
{
int firstRow = crB.FirstRow;
int lastRow = crB.LastRow;
int firstCol = crB.FirstColumn;
int lastCol = crB.LastColumn;
return le(crA.FirstRow, firstRow) && ge(crA.LastRow, lastRow)
&& le(crA.FirstColumn, firstCol) && ge(crA.LastColumn, lastCol);
}
/**
* Check if the specified cell range has a shared border with the current range.
*
* @return <c>true</c> if the ranges have a complete shared border (i.e.
* the two ranges toher make a simple rectangular region.
*/
public static bool HasExactSharedBorder(CellRangeAddress crA, CellRangeAddress crB)
{
int oFirstRow = crB.FirstRow;
int oLastRow = crB.LastRow;
int oFirstCol = crB.FirstColumn;
int oLastCol = crB.LastColumn;
if (crA.FirstRow > 0 && crA.FirstRow - 1 == oLastRow ||
oFirstRow > 0 && oFirstRow - 1 == crA.LastRow)
{
// ranges have a horizontal border in common
// make sure columns are identical:
return crA.FirstColumn == oFirstCol && crA.LastColumn == oLastCol;
}
if (crA.FirstColumn > 0 && crA.FirstColumn - 1 == oLastCol ||
oFirstCol > 0 && crA.LastColumn == oFirstCol - 1)
{
// ranges have a vertical border in common
// make sure rows are identical:
return crA.FirstRow == oFirstRow && crA.LastRow == oLastRow;
}
return false;
}
/**
* Create an enclosing CellRange for the two cell ranges.
*
* @return enclosing CellRange
*/
public static CellRangeAddress CreateEnclosingCellRange(CellRangeAddress crA, CellRangeAddress crB)
{
if (crB == null)
{
return crA.Copy();
}
return
new CellRangeAddress(
lt(crB.FirstRow, crA.FirstRow) ? crB.FirstRow : crA.FirstRow,
gt(crB.LastRow, crA.LastRow) ? crB.LastRow : crA.LastRow,
lt(crB.FirstColumn, crA.FirstColumn) ? crB.FirstColumn : crA.FirstColumn,
gt(crB.LastColumn, crA.LastColumn) ? crB.LastColumn : crA.LastColumn
);
}
/**
* @return true if a < b
*/
private static bool lt(int a, int b)
{
return a == -1 ? false : (b == -1 ? true : a < b);
}
/**
* @return true if a <= b
*/
private static bool le(int a, int b)
{
return a == b || lt(a, b);
}
/**
* @return true if a > b
*/
private static bool gt(int a, int b)
{
return lt(b, a);
}
/**
* @return true if a >= b
*/
private static bool ge(int a, int b)
{
return !lt(a, b);
}
}
}
| |
using Xunit;
namespace Jint.Tests.Ecma
{
public class Test_7_6_1_2 : EcmaTest
{
[Fact]
[Trait("Category", "7.6.1.2")]
public void StrictModeSyntaxerrorIsThrownWhenFuturereservedwordImplementsOccursInStrictModeCode()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2-1gs.js", true);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void StrictModeSyntaxerrorIsThrownWhenFuturereservedwordImplementsOccursInStrictModeCode2()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/7.6.1.2-1-s.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void StrictModeSyntaxerrorIsnTThrownWhenImplementsOccursInStrictModeCode()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/7.6.1.2-10-s.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void StrictModeSyntaxerrorIsnTThrownWhenImplementsOccursInStrictModeCode2()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/7.6.1.2-11-s.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void StrictModeSyntaxerrorIsnTThrownWhenImplementOccursInStrictModeCode()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/7.6.1.2-12-s.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void StrictModeSyntaxerrorIsnTThrownWhenImplementssOccursInStrictModeCode()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/7.6.1.2-13-s.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void StrictModeSyntaxerrorIsnTThrownWhenImplements0OccursInStrictModeCode()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/7.6.1.2-14-s.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void StrictModeSyntaxerrorIsnTThrownWhenImplementsOccursInStrictModeCode3()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/7.6.1.2-16-s.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void StrictModeSyntaxerrorIsThrownWhenFuturereservedwordLetOccursInStrictModeCode()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/7.6.1.2-2-s.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void StrictModeSyntaxerrorIsThrownWhenFuturereservedwordPrivateOccursInStrictModeCode()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/7.6.1.2-3-s.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void StrictModeSyntaxerrorIsThrownWhenFuturereservedwordPublicOccursInStrictModeCode()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/7.6.1.2-4-s.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void StrictModeSyntaxerrorIsThrownWhenFuturereservedwordYieldOccursInStrictModeCode()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/7.6.1.2-5-s.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void StrictModeSyntaxerrorIsThrownWhenFuturereservedwordInterfaceOccursInStrictModeCode()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/7.6.1.2-6-s.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void StrictModeSyntaxerrorIsThrownWhenFuturereservedwordPackageOccursInStrictModeCode()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/7.6.1.2-7-s.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void StrictModeSyntaxerrorIsThrownWhenFuturereservedwordProtectedOccursInStrictModeCode()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/7.6.1.2-8-s.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void StrictModeSyntaxerrorIsThrownWhenFuturereservedwordStaticOccursInStrictModeCode()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/7.6.1.2-9-s.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheAbstractTokenCanBeUsedAsIdentifier()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.1.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheExportTokenCanNotBeUsedAsIdentifier()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.10.js", true);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheExtendsTokenCanNotBeUsedAsIdentifier()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.11.js", true);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheFinalTokenCanBeUsedAsIdentifier()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.12.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheFloatTokenCanBeUsedAsIdentifier()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.13.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheGotoTokenCanBeUsedAsIdentifier()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.14.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheImplementsTokenCanNotBeUsedAsIdentifierInStrictCode()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.15.js", true);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheImplementsTokenCanBeUsedAsIdentifierInNonStrictCode()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.15ns.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheImportTokenCanNotBeUsedAsIdentifier()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.16.js", true);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheIntTokenCanBeUsedAsIdentifier()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.17.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheInterfaceTokenCanNotBeUsedAsIdentifierInStrictCode()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.18.js", true);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheInterfaceTokenCanBeUsedAsIdentifierInNonStrictCode()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.18ns.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheLongTokenCanBeUsedAsIdentifier()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.19.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheBooleanTokenCanBeUsedAsIdentifier()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.2.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheNativeTokenCanBeUsedAsIdentifier()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.20.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void ThePackageTokenCanNotBeUsedAsIdentifierInStrictCode()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.21.js", true);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void ThePackageTokenCanBeUsedAsIdentifierInNonStrictCode()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.21ns.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void ThePrivateTokenCanNotBeUsedAsIdentifierInStrictCode()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.22.js", true);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void ThePrivateTokenCanBeUsedAsIdentifierInNonStrictCode()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.22ns.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheProtectedTokenCanNotBeUsedAsIdentifierInStrictCode()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.23.js", true);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheProtectedTokenCanBeUsedAsIdentifierInNonStrictCode()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.23ns.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void ThePublicTokenCanNotBeUsedAsIdentifierInStrictCode()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.24.js", true);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void ThePublicTokenCanBeUsedAsIdentifierInNonStrictCode()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.24ns.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheShortTokenCanBeUsedAsIdentifier()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.25.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheStaticTokenCanNotBeUsedAsIdentifierInStrictCode()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.26.js", true);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheStaticTokenCanBeUsedAsIdentifierInNonStrictCode()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.26ns.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheSuperTokenCanNotBeUsedAsIdentifier()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.27.js", true);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheSynchronizedTokenCanBeUsedAsIdentifier()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.28.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheThrowsTokenCanBeUsedAsIdentifier()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.29.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheByteTokenCanBeUsedAsIdentifier()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.3.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheTransientTokenCanBeUsedAsIdentifier()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.30.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheVolatileTokenCanBeUsedAsIdentifier()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.31.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheCharTokenCanBeUsedAsIdentifier()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.4.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheClassTokenCanNotBeUsedAsIdentifier()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.5.js", true);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheConstTokenCanNotBeUsedAsIdentifier()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.6.js", true);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheDebuggerTokenCanNotBeUsedAsIdentifier()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.7.js", true);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheDoubleTokenCanBeUsedAsIdentifier()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.8.js", false);
}
[Fact]
[Trait("Category", "7.6.1.2")]
public void TheEnumTokenCanNotBeUsedAsIdentifier()
{
RunTest(@"TestCases/ch07/7.6/7.6.1/7.6.1.2/S7.6.1.2_A1.9.js", true);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading;
namespace System.Diagnostics
{
public partial class Process : IDisposable
{
/// <summary>
/// Puts a Process component in state to interact with operating system processes that run in a
/// special mode by enabling the native property SeDebugPrivilege on the current thread.
/// </summary>
public static void EnterDebugMode()
{
SetPrivilege(Interop.mincore.SeDebugPrivilege, (int)Interop.mincore.SEPrivileges.SE_PRIVILEGE_ENABLED);
}
/// <summary>
/// Takes a Process component out of the state that lets it interact with operating system processes
/// that run in a special mode.
/// </summary>
public static void LeaveDebugMode()
{
SetPrivilege(Interop.mincore.SeDebugPrivilege, 0);
}
/// <summary>Stops the associated process immediately.</summary>
public void Kill()
{
SafeProcessHandle handle = null;
try
{
handle = GetProcessHandle(Interop.mincore.ProcessOptions.PROCESS_TERMINATE);
if (!Interop.mincore.TerminateProcess(handle, -1))
throw new Win32Exception();
}
finally
{
ReleaseProcessHandle(handle);
}
}
/// <summary>Discards any information about the associated process.</summary>
private void RefreshCore()
{
_signaled = false;
}
/// <summary>Additional logic invoked when the Process is closed.</summary>
private void CloseCore()
{
// Nop
}
/// <summary>
/// Instructs the Process component to wait the specified number of milliseconds for the associated process to exit.
/// </summary>
private bool WaitForExitCore(int milliseconds)
{
SafeProcessHandle handle = null;
bool exited;
ProcessWaitHandle processWaitHandle = null;
try
{
handle = GetProcessHandle(Interop.mincore.ProcessOptions.SYNCHRONIZE, false);
if (handle.IsInvalid)
{
exited = true;
}
else
{
processWaitHandle = new ProcessWaitHandle(handle);
if (processWaitHandle.WaitOne(milliseconds))
{
exited = true;
_signaled = true;
}
else
{
exited = false;
_signaled = false;
}
}
}
finally
{
if (processWaitHandle != null)
{
processWaitHandle.Dispose();
}
// If we have a hard timeout, we cannot wait for the streams
if (_output != null && milliseconds == Timeout.Infinite)
{
_output.WaitUtilEOF();
}
if (_error != null && milliseconds == Timeout.Infinite)
{
_error.WaitUtilEOF();
}
ReleaseProcessHandle(handle);
}
return exited;
}
/// <summary>Gets the main module for the associated process.</summary>
public ProcessModule MainModule
{
get
{
// We only return null if we couldn't find a main module. This could be because
// the process hasn't finished loading the main module (most likely).
// On NT, the first module is the main module.
EnsureState(State.HaveId | State.IsLocal);
ModuleInfo module = NtProcessManager.GetFirstModuleInfo(_processId);
return (module != null ? new ProcessModule(module) : null);
}
}
/// <summary>Checks whether the process has exited and updates state accordingly.</summary>
private void UpdateHasExited()
{
SafeProcessHandle handle = null;
try
{
handle = GetProcessHandle(Interop.mincore.ProcessOptions.PROCESS_QUERY_LIMITED_INFORMATION | Interop.mincore.ProcessOptions.SYNCHRONIZE, false);
if (handle.IsInvalid)
{
_exited = true;
}
else
{
int localExitCode;
// Although this is the wrong way to check whether the process has exited,
// it was historically the way we checked for it, and a lot of code then took a dependency on
// the fact that this would always be set before the pipes were closed, so they would read
// the exit code out after calling ReadToEnd() or standard output or standard error. In order
// to allow 259 to function as a valid exit code and to break as few people as possible that
// took the ReadToEnd dependency, we check for an exit code before doing the more correct
// check to see if we have been signalled.
if (Interop.mincore.GetExitCodeProcess(handle, out localExitCode) && localExitCode != Interop.mincore.HandleOptions.STILL_ACTIVE)
{
_exitCode = localExitCode;
_exited = true;
}
else
{
// The best check for exit is that the kernel process object handle is invalid,
// or that it is valid and signaled. Checking if the exit code != STILL_ACTIVE
// does not guarantee the process is closed,
// since some process could return an actual STILL_ACTIVE exit code (259).
if (!_signaled) // if we just came from WaitForExit, don't repeat
{
using (var wh = new ProcessWaitHandle(handle))
{
_signaled = wh.WaitOne(0);
}
}
if (_signaled)
{
if (!Interop.mincore.GetExitCodeProcess(handle, out localExitCode))
throw new Win32Exception();
_exitCode = localExitCode;
_exited = true;
}
}
}
}
finally
{
ReleaseProcessHandle(handle);
}
}
/// <summary>Gets the time that the associated process exited.</summary>
private DateTime ExitTimeCore
{
get { return GetProcessTimes().ExitTime; }
}
/// <summary>Gets the amount of time the process has spent running code inside the operating system core.</summary>
public TimeSpan PrivilegedProcessorTime
{
get { return GetProcessTimes().PrivilegedProcessorTime; }
}
/// <summary>Gets the time the associated process was started.</summary>
public DateTime StartTime
{
get { return GetProcessTimes().StartTime; }
}
/// <summary>
/// Gets the amount of time the associated process has spent utilizing the CPU.
/// It is the sum of the <see cref='System.Diagnostics.Process.UserProcessorTime'/> and
/// <see cref='System.Diagnostics.Process.PrivilegedProcessorTime'/>.
/// </summary>
public TimeSpan TotalProcessorTime
{
get { return GetProcessTimes().TotalProcessorTime; }
}
/// <summary>
/// Gets the amount of time the associated process has spent running code
/// inside the application portion of the process (not the operating system core).
/// </summary>
public TimeSpan UserProcessorTime
{
get { return GetProcessTimes().UserProcessorTime; }
}
/// <summary>
/// Gets or sets a value indicating whether the associated process priority
/// should be temporarily boosted by the operating system when the main window
/// has focus.
/// </summary>
private bool PriorityBoostEnabledCore
{
get
{
SafeProcessHandle handle = null;
try
{
handle = GetProcessHandle(Interop.mincore.ProcessOptions.PROCESS_QUERY_INFORMATION);
bool disabled;
if (!Interop.mincore.GetProcessPriorityBoost(handle, out disabled))
{
throw new Win32Exception();
}
return !disabled;
}
finally
{
ReleaseProcessHandle(handle);
}
}
set
{
SafeProcessHandle handle = null;
try
{
handle = GetProcessHandle(Interop.mincore.ProcessOptions.PROCESS_SET_INFORMATION);
if (!Interop.mincore.SetProcessPriorityBoost(handle, !value))
throw new Win32Exception();
}
finally
{
ReleaseProcessHandle(handle);
}
}
}
/// <summary>
/// Gets or sets the overall priority category for the associated process.
/// </summary>
private ProcessPriorityClass PriorityClassCore
{
get
{
SafeProcessHandle handle = null;
try
{
handle = GetProcessHandle(Interop.mincore.ProcessOptions.PROCESS_QUERY_INFORMATION);
int value = Interop.mincore.GetPriorityClass(handle);
if (value == 0)
{
throw new Win32Exception();
}
return (ProcessPriorityClass)value;
}
finally
{
ReleaseProcessHandle(handle);
}
}
set
{
SafeProcessHandle handle = null;
try
{
handle = GetProcessHandle(Interop.mincore.ProcessOptions.PROCESS_SET_INFORMATION);
if (!Interop.mincore.SetPriorityClass(handle, (int)value))
{
throw new Win32Exception();
}
}
finally
{
ReleaseProcessHandle(handle);
}
}
}
/// <summary>
/// Gets or sets which processors the threads in this process can be scheduled to run on.
/// </summary>
private IntPtr ProcessorAffinityCore
{
get
{
SafeProcessHandle handle = null;
try
{
handle = GetProcessHandle(Interop.mincore.ProcessOptions.PROCESS_QUERY_INFORMATION);
IntPtr processAffinity, systemAffinity;
if (!Interop.mincore.GetProcessAffinityMask(handle, out processAffinity, out systemAffinity))
throw new Win32Exception();
return processAffinity;
}
finally
{
ReleaseProcessHandle(handle);
}
}
set
{
SafeProcessHandle handle = null;
try
{
handle = GetProcessHandle(Interop.mincore.ProcessOptions.PROCESS_SET_INFORMATION);
if (!Interop.mincore.SetProcessAffinityMask(handle, value))
throw new Win32Exception();
}
finally
{
ReleaseProcessHandle(handle);
}
}
}
/// <summary>Gets the ID of the current process.</summary>
private static int GetCurrentProcessId()
{
return unchecked((int)Interop.mincore.GetCurrentProcessId());
}
/// <summary>
/// Gets a short-term handle to the process, with the given access. If a handle exists,
/// then it is reused. If the process has exited, it throws an exception.
/// </summary>
private SafeProcessHandle GetProcessHandle()
{
return GetProcessHandle(Interop.mincore.ProcessOptions.PROCESS_ALL_ACCESS);
}
/// <summary>Get the minimum and maximum working set limits.</summary>
private void GetWorkingSetLimits(out IntPtr minWorkingSet, out IntPtr maxWorkingSet)
{
SafeProcessHandle handle = null;
try
{
handle = GetProcessHandle(Interop.mincore.ProcessOptions.PROCESS_QUERY_INFORMATION);
// GetProcessWorkingSetSize is not exposed in coresys. We use
// GetProcessWorkingSetSizeEx instead which also returns FLAGS which give some flexibility
// in terms of Min and Max values which we neglect.
int ignoredFlags;
if (!Interop.mincore.GetProcessWorkingSetSizeEx(handle, out minWorkingSet, out maxWorkingSet, out ignoredFlags))
{
throw new Win32Exception();
}
}
finally
{
ReleaseProcessHandle(handle);
}
}
/// <summary>Sets one or both of the minimum and maximum working set limits.</summary>
/// <param name="newMin">The new minimum working set limit, or null not to change it.</param>
/// <param name="newMax">The new maximum working set limit, or null not to change it.</param>
/// <param name="resultingMin">The resulting minimum working set limit after any changes applied.</param>
/// <param name="resultingMax">The resulting maximum working set limit after any changes applied.</param>
private void SetWorkingSetLimitsCore(IntPtr? newMin, IntPtr? newMax, out IntPtr resultingMin, out IntPtr resultingMax)
{
SafeProcessHandle handle = null;
try
{
handle = GetProcessHandle(Interop.mincore.ProcessOptions.PROCESS_QUERY_INFORMATION | Interop.mincore.ProcessOptions.PROCESS_SET_QUOTA);
IntPtr min, max;
int ignoredFlags;
if (!Interop.mincore.GetProcessWorkingSetSizeEx(handle, out min, out max, out ignoredFlags))
{
throw new Win32Exception();
}
if (newMin.HasValue)
{
min = newMin.Value;
}
if (newMax.HasValue)
{
max = newMax.Value;
}
if ((long)min > (long)max)
{
if (newMin != null)
{
throw new ArgumentException(SR.BadMinWorkset);
}
else
{
throw new ArgumentException(SR.BadMaxWorkset);
}
}
// We use SetProcessWorkingSetSizeEx which gives an option to follow
// the max and min value even in low-memory and abundant-memory situations.
// However, we do not use these flags to emulate the existing behavior
if (!Interop.mincore.SetProcessWorkingSetSizeEx(handle, min, max, 0))
{
throw new Win32Exception();
}
// The value may be rounded/changed by the OS, so go get it
if (!Interop.mincore.GetProcessWorkingSetSizeEx(handle, out min, out max, out ignoredFlags))
{
throw new Win32Exception();
}
resultingMin = min;
resultingMax = max;
}
finally
{
ReleaseProcessHandle(handle);
}
}
private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
/// <summary>Starts the process using the supplied start info.</summary>
/// <param name="startInfo">The start info with which to start the process.</param>
private bool StartCore(ProcessStartInfo startInfo)
{
// See knowledge base article Q190351 for an explanation of the following code. Noteworthy tricky points:
// * The handles are duplicated as non-inheritable before they are passed to CreateProcess so
// that the child process can not close them
// * CreateProcess allows you to redirect all or none of the standard IO handles, so we use
// GetStdHandle for the handles that are not being redirected
StringBuilder commandLine = BuildCommandLine(startInfo.FileName, startInfo.Arguments);
Interop.mincore.STARTUPINFO startupInfo = new Interop.mincore.STARTUPINFO();
Interop.mincore.PROCESS_INFORMATION processInfo = new Interop.mincore.PROCESS_INFORMATION();
Interop.mincore.SECURITY_ATTRIBUTES unused_SecAttrs = new Interop.mincore.SECURITY_ATTRIBUTES();
SafeProcessHandle procSH = new SafeProcessHandle();
SafeThreadHandle threadSH = new SafeThreadHandle();
bool retVal;
int errorCode = 0;
// handles used in parent process
SafeFileHandle standardInputWritePipeHandle = null;
SafeFileHandle standardOutputReadPipeHandle = null;
SafeFileHandle standardErrorReadPipeHandle = null;
GCHandle environmentHandle = new GCHandle();
lock (s_createProcessLock)
{
try
{
// set up the streams
if (startInfo.RedirectStandardInput || startInfo.RedirectStandardOutput || startInfo.RedirectStandardError)
{
if (startInfo.RedirectStandardInput)
{
CreatePipe(out standardInputWritePipeHandle, out startupInfo.hStdInput, true);
}
else
{
startupInfo.hStdInput = new SafeFileHandle(Interop.mincore.GetStdHandle(Interop.mincore.HandleTypes.STD_INPUT_HANDLE), false);
}
if (startInfo.RedirectStandardOutput)
{
CreatePipe(out standardOutputReadPipeHandle, out startupInfo.hStdOutput, false);
}
else
{
startupInfo.hStdOutput = new SafeFileHandle(Interop.mincore.GetStdHandle(Interop.mincore.HandleTypes.STD_OUTPUT_HANDLE), false);
}
if (startInfo.RedirectStandardError)
{
CreatePipe(out standardErrorReadPipeHandle, out startupInfo.hStdError, false);
}
else
{
startupInfo.hStdError = new SafeFileHandle(Interop.mincore.GetStdHandle(Interop.mincore.HandleTypes.STD_ERROR_HANDLE), false);
}
startupInfo.dwFlags = Interop.mincore.StartupInfoOptions.STARTF_USESTDHANDLES;
}
// set up the creation flags paramater
int creationFlags = 0;
if (startInfo.CreateNoWindow) creationFlags |= Interop.mincore.StartupInfoOptions.CREATE_NO_WINDOW;
// set up the environment block parameter
IntPtr environmentPtr = (IntPtr)0;
if (startInfo._environmentVariables != null)
{
creationFlags |= Interop.mincore.StartupInfoOptions.CREATE_UNICODE_ENVIRONMENT;
byte[] environmentBytes = EnvironmentVariablesToByteArray(startInfo._environmentVariables);
environmentHandle = GCHandle.Alloc(environmentBytes, GCHandleType.Pinned);
environmentPtr = environmentHandle.AddrOfPinnedObject();
}
string workingDirectory = startInfo.WorkingDirectory;
if (workingDirectory == string.Empty)
workingDirectory = Directory.GetCurrentDirectory();
if (startInfo.UserName.Length != 0)
{
Interop.mincore.LogonFlags logonFlags = (Interop.mincore.LogonFlags)0;
if (startInfo.LoadUserProfile)
{
logonFlags = Interop.mincore.LogonFlags.LOGON_WITH_PROFILE;
}
IntPtr password = IntPtr.Zero;
try
{
if (startInfo.Password == null)
{
password = Marshal.StringToCoTaskMemUni(String.Empty);
}
else
{
password = SecureStringMarshal.SecureStringToCoTaskMemUnicode(startInfo.Password);
}
try { }
finally
{
retVal = Interop.mincore.CreateProcessWithLogonW(
startInfo.UserName,
startInfo.Domain,
password,
logonFlags,
null, // we don't need this since all the info is in commandLine
commandLine,
creationFlags,
environmentPtr,
workingDirectory,
startupInfo, // pointer to STARTUPINFO
processInfo // pointer to PROCESS_INFORMATION
);
if (!retVal)
errorCode = Marshal.GetLastWin32Error();
if (processInfo.hProcess != IntPtr.Zero && processInfo.hProcess != (IntPtr)INVALID_HANDLE_VALUE)
procSH.InitialSetHandle(processInfo.hProcess);
if (processInfo.hThread != IntPtr.Zero && processInfo.hThread != (IntPtr)INVALID_HANDLE_VALUE)
threadSH.InitialSetHandle(processInfo.hThread);
}
if (!retVal)
{
if (errorCode == Interop.mincore.Errors.ERROR_BAD_EXE_FORMAT || errorCode == Interop.mincore.Errors.ERROR_EXE_MACHINE_TYPE_MISMATCH)
throw new Win32Exception(errorCode, SR.InvalidApplication);
throw new Win32Exception(errorCode);
}
}
finally
{
if (password != IntPtr.Zero)
{
Marshal.ZeroFreeCoTaskMemUnicode(password);
}
}
}
else
{
try { }
finally
{
retVal = Interop.mincore.CreateProcess(
null, // we don't need this since all the info is in commandLine
commandLine, // pointer to the command line string
ref unused_SecAttrs, // address to process security attributes, we don't need to inheriat the handle
ref unused_SecAttrs, // address to thread security attributes.
true, // handle inheritance flag
creationFlags, // creation flags
environmentPtr, // pointer to new environment block
workingDirectory, // pointer to current directory name
startupInfo, // pointer to STARTUPINFO
processInfo // pointer to PROCESS_INFORMATION
);
if (!retVal)
errorCode = Marshal.GetLastWin32Error();
if (processInfo.hProcess != (IntPtr)0 && processInfo.hProcess != (IntPtr)INVALID_HANDLE_VALUE)
procSH.InitialSetHandle(processInfo.hProcess);
if (processInfo.hThread != (IntPtr)0 && processInfo.hThread != (IntPtr)INVALID_HANDLE_VALUE)
threadSH.InitialSetHandle(processInfo.hThread);
}
if (!retVal)
{
if (errorCode == Interop.mincore.Errors.ERROR_BAD_EXE_FORMAT || errorCode == Interop.mincore.Errors.ERROR_EXE_MACHINE_TYPE_MISMATCH)
throw new Win32Exception(errorCode, SR.InvalidApplication);
throw new Win32Exception(errorCode);
}
}
}
finally
{
// free environment block
if (environmentHandle.IsAllocated)
{
environmentHandle.Free();
}
startupInfo.Dispose();
}
}
if (startInfo.RedirectStandardInput)
{
Encoding enc = GetEncoding((int)Interop.mincore.GetConsoleCP());
_standardInput = new StreamWriter(new FileStream(standardInputWritePipeHandle, FileAccess.Write, 4096, false), enc, 4096);
_standardInput.AutoFlush = true;
}
if (startInfo.RedirectStandardOutput)
{
Encoding enc = startInfo.StandardOutputEncoding ?? GetEncoding((int)Interop.mincore.GetConsoleOutputCP());
_standardOutput = new StreamReader(new FileStream(standardOutputReadPipeHandle, FileAccess.Read, 4096, false), enc, true, 4096);
}
if (startInfo.RedirectStandardError)
{
Encoding enc = startInfo.StandardErrorEncoding ?? GetEncoding((int)Interop.mincore.GetConsoleOutputCP());
_standardError = new StreamReader(new FileStream(standardErrorReadPipeHandle, FileAccess.Read, 4096, false), enc, true, 4096);
}
bool ret = false;
if (!procSH.IsInvalid)
{
SetProcessHandle(procSH);
SetProcessId((int)processInfo.dwProcessId);
threadSH.Dispose();
ret = true;
}
return ret;
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
private bool _signaled;
private static StringBuilder BuildCommandLine(string executableFileName, string arguments)
{
// Construct a StringBuilder with the appropriate command line
// to pass to CreateProcess. If the filename isn't already
// in quotes, we quote it here. This prevents some security
// problems (it specifies exactly which part of the string
// is the file to execute).
StringBuilder commandLine = new StringBuilder();
string fileName = executableFileName.Trim();
bool fileNameIsQuoted = (fileName.StartsWith("\"", StringComparison.Ordinal) && fileName.EndsWith("\"", StringComparison.Ordinal));
if (!fileNameIsQuoted)
{
commandLine.Append("\"");
}
commandLine.Append(fileName);
if (!fileNameIsQuoted)
{
commandLine.Append("\"");
}
if (!String.IsNullOrEmpty(arguments))
{
commandLine.Append(" ");
commandLine.Append(arguments);
}
return commandLine;
}
/// <summary>Gets timing information for the current process.</summary>
private ProcessThreadTimes GetProcessTimes()
{
SafeProcessHandle handle = null;
try
{
handle = GetProcessHandle(Interop.mincore.ProcessOptions.PROCESS_QUERY_LIMITED_INFORMATION, false);
if (handle.IsInvalid)
{
throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString(CultureInfo.CurrentCulture)));
}
ProcessThreadTimes processTimes = new ProcessThreadTimes();
if (!Interop.mincore.GetProcessTimes(handle,
out processTimes._create, out processTimes._exit,
out processTimes._kernel, out processTimes._user))
{
throw new Win32Exception();
}
return processTimes;
}
finally
{
ReleaseProcessHandle(handle);
}
}
private static void SetPrivilege(string privilegeName, int attrib)
{
SafeTokenHandle hToken = null;
Interop.mincore.LUID debugValue = new Interop.mincore.LUID();
// this is only a "pseudo handle" to the current process - no need to close it later
SafeProcessHandle processHandle = Interop.mincore.GetCurrentProcess();
// get the process token so we can adjust the privilege on it. We DO need to
// close the token when we're done with it.
if (!Interop.mincore.OpenProcessToken(processHandle, Interop.mincore.HandleOptions.TOKEN_ADJUST_PRIVILEGES, out hToken))
{
throw new Win32Exception();
}
try
{
if (!Interop.mincore.LookupPrivilegeValue(null, privilegeName, out debugValue))
{
throw new Win32Exception();
}
Interop.mincore.TokenPrivileges tkp = new Interop.mincore.TokenPrivileges();
tkp.Luid = debugValue;
tkp.Attributes = attrib;
Interop.mincore.AdjustTokenPrivileges(hToken, false, tkp, 0, IntPtr.Zero, IntPtr.Zero);
// AdjustTokenPrivileges can return true even if it failed to
// set the privilege, so we need to use GetLastError
if (Marshal.GetLastWin32Error() != Interop.mincore.Errors.ERROR_SUCCESS)
{
throw new Win32Exception();
}
}
finally
{
#if FEATURE_TRACESWITCH
Debug.WriteLineIf(_processTracing.TraceVerbose, "Process - CloseHandle(processToken)");
#endif
if (hToken != null)
{
hToken.Dispose();
}
}
}
/// <devdoc>
/// Gets a short-term handle to the process, with the given access.
/// If a handle is stored in current process object, then use it.
/// Note that the handle we stored in current process object will have all access we need.
/// </devdoc>
/// <internalonly/>
private SafeProcessHandle GetProcessHandle(int access, bool throwIfExited)
{
#if FEATURE_TRACESWITCH
Debug.WriteLineIf(_processTracing.TraceVerbose, "GetProcessHandle(access = 0x" + access.ToString("X8", CultureInfo.InvariantCulture) + ", throwIfExited = " + throwIfExited + ")");
#if DEBUG
if (_processTracing.TraceVerbose) {
StackFrame calledFrom = new StackTrace(true).GetFrame(0);
Debug.WriteLine(" called from " + calledFrom.GetFileName() + ", line " + calledFrom.GetFileLineNumber());
}
#endif
#endif
if (_haveProcessHandle)
{
if (throwIfExited)
{
// Since haveProcessHandle is true, we know we have the process handle
// open with at least SYNCHRONIZE access, so we can wait on it with
// zero timeout to see if the process has exited.
using (ProcessWaitHandle waitHandle = new ProcessWaitHandle(_processHandle))
{
if (waitHandle.WaitOne(0))
{
if (_haveProcessId)
throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString(CultureInfo.CurrentCulture)));
else
throw new InvalidOperationException(SR.ProcessHasExitedNoId);
}
}
}
return _processHandle;
}
else
{
EnsureState(State.HaveId | State.IsLocal);
SafeProcessHandle handle = SafeProcessHandle.InvalidHandle;
handle = ProcessManager.OpenProcess(_processId, access, throwIfExited);
if (throwIfExited && (access & Interop.mincore.ProcessOptions.PROCESS_QUERY_INFORMATION) != 0)
{
if (Interop.mincore.GetExitCodeProcess(handle, out _exitCode) && _exitCode != Interop.mincore.HandleOptions.STILL_ACTIVE)
{
throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString(CultureInfo.CurrentCulture)));
}
}
return handle;
}
}
/// <devdoc>
/// Gets a short-term handle to the process, with the given access. If a handle exists,
/// then it is reused. If the process has exited, it throws an exception.
/// </devdoc>
/// <internalonly/>
private SafeProcessHandle GetProcessHandle(int access)
{
return GetProcessHandle(access, true);
}
private static void CreatePipeWithSecurityAttributes(out SafeFileHandle hReadPipe, out SafeFileHandle hWritePipe, ref Interop.mincore.SECURITY_ATTRIBUTES lpPipeAttributes, int nSize)
{
bool ret = Interop.mincore.CreatePipe(out hReadPipe, out hWritePipe, ref lpPipeAttributes, nSize);
if (!ret || hReadPipe.IsInvalid || hWritePipe.IsInvalid)
{
throw new Win32Exception();
}
}
// Using synchronous Anonymous pipes for process input/output redirection means we would end up
// wasting a worker threadpool thread per pipe instance. Overlapped pipe IO is desirable, since
// it will take advantage of the NT IO completion port infrastructure. But we can't really use
// Overlapped I/O for process input/output as it would break Console apps (managed Console class
// methods such as WriteLine as well as native CRT functions like printf) which are making an
// assumption that the console standard handles (obtained via GetStdHandle()) are opened
// for synchronous I/O and hence they can work fine with ReadFile/WriteFile synchronously!
private void CreatePipe(out SafeFileHandle parentHandle, out SafeFileHandle childHandle, bool parentInputs)
{
Interop.mincore.SECURITY_ATTRIBUTES securityAttributesParent = new Interop.mincore.SECURITY_ATTRIBUTES();
securityAttributesParent.bInheritHandle = true;
SafeFileHandle hTmp = null;
try
{
if (parentInputs)
{
CreatePipeWithSecurityAttributes(out childHandle, out hTmp, ref securityAttributesParent, 0);
}
else
{
CreatePipeWithSecurityAttributes(out hTmp,
out childHandle,
ref securityAttributesParent,
0);
}
// Duplicate the parent handle to be non-inheritable so that the child process
// doesn't have access. This is done for correctness sake, exact reason is unclear.
// One potential theory is that child process can do something brain dead like
// closing the parent end of the pipe and there by getting into a blocking situation
// as parent will not be draining the pipe at the other end anymore.
SafeProcessHandle currentProcHandle = Interop.mincore.GetCurrentProcess();
if (!Interop.mincore.DuplicateHandle(currentProcHandle,
hTmp,
currentProcHandle,
out parentHandle,
0,
false,
Interop.mincore.HandleOptions.DUPLICATE_SAME_ACCESS))
{
throw new Win32Exception();
}
}
finally
{
if (hTmp != null && !hTmp.IsInvalid)
{
hTmp.Dispose();
}
}
}
private static byte[] EnvironmentVariablesToByteArray(Dictionary<string, string> sd)
{
// get the keys
string[] keys = new string[sd.Count];
byte[] envBlock = null;
sd.Keys.CopyTo(keys, 0);
// sort both by the keys
// Windows 2000 requires the environment block to be sorted by the key
// It will first converting the case the strings and do ordinal comparison.
// We do not use Array.Sort(keys, values, IComparer) since it is only supported
// in System.Runtime contract from 4.20.0.0 and Test.Net depends on System.Runtime 4.0.10.0
// we workaround this by sorting only the keys and then lookup the values form the keys.
Array.Sort(keys, StringComparer.OrdinalIgnoreCase);
// create a list of null terminated "key=val" strings
StringBuilder stringBuff = new StringBuilder();
for (int i = 0; i < sd.Count; ++i)
{
stringBuff.Append(keys[i]);
stringBuff.Append('=');
stringBuff.Append(sd[keys[i]]);
stringBuff.Append('\0');
}
// an extra null at the end indicates end of list.
stringBuff.Append('\0');
envBlock = Encoding.Unicode.GetBytes(stringBuff.ToString());
return envBlock;
}
}
}
| |
#region
/*
Copyright (c) 2002-2012, Bas Geertsema, Xih Solutions
(http://www.xihsolutions.net), Thiago.Sayao, Pang Wu, Ethem Evlice, Andy Phan, Chang Liu.
All rights reserved. http://code.google.com/p/msnp-sharp/
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the names of Bas Geertsema or Xih Solutions nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
using System;
using System.Text;
using System.IO;
using System.Threading;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace MSNPSharp.IO
{
/// <summary>
/// Object serializer/deserializer class.
/// </summary>
/// <remarks>
/// This class was used to save/load an object into/from a mcl file.
/// Any object needs to be serialized as a mcl file should derive from this class.
/// </remarks>
[Serializable]
public abstract class MCLSerializer
{
#region Members
[NonSerialized]
private MclSerialization serializationType;
[NonSerialized]
private string fileName;
[NonSerialized]
private string password;
[NonSerialized]
private bool useCache;
[NonSerialized]
private object syncObject;
private string version = "1.0";
#endregion
protected MCLSerializer()
{
}
#region Properties
/// <summary>
/// The version of serialized object in the mcl file.
/// </summary>
[XmlAttribute("Version")]
public string Version
{
get
{
return version;
}
set
{
version = value;
}
}
/// <summary>
/// Gets an object that can be used to synchronize access to this class.
/// </summary>
public object SyncObject
{
get
{
if (syncObject == null)
{
Interlocked.CompareExchange(ref syncObject, new object(), null);
}
return syncObject;
}
}
protected string FileName
{
get
{
return fileName;
}
set
{
fileName = value;
}
}
protected MclSerialization SerializationType
{
get
{
return serializationType;
}
set
{
serializationType = value;
}
}
protected bool UseCache
{
get
{
return useCache;
}
set
{
useCache = value;
}
}
#endregion
#region Methods
/// <summary>
/// Serialize and save the class into a file.
/// </summary>
public virtual void Save()
{
Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, "Saving underlying data...", "<" + GetType() + ">");
Save(FileName);
}
/// <summary>
/// Serialize and save the class into a file.
/// </summary>
/// <param name="filename"></param>
public virtual void Save(string filename)
{
SaveToMCL(filename);
}
protected static MCLSerializer LoadFromFile(string filename, MclSerialization st, Type targettype, string password, bool useCache)
{
int beginTick = Environment.TickCount;
MCLSerializer ret = (MCLSerializer)Activator.CreateInstance(targettype);
if (Settings.NoSave == false && File.Exists(filename))
{
MclFile file = MclFile.Open(filename, FileAccess.Read, st, password, useCache);
int deserializeTick = Environment.TickCount;
if (file.Content != null)
{
using (MemoryStream ms = new MemoryStream(file.Content))
{
try
{
ret = (MCLSerializer)new XmlSerializer(targettype).Deserialize(ms);
}
catch (InvalidOperationException)
{
// Deserialize error: XML struct changed, so create a empty mcl serializer.
ret = (MCLSerializer)Activator.CreateInstance(targettype);
}
}
}
int deserializeTickConsume = Environment.TickCount - deserializeTick;
Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, "<" + ret.GetType().ToString() + "> Deserialize time (by ticks): " + deserializeTickConsume);
}
ret.SerializationType = st;
ret.FileName = filename;
//ret.NSMessageHandler = handler;
ret.UseCache = useCache;
ret.password = password;
int tickConsume = Environment.TickCount - beginTick;
Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, "<" + ret.GetType().ToString() + "> Total loading time (by ticks): " + tickConsume + "\r\n");
return ret;
}
private void SaveToMCL(string filename)
{
int beginTime = Environment.TickCount;
if (!Settings.NoSave)
{
int serializeBegin = Environment.TickCount;
XmlSerializer ser = new XmlSerializer(this.GetType());
MemoryStream ms = new MemoryStream();
ser.Serialize(ms, this);
int serializeTickConsume = Environment.TickCount - serializeBegin;
Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, "<" + this.GetType().ToString() + "> serialize time (by ticks): " + serializeTickConsume);
MclFile file = MclFile.Open(filename, FileAccess.Write, SerializationType, password, UseCache);
file.Content = ms.ToArray();
file.Save(filename);
ms.Close();
}
int tickConsume = Environment.TickCount - beginTime;
Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, "<" + this.GetType().ToString() + "> Total saving time (by ticks): " + tickConsume + "\r\n");
}
#endregion
}
};
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
#if !netstandard
using Internal.Runtime.CompilerServices;
#endif
#if !netstandard11
using System.Numerics;
#endif
namespace System
{
internal static partial class SpanHelpers
{
public static int IndexOf<T>(ref T searchSpace, int searchSpaceLength, ref T value, int valueLength)
where T : IEquatable<T>
{
Debug.Assert(searchSpaceLength >= 0);
Debug.Assert(valueLength >= 0);
if (valueLength == 0)
return 0; // A zero-length sequence is always treated as "found" at the start of the search space.
T valueHead = value;
ref T valueTail = ref Unsafe.Add(ref value, 1);
int valueTailLength = valueLength - 1;
int index = 0;
for (; ; )
{
Debug.Assert(0 <= index && index <= searchSpaceLength); // Ensures no deceptive underflows in the computation of "remainingSearchSpaceLength".
int remainingSearchSpaceLength = searchSpaceLength - index - valueTailLength;
if (remainingSearchSpaceLength <= 0)
break; // The unsearched portion is now shorter than the sequence we're looking for. So it can't be there.
// Do a quick search for the first element of "value".
int relativeIndex = IndexOf(ref Unsafe.Add(ref searchSpace, index), valueHead, remainingSearchSpaceLength);
if (relativeIndex == -1)
break;
index += relativeIndex;
// Found the first element of "value". See if the tail matches.
if (SequenceEqual(ref Unsafe.Add(ref searchSpace, index + 1), ref valueTail, valueTailLength))
return index; // The tail matched. Return a successful find.
index++;
}
return -1;
}
public static unsafe int IndexOf<T>(ref T searchSpace, T value, int length)
where T : IEquatable<T>
{
Debug.Assert(length >= 0);
IntPtr index = (IntPtr)0; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
while (length >= 8)
{
length -= 8;
if (value.Equals(Unsafe.Add(ref searchSpace, index)))
goto Found;
if (value.Equals(Unsafe.Add(ref searchSpace, index + 1)))
goto Found1;
if (value.Equals(Unsafe.Add(ref searchSpace, index + 2)))
goto Found2;
if (value.Equals(Unsafe.Add(ref searchSpace, index + 3)))
goto Found3;
if (value.Equals(Unsafe.Add(ref searchSpace, index + 4)))
goto Found4;
if (value.Equals(Unsafe.Add(ref searchSpace, index + 5)))
goto Found5;
if (value.Equals(Unsafe.Add(ref searchSpace, index + 6)))
goto Found6;
if (value.Equals(Unsafe.Add(ref searchSpace, index + 7)))
goto Found7;
index += 8;
}
if (length >= 4)
{
length -= 4;
if (value.Equals(Unsafe.Add(ref searchSpace, index)))
goto Found;
if (value.Equals(Unsafe.Add(ref searchSpace, index + 1)))
goto Found1;
if (value.Equals(Unsafe.Add(ref searchSpace, index + 2)))
goto Found2;
if (value.Equals(Unsafe.Add(ref searchSpace, index + 3)))
goto Found3;
index += 4;
}
while (length > 0)
{
if (value.Equals(Unsafe.Add(ref searchSpace, index)))
goto Found;
index += 1;
length--;
}
return -1;
Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return (int)(byte*)index;
Found1:
return (int)(byte*)(index + 1);
Found2:
return (int)(byte*)(index + 2);
Found3:
return (int)(byte*)(index + 3);
Found4:
return (int)(byte*)(index + 4);
Found5:
return (int)(byte*)(index + 5);
Found6:
return (int)(byte*)(index + 6);
Found7:
return (int)(byte*)(index + 7);
}
public static int IndexOfAny<T>(ref T searchSpace, T value0, T value1, int length)
where T : IEquatable<T>
{
Debug.Assert(length >= 0);
T lookUp;
int index = 0;
while ((length - index) >= 8)
{
lookUp = Unsafe.Add(ref searchSpace, index);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found;
lookUp = Unsafe.Add(ref searchSpace, index + 1);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, index + 2);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, index + 3);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found3;
lookUp = Unsafe.Add(ref searchSpace, index + 4);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found4;
lookUp = Unsafe.Add(ref searchSpace, index + 5);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found5;
lookUp = Unsafe.Add(ref searchSpace, index + 6);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found6;
lookUp = Unsafe.Add(ref searchSpace, index + 7);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found7;
index += 8;
}
if ((length - index) >= 4)
{
lookUp = Unsafe.Add(ref searchSpace, index);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found;
lookUp = Unsafe.Add(ref searchSpace, index + 1);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, index + 2);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, index + 3);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found3;
index += 4;
}
while (index < length)
{
lookUp = Unsafe.Add(ref searchSpace, index);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found;
index++;
}
return -1;
Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return index;
Found1:
return index + 1;
Found2:
return index + 2;
Found3:
return index + 3;
Found4:
return index + 4;
Found5:
return index + 5;
Found6:
return index + 6;
Found7:
return index + 7;
}
public static int IndexOfAny<T>(ref T searchSpace, T value0, T value1, T value2, int length)
where T : IEquatable<T>
{
Debug.Assert(length >= 0);
T lookUp;
int index = 0;
while ((length - index) >= 8)
{
lookUp = Unsafe.Add(ref searchSpace, index);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found;
lookUp = Unsafe.Add(ref searchSpace, index + 1);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, index + 2);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, index + 3);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found3;
lookUp = Unsafe.Add(ref searchSpace, index + 4);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found4;
lookUp = Unsafe.Add(ref searchSpace, index + 5);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found5;
lookUp = Unsafe.Add(ref searchSpace, index + 6);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found6;
lookUp = Unsafe.Add(ref searchSpace, index + 7);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found7;
index += 8;
}
if ((length - index) >= 4)
{
lookUp = Unsafe.Add(ref searchSpace, index);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found;
lookUp = Unsafe.Add(ref searchSpace, index + 1);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, index + 2);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, index + 3);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found3;
index += 4;
}
while (index < length)
{
lookUp = Unsafe.Add(ref searchSpace, index);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found;
index++;
}
return -1;
Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return index;
Found1:
return index + 1;
Found2:
return index + 2;
Found3:
return index + 3;
Found4:
return index + 4;
Found5:
return index + 5;
Found6:
return index + 6;
Found7:
return index + 7;
}
public static int IndexOfAny<T>(ref T searchSpace, int searchSpaceLength, ref T value, int valueLength)
where T : IEquatable<T>
{
Debug.Assert(searchSpaceLength >= 0);
Debug.Assert(valueLength >= 0);
if (valueLength == 0)
return 0; // A zero-length sequence is always treated as "found" at the start of the search space.
int index = -1;
for (int i = 0; i < valueLength; i++)
{
var tempIndex = IndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength);
if ((uint)tempIndex < (uint)index)
{
index = tempIndex;
// Reduce space for search, cause we don't care if we find the search value after the index of a previously found value
searchSpaceLength = tempIndex;
if (index == 0) break;
}
}
return index;
}
public static int LastIndexOf<T>(ref T searchSpace, int searchSpaceLength, ref T value, int valueLength)
where T : IEquatable<T>
{
Debug.Assert(searchSpaceLength >= 0);
Debug.Assert(valueLength >= 0);
if (valueLength == 0)
return 0; // A zero-length sequence is always treated as "found" at the start of the search space.
T valueHead = value;
ref T valueTail = ref Unsafe.Add(ref value, 1);
int valueTailLength = valueLength - 1;
int index = 0;
for (; ; )
{
Debug.Assert(0 <= index && index <= searchSpaceLength); // Ensures no deceptive underflows in the computation of "remainingSearchSpaceLength".
int remainingSearchSpaceLength = searchSpaceLength - index - valueTailLength;
if (remainingSearchSpaceLength <= 0)
break; // The unsearched portion is now shorter than the sequence we're looking for. So it can't be there.
// Do a quick search for the first element of "value".
int relativeIndex = LastIndexOf(ref searchSpace, valueHead, remainingSearchSpaceLength);
if (relativeIndex == -1)
break;
// Found the first element of "value". See if the tail matches.
if (SequenceEqual(ref Unsafe.Add(ref searchSpace, relativeIndex + 1), ref valueTail, valueTailLength))
return relativeIndex; // The tail matched. Return a successful find.
index += remainingSearchSpaceLength - relativeIndex;
}
return -1;
}
public static int LastIndexOf<T>(ref T searchSpace, T value, int length)
where T : IEquatable<T>
{
Debug.Assert(length >= 0);
while (length >= 8)
{
length -= 8;
if (value.Equals(Unsafe.Add(ref searchSpace, length + 7)))
goto Found7;
if (value.Equals(Unsafe.Add(ref searchSpace, length + 6)))
goto Found6;
if (value.Equals(Unsafe.Add(ref searchSpace, length + 5)))
goto Found5;
if (value.Equals(Unsafe.Add(ref searchSpace, length + 4)))
goto Found4;
if (value.Equals(Unsafe.Add(ref searchSpace, length + 3)))
goto Found3;
if (value.Equals(Unsafe.Add(ref searchSpace, length + 2)))
goto Found2;
if (value.Equals(Unsafe.Add(ref searchSpace, length + 1)))
goto Found1;
if (value.Equals(Unsafe.Add(ref searchSpace, length)))
goto Found;
}
if (length >= 4)
{
length -= 4;
if (value.Equals(Unsafe.Add(ref searchSpace, length + 3)))
goto Found3;
if (value.Equals(Unsafe.Add(ref searchSpace, length + 2)))
goto Found2;
if (value.Equals(Unsafe.Add(ref searchSpace, length + 1)))
goto Found1;
if (value.Equals(Unsafe.Add(ref searchSpace, length)))
goto Found;
}
while (length > 0)
{
length--;
if (value.Equals(Unsafe.Add(ref searchSpace, length)))
goto Found;
}
return -1;
Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return length;
Found1:
return length + 1;
Found2:
return length + 2;
Found3:
return length + 3;
Found4:
return length + 4;
Found5:
return length + 5;
Found6:
return length + 6;
Found7:
return length + 7;
}
public static int LastIndexOfAny<T>(ref T searchSpace, T value0, T value1, int length)
where T : IEquatable<T>
{
Debug.Assert(length >= 0);
T lookUp;
while (length >= 8)
{
length -= 8;
lookUp = Unsafe.Add(ref searchSpace, length + 7);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found7;
lookUp = Unsafe.Add(ref searchSpace, length + 6);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found6;
lookUp = Unsafe.Add(ref searchSpace, length + 5);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found5;
lookUp = Unsafe.Add(ref searchSpace, length + 4);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found4;
lookUp = Unsafe.Add(ref searchSpace, length + 3);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found3;
lookUp = Unsafe.Add(ref searchSpace, length + 2);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, length + 1);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, length);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found;
}
if (length >= 4)
{
length -= 4;
lookUp = Unsafe.Add(ref searchSpace, length + 3);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found3;
lookUp = Unsafe.Add(ref searchSpace, length + 2);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, length + 1);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, length);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found;
}
while (length > 0)
{
length--;
lookUp = Unsafe.Add(ref searchSpace, length);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found;
}
return -1;
Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return length;
Found1:
return length + 1;
Found2:
return length + 2;
Found3:
return length + 3;
Found4:
return length + 4;
Found5:
return length + 5;
Found6:
return length + 6;
Found7:
return length + 7;
}
public static int LastIndexOfAny<T>(ref T searchSpace, T value0, T value1, T value2, int length)
where T : IEquatable<T>
{
Debug.Assert(length >= 0);
T lookUp;
while (length >= 8)
{
length -= 8;
lookUp = Unsafe.Add(ref searchSpace, length + 7);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found7;
lookUp = Unsafe.Add(ref searchSpace, length + 6);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found6;
lookUp = Unsafe.Add(ref searchSpace, length + 5);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found5;
lookUp = Unsafe.Add(ref searchSpace, length + 4);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found4;
lookUp = Unsafe.Add(ref searchSpace, length + 3);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found3;
lookUp = Unsafe.Add(ref searchSpace, length + 2);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, length + 1);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, length);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found;
}
if (length >= 4)
{
length -= 4;
lookUp = Unsafe.Add(ref searchSpace, length + 3);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found3;
lookUp = Unsafe.Add(ref searchSpace, length + 2);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, length + 1);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, length);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found;
}
while (length > 0)
{
length--;
lookUp = Unsafe.Add(ref searchSpace, length);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found;
}
return -1;
Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return length;
Found1:
return length + 1;
Found2:
return length + 2;
Found3:
return length + 3;
Found4:
return length + 4;
Found5:
return length + 5;
Found6:
return length + 6;
Found7:
return length + 7;
}
public static int LastIndexOfAny<T>(ref T searchSpace, int searchSpaceLength, ref T value, int valueLength)
where T : IEquatable<T>
{
Debug.Assert(searchSpaceLength >= 0);
Debug.Assert(valueLength >= 0);
if (valueLength == 0)
return 0; // A zero-length sequence is always treated as "found" at the start of the search space.
int index = -1;
for (int i = 0; i < valueLength; i++)
{
var tempIndex = LastIndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength);
if (tempIndex > index) index = tempIndex;
}
return index;
}
public static bool SequenceEqual<T>(ref T first, ref T second, int length)
where T : IEquatable<T>
{
Debug.Assert(length >= 0);
if (Unsafe.AreSame(ref first, ref second))
goto Equal;
IntPtr index = (IntPtr)0; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
while (length >= 8)
{
length -= 8;
if (!Unsafe.Add(ref first, index).Equals(Unsafe.Add(ref second, index)))
goto NotEqual;
if (!Unsafe.Add(ref first, index + 1).Equals(Unsafe.Add(ref second, index + 1)))
goto NotEqual;
if (!Unsafe.Add(ref first, index + 2).Equals(Unsafe.Add(ref second, index + 2)))
goto NotEqual;
if (!Unsafe.Add(ref first, index + 3).Equals(Unsafe.Add(ref second, index + 3)))
goto NotEqual;
if (!Unsafe.Add(ref first, index + 4).Equals(Unsafe.Add(ref second, index + 4)))
goto NotEqual;
if (!Unsafe.Add(ref first, index + 5).Equals(Unsafe.Add(ref second, index + 5)))
goto NotEqual;
if (!Unsafe.Add(ref first, index + 6).Equals(Unsafe.Add(ref second, index + 6)))
goto NotEqual;
if (!Unsafe.Add(ref first, index + 7).Equals(Unsafe.Add(ref second, index + 7)))
goto NotEqual;
index += 8;
}
if (length >= 4)
{
length -= 4;
if (!Unsafe.Add(ref first, index).Equals(Unsafe.Add(ref second, index)))
goto NotEqual;
if (!Unsafe.Add(ref first, index + 1).Equals(Unsafe.Add(ref second, index + 1)))
goto NotEqual;
if (!Unsafe.Add(ref first, index + 2).Equals(Unsafe.Add(ref second, index + 2)))
goto NotEqual;
if (!Unsafe.Add(ref first, index + 3).Equals(Unsafe.Add(ref second, index + 3)))
goto NotEqual;
index += 4;
}
while (length > 0)
{
if (!Unsafe.Add(ref first, index).Equals(Unsafe.Add(ref second, index)))
goto NotEqual;
index += 1;
length--;
}
Equal:
return true;
NotEqual: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return false;
}
public static int SequenceCompareTo<T>(ref T first, int firstLength, ref T second, int secondLength)
where T : IComparable<T>
{
Debug.Assert(firstLength >= 0);
Debug.Assert(secondLength >= 0);
var minLength = firstLength;
if (minLength > secondLength) minLength = secondLength;
for (int i = 0; i < minLength; i++)
{
int result = Unsafe.Add(ref first, i).CompareTo(Unsafe.Add(ref second, i));
if (result != 0) return result;
}
return firstLength.CompareTo(secondLength);
}
}
}
| |
#region Copyright
////////////////////////////////////////////////////////////////////////////////
// The following FIT Protocol software provided may be used with FIT protocol
// devices only and remains the copyrighted property of Dynastream Innovations Inc.
// The software is being provided on an "as-is" basis and as an accommodation,
// and therefore all warranties, representations, or guarantees of any kind
// (whether express, implied or statutory) including, without limitation,
// warranties of merchantability, non-infringement, or fitness for a particular
// purpose, are specifically disclaimed.
//
// Copyright 2015 Dynastream Innovations Inc.
////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 16.10Release
// Tag = development-akw-16.10.00-0
////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.IO;
namespace FickleFrostbite.FIT
{
/// <summary>
/// Implements the BloodPressure profile message.
/// </summary>
public class BloodPressureMesg : Mesg
{
#region Fields
#endregion
#region Constructors
public BloodPressureMesg() : base(Profile.mesgs[Profile.BloodPressureIndex])
{
}
public BloodPressureMesg(Mesg mesg) : base(mesg)
{
}
#endregion // Constructors
#region Methods
///<summary>
/// Retrieves the Timestamp field
/// Units: s</summary>
/// <returns>Returns DateTime representing the Timestamp field</returns>
public DateTime GetTimestamp()
{
return TimestampToDateTime((uint?)GetFieldValue(253, 0, Fit.SubfieldIndexMainField));
}
/// <summary>
/// Set Timestamp field
/// Units: s</summary>
/// <param name="timestamp_">Nullable field value to be set</param>
public void SetTimestamp(DateTime timestamp_)
{
SetFieldValue(253, 0, timestamp_.GetTimeStamp(), Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the SystolicPressure field
/// Units: mmHg</summary>
/// <returns>Returns nullable ushort representing the SystolicPressure field</returns>
public ushort? GetSystolicPressure()
{
return (ushort?)GetFieldValue(0, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set SystolicPressure field
/// Units: mmHg</summary>
/// <param name="systolicPressure_">Nullable field value to be set</param>
public void SetSystolicPressure(ushort? systolicPressure_)
{
SetFieldValue(0, 0, systolicPressure_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the DiastolicPressure field
/// Units: mmHg</summary>
/// <returns>Returns nullable ushort representing the DiastolicPressure field</returns>
public ushort? GetDiastolicPressure()
{
return (ushort?)GetFieldValue(1, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set DiastolicPressure field
/// Units: mmHg</summary>
/// <param name="diastolicPressure_">Nullable field value to be set</param>
public void SetDiastolicPressure(ushort? diastolicPressure_)
{
SetFieldValue(1, 0, diastolicPressure_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the MeanArterialPressure field
/// Units: mmHg</summary>
/// <returns>Returns nullable ushort representing the MeanArterialPressure field</returns>
public ushort? GetMeanArterialPressure()
{
return (ushort?)GetFieldValue(2, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set MeanArterialPressure field
/// Units: mmHg</summary>
/// <param name="meanArterialPressure_">Nullable field value to be set</param>
public void SetMeanArterialPressure(ushort? meanArterialPressure_)
{
SetFieldValue(2, 0, meanArterialPressure_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Map3SampleMean field
/// Units: mmHg</summary>
/// <returns>Returns nullable ushort representing the Map3SampleMean field</returns>
public ushort? GetMap3SampleMean()
{
return (ushort?)GetFieldValue(3, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Map3SampleMean field
/// Units: mmHg</summary>
/// <param name="map3SampleMean_">Nullable field value to be set</param>
public void SetMap3SampleMean(ushort? map3SampleMean_)
{
SetFieldValue(3, 0, map3SampleMean_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the MapMorningValues field
/// Units: mmHg</summary>
/// <returns>Returns nullable ushort representing the MapMorningValues field</returns>
public ushort? GetMapMorningValues()
{
return (ushort?)GetFieldValue(4, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set MapMorningValues field
/// Units: mmHg</summary>
/// <param name="mapMorningValues_">Nullable field value to be set</param>
public void SetMapMorningValues(ushort? mapMorningValues_)
{
SetFieldValue(4, 0, mapMorningValues_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the MapEveningValues field
/// Units: mmHg</summary>
/// <returns>Returns nullable ushort representing the MapEveningValues field</returns>
public ushort? GetMapEveningValues()
{
return (ushort?)GetFieldValue(5, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set MapEveningValues field
/// Units: mmHg</summary>
/// <param name="mapEveningValues_">Nullable field value to be set</param>
public void SetMapEveningValues(ushort? mapEveningValues_)
{
SetFieldValue(5, 0, mapEveningValues_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the HeartRate field
/// Units: bpm</summary>
/// <returns>Returns nullable byte representing the HeartRate field</returns>
public byte? GetHeartRate()
{
return (byte?)GetFieldValue(6, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set HeartRate field
/// Units: bpm</summary>
/// <param name="heartRate_">Nullable field value to be set</param>
public void SetHeartRate(byte? heartRate_)
{
SetFieldValue(6, 0, heartRate_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the HeartRateType field</summary>
/// <returns>Returns nullable HrType enum representing the HeartRateType field</returns>
public HrType? GetHeartRateType()
{
object obj = GetFieldValue(7, 0, Fit.SubfieldIndexMainField);
HrType? value = obj == null ? (HrType?)null : (HrType)obj;
return value;
}
/// <summary>
/// Set HeartRateType field</summary>
/// <param name="heartRateType_">Nullable field value to be set</param>
public void SetHeartRateType(HrType? heartRateType_)
{
SetFieldValue(7, 0, heartRateType_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Status field</summary>
/// <returns>Returns nullable BpStatus enum representing the Status field</returns>
public BpStatus? GetStatus()
{
object obj = GetFieldValue(8, 0, Fit.SubfieldIndexMainField);
BpStatus? value = obj == null ? (BpStatus?)null : (BpStatus)obj;
return value;
}
/// <summary>
/// Set Status field</summary>
/// <param name="status_">Nullable field value to be set</param>
public void SetStatus(BpStatus? status_)
{
SetFieldValue(8, 0, status_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the UserProfileIndex field
/// Comment: Associates this blood pressure message to a user. This corresponds to the index of the user profile message in the blood pressure file.</summary>
/// <returns>Returns nullable ushort representing the UserProfileIndex field</returns>
public ushort? GetUserProfileIndex()
{
return (ushort?)GetFieldValue(9, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set UserProfileIndex field
/// Comment: Associates this blood pressure message to a user. This corresponds to the index of the user profile message in the blood pressure file.</summary>
/// <param name="userProfileIndex_">Nullable field value to be set</param>
public void SetUserProfileIndex(ushort? userProfileIndex_)
{
SetFieldValue(9, 0, userProfileIndex_, Fit.SubfieldIndexMainField);
}
#endregion // Methods
} // Class
} // namespace
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Dns
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ZonesOperations operations.
/// </summary>
public partial interface IZonesOperations
{
/// <summary>
/// Creates or updates a DNS zone. Does not modify DNS records within
/// the zone.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the DNS zone (without a terminating dot).
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the CreateOrUpdate operation.
/// </param>
/// <param name='ifMatch'>
/// The etag of the DNS zone. Omit this value to always overwrite the
/// current zone. Specify the last-seen etag value to prevent
/// accidentally overwritting any concurrent changes.
/// </param>
/// <param name='ifNoneMatch'>
/// Set to '*' to allow a new DNS zone to be created, but to prevent
/// updating an existing zone. Other values will be ignored.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<Zone>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string zoneName, Zone parameters, string ifMatch = default(string), string ifNoneMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a DNS zone. WARNING: All DNS records in the zone will also
/// be deleted. This operation cannot be undone.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the DNS zone (without a terminating dot).
/// </param>
/// <param name='ifMatch'>
/// The etag of the DNS zone. Omit this value to always delete the
/// current zone. Specify the last-seen etag value to prevent
/// accidentally deleting any concurrent changes.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string zoneName, string ifMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a DNS zone. Retrieves the zone properties, but not the record
/// sets within the zone.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the DNS zone (without a terminating dot).
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<Zone>> GetWithHttpMessagesAsync(string resourceGroupName, string zoneName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the DNS zones within a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='top'>
/// The maximum number of record sets to return. If not specified,
/// returns up to 100 record sets.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<Zone>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, int? top = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the DNS zones in all resource groups in a subscription.
/// </summary>
/// <param name='top'>
/// The maximum number of DNS zones to return. If not specified,
/// returns up to 100 zones.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<Zone>>> ListWithHttpMessagesAsync(int? top = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a DNS zone. WARNING: All DNS records in the zone will also
/// be deleted. This operation cannot be undone.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the DNS zone (without a terminating dot).
/// </param>
/// <param name='ifMatch'>
/// The etag of the DNS zone. Omit this value to always delete the
/// current zone. Specify the last-seen etag value to prevent
/// accidentally deleting any concurrent changes.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string zoneName, string ifMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the DNS zones within a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<Zone>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the DNS zones in all resource groups in a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<Zone>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.IO.Pipelines.Text.Primitives;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
namespace System.IO.Pipelines.Samples.Http
{
public class RequestHeaderDictionary : IHeaderDictionary
{
private static readonly byte[] ContentLengthKeyBytes = Encoding.ASCII.GetBytes("CONTENT-LENGTH");
private static readonly byte[] ContentTypeKeyBytes = Encoding.ASCII.GetBytes("CONTENT-TYPE");
private static readonly byte[] AcceptBytes = Encoding.ASCII.GetBytes("ACCEPT");
private static readonly byte[] AcceptLanguageBytes = Encoding.ASCII.GetBytes("ACCEPT-LANGUAGE");
private static readonly byte[] AcceptEncodingBytes = Encoding.ASCII.GetBytes("ACCEPT-ENCODING");
private static readonly byte[] HostBytes = Encoding.ASCII.GetBytes("HOST");
private static readonly byte[] ConnectionBytes = Encoding.ASCII.GetBytes("CONNECTION");
private static readonly byte[] CacheControlBytes = Encoding.ASCII.GetBytes("CACHE-CONTROL");
private static readonly byte[] UserAgentBytes = Encoding.ASCII.GetBytes("USER-AGENT");
private static readonly byte[] UpgradeInsecureRequests = Encoding.ASCII.GetBytes("UPGRADE-INSECURE-REQUESTS");
private Dictionary<string, HeaderValue> _headers = new Dictionary<string, HeaderValue>(10, StringComparer.OrdinalIgnoreCase);
public StringValues this[string key]
{
get
{
StringValues values;
TryGetValue(key, out values);
return values;
}
set
{
SetHeader(key, value);
}
}
public int Count => _headers.Count;
public bool IsReadOnly => false;
public ICollection<string> Keys => _headers.Keys;
public ICollection<StringValues> Values => _headers.Values.Select(v => v.GetValue()).ToList();
public void SetHeader(ref ReadableBuffer key, ref ReadableBuffer value)
{
string headerKey = GetHeaderKey(ref key);
_headers[headerKey] = new HeaderValue
{
Raw = value.Preserve()
};
}
public ReadableBuffer GetHeaderRaw(string key)
{
HeaderValue value;
if (_headers.TryGetValue(key, out value))
{
return value.Raw.Value.Buffer;
}
return default;
}
private string GetHeaderKey(ref ReadableBuffer key)
{
// Uppercase the things
foreach (var memory in key)
{
var data = memory.Span;
for (int i = 0; i < memory.Length; i++)
{
var mask = IsAlpha(data[i]) ? 0xdf : 0xff;
data[i] = (byte)(data[i] & mask);
}
}
if (EqualsIgnoreCase(ref key, AcceptBytes))
{
return "Accept";
}
if (EqualsIgnoreCase(ref key, AcceptEncodingBytes))
{
return "Accept-Encoding";
}
if (EqualsIgnoreCase(ref key, AcceptLanguageBytes))
{
return "Accept-Language";
}
if (EqualsIgnoreCase(ref key, HostBytes))
{
return "Host";
}
if (EqualsIgnoreCase(ref key, UserAgentBytes))
{
return "User-Agent";
}
if (EqualsIgnoreCase(ref key, CacheControlBytes))
{
return "Cache-Control";
}
if (EqualsIgnoreCase(ref key, ConnectionBytes))
{
return "Connection";
}
if (EqualsIgnoreCase(ref key, UpgradeInsecureRequests))
{
return "Upgrade-Insecure-Requests";
}
return key.GetAsciiString();
}
private bool EqualsIgnoreCase(ref ReadableBuffer key, byte[] buffer)
{
if (key.Length != buffer.Length)
{
return false;
}
return key.EqualsTo(buffer);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool IsAlpha(byte b)
{
return b >= 'a' && b <= 'z' || b >= 'A' && b <= 'Z';
}
private void SetHeader(string key, StringValues value)
{
_headers[key] = new HeaderValue
{
Value = value
};
}
public void Add(KeyValuePair<string, StringValues> item)
{
SetHeader(item.Key, item.Value);
}
public void Add(string key, StringValues value)
{
SetHeader(key, value);
}
public void Clear()
{
_headers.Clear();
}
public bool Contains(KeyValuePair<string, StringValues> item)
{
return false;
}
public bool ContainsKey(string key)
{
return _headers.ContainsKey(key);
}
public void CopyTo(KeyValuePair<string, StringValues>[] array, int arrayIndex)
{
throw new NotSupportedException();
}
public void Reset()
{
foreach (var pair in _headers)
{
pair.Value.Raw?.Dispose();
}
_headers.Clear();
}
public IEnumerator<KeyValuePair<string, StringValues>> GetEnumerator()
{
return _headers.Select(h => new KeyValuePair<string, StringValues>(h.Key, h.Value.GetValue())).GetEnumerator();
}
public bool Remove(KeyValuePair<string, StringValues> item)
{
throw new NotImplementedException();
}
public bool Remove(string key)
{
return _headers.Remove(key);
}
public bool TryGetValue(string key, out StringValues value)
{
HeaderValue headerValue;
if (_headers.TryGetValue(key, out headerValue))
{
value = headerValue.GetValue();
return true;
}
return false;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private struct HeaderValue
{
public PreservedBuffer? Raw;
public StringValues? Value;
public StringValues GetValue()
{
if (!Value.HasValue)
{
if (!Raw.HasValue)
{
return StringValues.Empty;
}
Value = Raw.Value.Buffer.GetAsciiString();
}
return Value.Value;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using log4net;
using Polly;
using RestSharp;
using Xpressive.Home.Contracts.Gateway;
using Xpressive.Home.Contracts.Messaging;
using Action = Xpressive.Home.Contracts.Gateway.Action;
namespace Xpressive.Home.Plugins.Denon
{
internal class DenonGateway : GatewayBase, IDenonGateway, IMessageQueueListener<NetworkDeviceFoundMessage>
{
private static readonly ILog _log = LogManager.GetLogger(typeof(DenonGateway));
private readonly IMessageQueue _messageQueue;
private readonly object _deviceLock = new object();
public DenonGateway(IMessageQueue messageQueue) : base("Denon")
{
_messageQueue = messageQueue;
_canCreateDevices = false;
}
public override IDevice CreateEmptyDevice()
{
throw new NotSupportedException();
}
public IEnumerable<DenonDevice> GetDevices()
{
return Devices.OfType<DenonDevice>();
}
public override IEnumerable<IAction> GetActions(IDevice device)
{
if (device is DenonDevice)
{
yield return new Action("Change Volume") { Fields = { "Volume" } };
yield return new Action("Volume Up");
yield return new Action("Volume Down");
yield return new Action("Power On");
yield return new Action("Power Off");
yield return new Action("Mute On");
yield return new Action("Mute Off");
yield return new Action("Change Input Source") { Fields = { "Source" } };
}
}
public void PowerOn(DenonDevice device)
{
StartActionInNewTask(device, new Action("Power On"), null);
}
public void PowerOff(DenonDevice device)
{
StartActionInNewTask(device, new Action("Power Off"), null);
}
public void ChangeVolumne(DenonDevice device, int volume)
{
var parameters = new Dictionary<string, string>
{
{"Volume", volume.ToString()}
};
StartActionInNewTask(device, new Action("Change Volume"), parameters);
}
public void Mute(DenonDevice device)
{
StartActionInNewTask(device, new Action("Mute On"), null);
}
public void Unmute(DenonDevice device)
{
StartActionInNewTask(device, new Action("Mute Off"), null);
}
public void ChangeInput(DenonDevice device, string source)
{
var parameters = new Dictionary<string, string>
{
{"Source", source}
};
StartActionInNewTask(device, new Action("Change Input Source"), parameters);
}
protected override async Task ExecuteInternalAsync(IDevice device, IAction action, IDictionary<string, string> values)
{
if (device == null)
{
_log.Warn($"Unable to execute action {action.Name} because the device was not found.");
return;
}
string command = null;
switch (action.Name.ToLowerInvariant())
{
case "change volume":
string volume;
int v;
if (values.TryGetValue("Volume", out volume) && int.TryParse(volume, out v))
{
volume = Math.Max(0, Math.Min(98, v)).ToString("D2");
command = "MV" + volume;
}
break;
case "volume up":
command = "MVUP";
break;
case "volume down":
command = "MVDOWN";
break;
case "power on":
command = "PWON";
break;
case "power off":
command = "PWSTANDBY";
break;
case "mute on":
command = "MUON";
break;
case "mute off":
command = "MUOFF";
break;
case "change input source":
string source;
if (values.TryGetValue("Source", out source))
{
command = "SI" + source;
}
break;
}
var denon = device as DenonDevice;
if (string.IsNullOrEmpty(command) || denon == null)
{
return;
}
_log.Debug($"Send command {command} to {denon.IpAddress}.");
using (var client = new TcpClient())
{
await client.ConnectAsync(denon.IpAddress, 23);
using (var stream = client.GetStream())
{
var data = Encoding.UTF8.GetBytes(command + '\r');
await stream.WriteAsync(data, 0, data.Length);
await stream.FlushAsync();
}
}
}
public override async Task StartAsync(CancellationToken cancellationToken)
{
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ContinueWith(_ => { });
while (!cancellationToken.IsCancellationRequested)
{
foreach (var device in GetDevices())
{
if (!cancellationToken.IsCancellationRequested)
{
await UpdateVariablesAsync(device);
}
}
await Task.Delay(TimeSpan.FromMinutes(1), cancellationToken).ContinueWith(_ => { });
}
}
public async void Notify(NetworkDeviceFoundMessage message)
{
string server;
string location;
if (!message.Values.TryGetValue("Server", out server) ||
!message.Values.TryGetValue("Location", out location) ||
location.IndexOf(":8080/description.xml", StringComparison.OrdinalIgnoreCase) < 0 ||
server.IndexOf("knos/", StringComparison.OrdinalIgnoreCase) < 0)
{
return;
}
var policy = Policy
.Handle<WebException>()
.Or<XmlException>()
.WaitAndRetryAsync(new[]
{
TimeSpan.FromSeconds(1),
TimeSpan.FromSeconds(2),
TimeSpan.FromSeconds(5)
});
await policy.ExecuteAsync(async () =>
{
var device = RegisterDevice(location, message.IpAddress);
if (device == null)
{
return;
}
await UpdateVariablesAsync(device);
});
}
private DenonDevice RegisterDevice(string url, string ipAddress)
{
var xml = new XmlDocument();
xml.Load(url);
var ns = new XmlNamespaceManager(xml.NameTable);
ns.AddNamespace("n", "urn:schemas-upnp-org:device-1-0");
var mn = xml.SelectSingleNode("//n:manufacturer", ns);
var fn = xml.SelectSingleNode("//n:friendlyName", ns);
var sn = xml.SelectSingleNode("//n:serialNumber", ns);
if (mn == null || fn == null || sn == null || !"Denon".Equals(mn.InnerText, StringComparison.Ordinal))
{
return null;
}
lock (_deviceLock)
{
if (GetDevices().Any(d => d.IpAddress.Equals(ipAddress, StringComparison.OrdinalIgnoreCase)))
{
return null;
}
var device = new DenonDevice(sn.InnerText, ipAddress)
{
Name = fn.InnerText.Replace("Denon", string.Empty).Trim()
};
_devices.Add(device);
return device;
}
}
private async Task UpdateVariablesAsync(DenonDevice device)
{
var client = new RestClient($"http://{device.IpAddress}/");
var request = new RestRequest("goform/formMainZone_MainZoneXml.xml", Method.GET);
var response = await client.ExecuteTaskAsync<DenonDeviceDto>(request);
double volume;
var isMute = response.Data.Mute.Value.Equals("on", StringComparison.OrdinalIgnoreCase);
var select = response.Data.InputFuncSelect.Value;
if (!double.TryParse(response.Data.MasterVolume.Value, out volume))
{
volume = 0;
}
device.Name = response.Data.FriendlyName.Value.Replace("Denon", string.Empty).Trim();
device.Volume = volume;
device.IsMute = isMute;
device.Source = select;
_messageQueue.Publish(new UpdateVariableMessage($"{Name}.{device.Id}.Volume", volume));
_messageQueue.Publish(new UpdateVariableMessage($"{Name}.{device.Id}.IsMute", isMute));
_messageQueue.Publish(new UpdateVariableMessage($"{Name}.{device.Id}.Source", select));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace ClearScript.Manager.WebDemo.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;
namespace Nickymaco.WebEngine
{
sealed class ViewRenderer : IViewRender
{
const string DEBUG_TEMPORARY_FOLDER = "_debug";
static Hashtable _viewCache = new Hashtable();
static object _syncObj = new object();
private readonly string _rootPath;
private readonly IViewParser _viewParser;
public ViewRenderer()
{
_rootPath = HttpContext.Current.Server.MapPath("~/");
_viewParser = Engine.Container.GetExport<IViewParser>().Value;
}
public HttpContext Context { get; set; }
// the render entrance
public void Render(ViewModel viewModel)
{
lock (_syncObj)
{
ViewAttribute view = viewModel.GetType().GetAttribute<ViewAttribute>();
if (view != null)
{
RenderTemplate(view, viewModel);
}
}
}
// Render from template file
private void RenderTemplate(ViewAttribute viewAttr, ViewModel viewModel)
{
if (_viewParser == null)
{
throw new Exception("there are not any ViewParser");
}
Type viewModelType = viewModel.GetType();
// if debug, will be read file from local path "_debug folder"
if (viewModel.DeBug)
{
string content = ReadFeatureFromTemporaryFile(viewModelType.FullName);
if (!string.IsNullOrEmpty(content))
{
Context.Response.Write(this._viewParser.Parse(content, viewModel));
return;
}
}
// find from cache
if (_viewCache.ContainsKey(viewAttr.ViewName))
{
Context.Response.Write(this._viewParser.Parse(_viewCache[viewAttr.ViewName].ToString(), viewModel));
return;
}
Stream strm = null;
try
{
// from internet
if (Regex.IsMatch(viewAttr.ViewName, @"^http(s)?\:\/\/", RegexOptions.IgnoreCase))
{
var httpRequest = (HttpWebRequest)WebRequest.Create(viewAttr.ViewName);
var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
strm = httpResponse.GetResponseStream();
}
// from local path
else if (Regex.IsMatch(viewAttr.ViewName, @"\~/(\w+(/)?)+(\.\w+)"))
{
// convert to physics Path
var physicsPath = Context.Server.MapPath(viewAttr.ViewName);
if (File.Exists(physicsPath))
{
strm = new FileStream(physicsPath, FileMode.Open);
}
}
// from embed resources
else
{
strm = viewModel.GetType().Assembly.GetManifestResourceStream(viewAttr.ViewName);
}
if (strm == null)
{
Context.Response.StatusCode = 404;
return;
}
using (StreamReader stmR = new StreamReader(strm))
{
string content = stmR.ReadToEnd();
if (!string.IsNullOrEmpty(content) && !_viewCache.ContainsKey(viewAttr.ViewName))
{
_viewCache.Add(viewAttr.ViewName, content);
}
// if debug output the content to a file that saved in loacl path "_debug folder"
if (viewModel.DeBug)
{
WriteFeatureToTemporaryFile(content, viewModelType.FullName);
}
Context.Response.Write(this._viewParser.Parse(content, viewModel));
}
}
catch (Exception ex)
{
Engine.Logging(EngineLogger.Level.Error, ex, ex.Message);
throw ex;
}
finally
{
if (strm != null)
{
strm.Dispose();
}
}
}
// Save content into a local file
private void WriteFeatureToTemporaryFile(string content, string fileName)
{
string folderPath = _rootPath + DEBUG_TEMPORARY_FOLDER;
string filePath = folderPath + "\\" + fileName;
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
FileStream fs = null;
StreamWriter sw = null;
try
{
fs = new FileStream(filePath, FileMode.Create);
sw = new StreamWriter(fs);
sw.Write(content);
}
finally
{
if (sw != null)
{
sw.Dispose();
}
if (fs != null)
{
fs.Dispose();
}
}
}
// Read template content from a local file
private string ReadFeatureFromTemporaryFile(string fileName)
{
string folderPath = _rootPath + DEBUG_TEMPORARY_FOLDER;
string filePath = folderPath + "\\" + fileName;
if (!Directory.Exists(folderPath))
{
return string.Empty;
}
if (!File.Exists(filePath))
{
return string.Empty;
}
FileStream fs = null;
StreamReader sr = null;
try
{
fs = new FileStream(filePath, FileMode.Open);
sr = new StreamReader(fs);
return sr.ReadToEnd();
}
finally
{
if (sr != null)
{
sr.Dispose();
}
if (fs != null)
{
fs.Dispose();
}
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
extern alias WORKSPACES;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Windows.Threading;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Scripting.Hosting;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.VisualBasic;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Test.EditorUtilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
{
using System.Threading.Tasks;
using RelativePathResolver = WORKSPACES::Microsoft.CodeAnalysis.RelativePathResolver;
public partial class TestWorkspace
{
/// <summary>
/// This place-holder value is used to set a project's file path to be null. It was explicitly chosen to be
/// convoluted to avoid any accidental usage (e.g., what if I really wanted FilePath to be the string "null"?),
/// obvious to anybody debugging that it is a special value, and invalid as an actual file path.
/// </summary>
public const string NullFilePath = "NullFilePath::{AFA13775-BB7D-4020-9E58-C68CF43D8A68}";
private class TestDocumentationProvider : DocumentationProvider
{
protected override string GetDocumentationForSymbol(string documentationMemberID, CultureInfo preferredCulture, CancellationToken cancellationToken = default(CancellationToken))
{
return string.Format("<member name='{0}'><summary>{0}</summary></member>", documentationMemberID);
}
public override bool Equals(object obj)
{
return (object)this == obj;
}
public override int GetHashCode()
{
return RuntimeHelpers.GetHashCode(this);
}
}
public static Task<TestWorkspace> CreateAsync(string xmlDefinition, bool completed = true, bool openDocuments = true, ExportProvider exportProvider = null)
{
return CreateAsync(XElement.Parse(xmlDefinition), completed, openDocuments, exportProvider);
}
public static TestWorkspace CreateWorkspace(
XElement workspaceElement,
bool completed = true,
bool openDocuments = true,
ExportProvider exportProvider = null,
string workspaceKind = null)
{
return CreateAsync(workspaceElement, completed, openDocuments, exportProvider, workspaceKind).WaitAndGetResult_CanCallOnBackground(CancellationToken.None);
}
public static Task<TestWorkspace> CreateAsync(
XElement workspaceElement,
bool completed = true,
bool openDocuments = true,
ExportProvider exportProvider = null,
string workspaceKind = null)
{
if (workspaceElement.Name != WorkspaceElementName)
{
throw new ArgumentException();
}
exportProvider = exportProvider ?? TestExportProvider.ExportProviderWithCSharpAndVisualBasic;
var workspace = new TestWorkspace(exportProvider, workspaceKind);
var projectNameToTestHostProject = new Dictionary<string, TestHostProject>();
var documentElementToFilePath = new Dictionary<XElement, string>();
var projectElementToProjectName = new Dictionary<XElement, string>();
var filePathToTextBufferMap = new Dictionary<string, ITextBuffer>();
int projectIdentifier = 0;
int documentIdentifier = 0;
foreach (var projectElement in workspaceElement.Elements(ProjectElementName))
{
var project = CreateProject(
workspaceElement,
projectElement,
exportProvider,
workspace,
documentElementToFilePath,
filePathToTextBufferMap,
ref projectIdentifier,
ref documentIdentifier);
Assert.False(projectNameToTestHostProject.ContainsKey(project.Name), $"The workspace XML already contains a project with name {project.Name}");
projectNameToTestHostProject.Add(project.Name, project);
projectElementToProjectName.Add(projectElement, project.Name);
workspace.Projects.Add(project);
}
var documentFilePaths = new HashSet<string>();
foreach (var project in projectNameToTestHostProject.Values)
{
foreach (var document in project.Documents)
{
Assert.True(document.IsLinkFile || documentFilePaths.Add(document.FilePath));
}
}
var submissions = CreateSubmissions(workspace, workspaceElement.Elements(SubmissionElementName), exportProvider);
foreach (var submission in submissions)
{
projectNameToTestHostProject.Add(submission.Name, submission);
}
var solution = new TestHostSolution(projectNameToTestHostProject.Values.ToArray());
workspace.AddTestSolution(solution);
foreach (var projectElement in workspaceElement.Elements(ProjectElementName))
{
foreach (var projectReference in projectElement.Elements(ProjectReferenceElementName))
{
var fromName = projectElementToProjectName[projectElement];
var toName = projectReference.Value;
var fromProject = projectNameToTestHostProject[fromName];
var toProject = projectNameToTestHostProject[toName];
var aliases = projectReference.Attributes(AliasAttributeName).Select(a => a.Value).ToImmutableArray();
workspace.OnProjectReferenceAdded(fromProject.Id, new ProjectReference(toProject.Id, aliases.Any() ? aliases : default(ImmutableArray<string>)));
}
}
for (int i = 1; i < submissions.Count; i++)
{
if (submissions[i].CompilationOptions == null)
{
continue;
}
for (int j = i - 1; j >= 0; j--)
{
if (submissions[j].CompilationOptions != null)
{
workspace.OnProjectReferenceAdded(submissions[i].Id, new ProjectReference(submissions[j].Id));
break;
}
}
}
foreach (var project in projectNameToTestHostProject.Values)
{
foreach (var document in project.Documents)
{
if (openDocuments)
{
workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer(), isCurrentContext: !document.IsLinkFile);
}
workspace.Documents.Add(document);
}
}
return Task.FromResult(workspace);
}
private static IList<TestHostProject> CreateSubmissions(
TestWorkspace workspace,
IEnumerable<XElement> submissionElements,
ExportProvider exportProvider)
{
var submissions = new List<TestHostProject>();
var submissionIndex = 0;
foreach (var submissionElement in submissionElements)
{
var submissionName = "Submission" + (submissionIndex++);
var languageName = GetLanguage(workspace, submissionElement);
// The document
var markupCode = submissionElement.NormalizedValue();
string code;
int? cursorPosition;
IDictionary<string, IList<TextSpan>> spans;
MarkupTestFile.GetPositionAndSpans(markupCode, out code, out cursorPosition, out spans);
var languageServices = workspace.Services.GetLanguageServices(languageName);
var contentTypeLanguageService = languageServices.GetService<IContentTypeLanguageService>();
var contentType = contentTypeLanguageService.GetDefaultContentType();
var textBuffer = EditorFactory.CreateBuffer(contentType.TypeName, exportProvider, code);
// The project
var document = new TestHostDocument(exportProvider, languageServices, textBuffer, submissionName, cursorPosition, spans, SourceCodeKind.Script);
var documents = new List<TestHostDocument> { document };
if (languageName == NoCompilationConstants.LanguageName)
{
submissions.Add(
new TestHostProject(
languageServices,
compilationOptions: null,
parseOptions: null,
assemblyName: submissionName,
projectName: submissionName,
references: null,
documents: documents,
isSubmission: true));
continue;
}
var syntaxFactory = languageServices.GetService<ISyntaxTreeFactoryService>();
var compilationFactory = languageServices.GetService<ICompilationFactoryService>();
var compilationOptions = compilationFactory.GetDefaultCompilationOptions().WithOutputKind(OutputKind.DynamicallyLinkedLibrary);
var parseOptions = syntaxFactory.GetDefaultParseOptions().WithKind(SourceCodeKind.Script);
var references = CreateCommonReferences(workspace, submissionElement);
var project = new TestHostProject(
languageServices,
compilationOptions,
parseOptions,
submissionName,
submissionName,
references,
documents,
isSubmission: true);
submissions.Add(project);
}
return submissions;
}
private static TestHostProject CreateProject(
XElement workspaceElement,
XElement projectElement,
ExportProvider exportProvider,
TestWorkspace workspace,
Dictionary<XElement, string> documentElementToFilePath,
Dictionary<string, ITextBuffer> filePathToTextBufferMap,
ref int projectId,
ref int documentId)
{
var language = GetLanguage(workspace, projectElement);
var assemblyName = GetAssemblyName(workspace, projectElement, ref projectId);
string filePath;
string projectName = projectElement.Attribute(ProjectNameAttribute)?.Value ?? assemblyName;
if (projectElement.Attribute(FilePathAttributeName) != null)
{
filePath = projectElement.Attribute(FilePathAttributeName).Value;
if (string.Compare(filePath, NullFilePath, StringComparison.Ordinal) == 0)
{
// allow explicit null file path
filePath = null;
}
}
else
{
filePath = projectName +
(language == LanguageNames.CSharp ? ".csproj" :
language == LanguageNames.VisualBasic ? ".vbproj" : ("." + language));
}
var contentTypeRegistryService = exportProvider.GetExportedValue<IContentTypeRegistryService>();
var languageServices = workspace.Services.GetLanguageServices(language);
var compilationOptions = CreateCompilationOptions(workspace, projectElement, language);
var parseOptions = GetParseOptions(projectElement, language, languageServices);
var references = CreateReferenceList(workspace, projectElement);
var analyzers = CreateAnalyzerList(workspace, projectElement);
var documents = new List<TestHostDocument>();
var documentElements = projectElement.Elements(DocumentElementName).ToList();
foreach (var documentElement in documentElements)
{
var document = CreateDocument(
workspace,
workspaceElement,
documentElement,
language,
exportProvider,
languageServices,
filePathToTextBufferMap,
ref documentId);
documents.Add(document);
documentElementToFilePath.Add(documentElement, document.FilePath);
}
return new TestHostProject(languageServices, compilationOptions, parseOptions, assemblyName, projectName, references, documents, filePath: filePath, analyzerReferences: analyzers);
}
private static ParseOptions GetParseOptions(XElement projectElement, string language, HostLanguageServices languageServices)
{
return language == LanguageNames.CSharp || language == LanguageNames.VisualBasic
? GetParseOptionsWorker(projectElement, language, languageServices)
: null;
}
private static ParseOptions GetParseOptionsWorker(XElement projectElement, string language, HostLanguageServices languageServices)
{
ParseOptions parseOptions;
var preprocessorSymbolsAttribute = projectElement.Attribute(PreprocessorSymbolsAttributeName);
if (preprocessorSymbolsAttribute != null)
{
parseOptions = GetPreProcessorParseOptions(language, preprocessorSymbolsAttribute);
}
else
{
parseOptions = languageServices.GetService<ISyntaxTreeFactoryService>().GetDefaultParseOptions();
}
var languageVersionAttribute = projectElement.Attribute(LanguageVersionAttributeName);
if (languageVersionAttribute != null)
{
parseOptions = GetParseOptionsWithLanguageVersion(language, parseOptions, languageVersionAttribute);
}
var featuresAttribute = projectElement.Attribute(FeaturesAttributeName);
if (featuresAttribute != null)
{
parseOptions = GetParseOptionsWithFeatures(parseOptions, featuresAttribute);
}
var documentationMode = GetDocumentationMode(projectElement);
if (documentationMode != null)
{
parseOptions = parseOptions.WithDocumentationMode(documentationMode.Value);
}
return parseOptions;
}
private static ParseOptions GetPreProcessorParseOptions(string language, XAttribute preprocessorSymbolsAttribute)
{
if (language == LanguageNames.CSharp)
{
return new CSharpParseOptions(preprocessorSymbols: preprocessorSymbolsAttribute.Value.Split(','));
}
else if (language == LanguageNames.VisualBasic)
{
return new VisualBasicParseOptions(preprocessorSymbols: preprocessorSymbolsAttribute.Value
.Split(',').Select(v => KeyValuePair.Create(v.Split('=').ElementAt(0), (object)v.Split('=').ElementAt(1))).ToImmutableArray());
}
else
{
throw new ArgumentException("Unexpected language '{0}' for generating custom parse options.", language);
}
}
private static ParseOptions GetParseOptionsWithFeatures(ParseOptions parseOptions, XAttribute featuresAttribute)
{
var entries = featuresAttribute.Value.Split(';');
var features = entries.Select(x =>
{
var split = x.Split('=');
var key = split[0];
var value = split.Length == 2 ? split[1] : "true";
return new KeyValuePair<string, string>(key, value);
});
return parseOptions.WithFeatures(features);
}
private static ParseOptions GetParseOptionsWithLanguageVersion(string language, ParseOptions parseOptions, XAttribute languageVersionAttribute)
{
if (language == LanguageNames.CSharp)
{
var languageVersion = (CodeAnalysis.CSharp.LanguageVersion)Enum.Parse(typeof(CodeAnalysis.CSharp.LanguageVersion), languageVersionAttribute.Value);
parseOptions = ((CSharpParseOptions)parseOptions).WithLanguageVersion(languageVersion);
}
else if (language == LanguageNames.VisualBasic)
{
var languageVersion = (CodeAnalysis.VisualBasic.LanguageVersion)Enum.Parse(typeof(CodeAnalysis.VisualBasic.LanguageVersion), languageVersionAttribute.Value);
parseOptions = ((VisualBasicParseOptions)parseOptions).WithLanguageVersion(languageVersion);
}
return parseOptions;
}
private static DocumentationMode? GetDocumentationMode(XElement projectElement)
{
var documentationModeAttribute = projectElement.Attribute(DocumentationModeAttributeName);
if (documentationModeAttribute != null)
{
return (DocumentationMode)Enum.Parse(typeof(DocumentationMode), documentationModeAttribute.Value);
}
else
{
return null;
}
}
private static string GetAssemblyName(TestWorkspace workspace, XElement projectElement, ref int projectId)
{
var assemblyNameAttribute = projectElement.Attribute(AssemblyNameAttributeName);
if (assemblyNameAttribute != null)
{
return assemblyNameAttribute.Value;
}
var language = GetLanguage(workspace, projectElement);
projectId++;
return language == LanguageNames.CSharp ? "CSharpAssembly" + projectId :
language == LanguageNames.VisualBasic ? "VisualBasicAssembly" + projectId :
language + "Assembly" + projectId;
}
private static string GetLanguage(TestWorkspace workspace, XElement projectElement)
{
string languageName = projectElement.Attribute(LanguageAttributeName).Value;
if (!workspace.Services.SupportedLanguages.Contains(languageName))
{
throw new ArgumentException(string.Format("Language should be one of '{0}' and it is {1}",
string.Join(", ", workspace.Services.SupportedLanguages),
languageName));
}
return languageName;
}
private static CompilationOptions CreateCompilationOptions(
TestWorkspace workspace,
XElement projectElement,
string language)
{
var compilationOptionsElement = projectElement.Element(CompilationOptionsElementName);
return language == LanguageNames.CSharp || language == LanguageNames.VisualBasic
? CreateCompilationOptions(workspace, language, compilationOptionsElement)
: null;
}
private static CompilationOptions CreateCompilationOptions(TestWorkspace workspace, string language, XElement compilationOptionsElement)
{
var rootNamespace = new VisualBasicCompilationOptions(OutputKind.ConsoleApplication).RootNamespace;
var globalImports = new List<GlobalImport>();
var reportDiagnostic = ReportDiagnostic.Default;
if (compilationOptionsElement != null)
{
globalImports = compilationOptionsElement.Elements(GlobalImportElementName)
.Select(x => GlobalImport.Parse(x.Value)).ToList();
var rootNamespaceAttribute = compilationOptionsElement.Attribute(RootNamespaceAttributeName);
if (rootNamespaceAttribute != null)
{
rootNamespace = rootNamespaceAttribute.Value;
}
var reportDiagnosticAttribute = compilationOptionsElement.Attribute(ReportDiagnosticAttributeName);
if (reportDiagnosticAttribute != null)
{
reportDiagnostic = (ReportDiagnostic)Enum.Parse(typeof(ReportDiagnostic), (string)reportDiagnosticAttribute);
}
var outputTypeAttribute = compilationOptionsElement.Attribute(OutputTypeAttributeName);
if (outputTypeAttribute != null
&& outputTypeAttribute.Value == "WindowsRuntimeMetadata")
{
if (rootNamespaceAttribute == null)
{
rootNamespace = new VisualBasicCompilationOptions(OutputKind.WindowsRuntimeMetadata).RootNamespace;
}
return language == LanguageNames.CSharp
? (CompilationOptions)new CSharpCompilationOptions(OutputKind.WindowsRuntimeMetadata)
: new VisualBasicCompilationOptions(OutputKind.WindowsRuntimeMetadata).WithGlobalImports(globalImports).WithRootNamespace(rootNamespace);
}
}
else
{
// Add some common global imports by default for VB
globalImports.Add(GlobalImport.Parse("System"));
globalImports.Add(GlobalImport.Parse("System.Collections.Generic"));
globalImports.Add(GlobalImport.Parse("System.Linq"));
}
// TODO: Allow these to be specified.
var languageServices = workspace.Services.GetLanguageServices(language);
var metadataService = workspace.Services.GetService<IMetadataService>();
var compilationOptions = languageServices.GetService<ICompilationFactoryService>().GetDefaultCompilationOptions();
compilationOptions = compilationOptions.WithOutputKind(OutputKind.DynamicallyLinkedLibrary)
.WithGeneralDiagnosticOption(reportDiagnostic)
.WithSourceReferenceResolver(SourceFileResolver.Default)
.WithXmlReferenceResolver(XmlFileResolver.Default)
.WithMetadataReferenceResolver(new WorkspaceMetadataFileReferenceResolver(metadataService, new RelativePathResolver(ImmutableArray<string>.Empty, null)))
.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default);
if (language == LanguageNames.VisualBasic)
{
compilationOptions = ((VisualBasicCompilationOptions)compilationOptions).WithRootNamespace(rootNamespace)
.WithGlobalImports(globalImports);
}
return compilationOptions;
}
private static TestHostDocument CreateDocument(
TestWorkspace workspace,
XElement workspaceElement,
XElement documentElement,
string language,
ExportProvider exportProvider,
HostLanguageServices languageServiceProvider,
Dictionary<string, ITextBuffer> filePathToTextBufferMap,
ref int documentId)
{
string markupCode;
string filePath;
var isLinkFileAttribute = documentElement.Attribute(IsLinkFileAttributeName);
bool isLinkFile = isLinkFileAttribute != null && ((bool?)isLinkFileAttribute).HasValue && ((bool?)isLinkFileAttribute).Value;
if (isLinkFile)
{
// This is a linked file. Use the filePath and markup from the referenced document.
var originalAssemblyName = documentElement.Attribute(LinkAssemblyNameAttributeName)?.Value;
var originalProjectName = documentElement.Attribute(LinkProjectNameAttributeName)?.Value;
if (originalAssemblyName == null && originalProjectName == null)
{
throw new ArgumentException($"Linked files must specify either a {LinkAssemblyNameAttributeName} or {LinkProjectNameAttributeName}");
}
var originalProject = workspaceElement.Elements(ProjectElementName).FirstOrDefault(p =>
{
if (originalAssemblyName != null)
{
return p.Attribute(AssemblyNameAttributeName)?.Value == originalAssemblyName;
}
else
{
return p.Attribute(ProjectNameAttribute)?.Value == originalProjectName;
}
});
if (originalProject == null)
{
if (originalProjectName != null)
{
throw new ArgumentException($"Linked file's {LinkProjectNameAttributeName} '{originalProjectName}' project not found.");
}
else
{
throw new ArgumentException($"Linked file's {LinkAssemblyNameAttributeName} '{originalAssemblyName}' project not found.");
}
}
var originalDocumentPath = documentElement.Attribute(LinkFilePathAttributeName)?.Value;
if (originalDocumentPath == null)
{
throw new ArgumentException($"Linked files must specify a {LinkFilePathAttributeName}");
}
documentElement = originalProject.Elements(DocumentElementName).FirstOrDefault(d =>
{
return d.Attribute(FilePathAttributeName)?.Value == originalDocumentPath;
});
if (documentElement == null)
{
throw new ArgumentException($"Linked file's LinkFilePath '{originalDocumentPath}' file not found.");
}
}
markupCode = documentElement.NormalizedValue();
filePath = GetFilePath(workspace, documentElement, ref documentId);
var folders = GetFolders(documentElement);
var optionsElement = documentElement.Element(ParseOptionsElementName);
// TODO: Allow these to be specified.
var codeKind = SourceCodeKind.Regular;
if (optionsElement != null)
{
var attr = optionsElement.Attribute(KindAttributeName);
codeKind = attr == null
? SourceCodeKind.Regular
: (SourceCodeKind)Enum.Parse(typeof(SourceCodeKind), attr.Value);
}
var contentTypeLanguageService = languageServiceProvider.GetService<IContentTypeLanguageService>();
var contentType = contentTypeLanguageService.GetDefaultContentType();
string code;
int? cursorPosition;
IDictionary<string, IList<TextSpan>> spans;
MarkupTestFile.GetPositionAndSpans(markupCode, out code, out cursorPosition, out spans);
// For linked files, use the same ITextBuffer for all linked documents
ITextBuffer textBuffer;
if (!filePathToTextBufferMap.TryGetValue(filePath, out textBuffer))
{
textBuffer = EditorFactory.CreateBuffer(contentType.TypeName, exportProvider, code);
filePathToTextBufferMap.Add(filePath, textBuffer);
}
return new TestHostDocument(exportProvider, languageServiceProvider, textBuffer, filePath, cursorPosition, spans, codeKind, folders, isLinkFile);
}
private static string GetFilePath(
TestWorkspace workspace,
XElement documentElement,
ref int documentId)
{
var filePathAttribute = documentElement.Attribute(FilePathAttributeName);
if (filePathAttribute != null)
{
return filePathAttribute.Value;
}
var language = GetLanguage(workspace, documentElement.Ancestors(ProjectElementName).Single());
documentId++;
var name = "Test" + documentId;
return language == LanguageNames.CSharp ? name + ".cs" : name + ".vb";
}
private static IReadOnlyList<string> GetFolders(XElement documentElement)
{
var folderAttribute = documentElement.Attribute(FoldersAttributeName);
if (folderAttribute == null)
{
return null;
}
var folderContainers = folderAttribute.Value.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
return new ReadOnlyCollection<string>(folderContainers.ToList());
}
/// <summary>
/// Takes completely valid code, compiles it, and emits it to a MetadataReference without using
/// the file system
/// </summary>
private static MetadataReference CreateMetadataReferenceFromSource(TestWorkspace workspace, XElement referencedSource)
{
var compilation = CreateCompilation(workspace, referencedSource);
var aliasElement = referencedSource.Attribute("Aliases") != null ? referencedSource.Attribute("Aliases").Value : null;
var aliases = aliasElement != null ? aliasElement.Split(',').Select(s => s.Trim()).ToImmutableArray() : default(ImmutableArray<string>);
bool includeXmlDocComments = false;
var includeXmlDocCommentsAttribute = referencedSource.Attribute(IncludeXmlDocCommentsAttributeName);
if (includeXmlDocCommentsAttribute != null &&
((bool?)includeXmlDocCommentsAttribute).HasValue &&
((bool?)includeXmlDocCommentsAttribute).Value)
{
includeXmlDocComments = true;
}
return MetadataReference.CreateFromImage(compilation.EmitToArray(), new MetadataReferenceProperties(aliases: aliases), includeXmlDocComments ? new DeferredDocumentationProvider(compilation) : null);
}
private static Compilation CreateCompilation(TestWorkspace workspace, XElement referencedSource)
{
string languageName = GetLanguage(workspace, referencedSource);
string assemblyName = "ReferencedAssembly";
var assemblyNameAttribute = referencedSource.Attribute(AssemblyNameAttributeName);
if (assemblyNameAttribute != null)
{
assemblyName = assemblyNameAttribute.Value;
}
var languageServices = workspace.Services.GetLanguageServices(languageName);
var compilationFactory = languageServices.GetService<ICompilationFactoryService>();
var options = compilationFactory.GetDefaultCompilationOptions().WithOutputKind(OutputKind.DynamicallyLinkedLibrary);
var compilation = compilationFactory.CreateCompilation(assemblyName, options);
var documentElements = referencedSource.Elements(DocumentElementName).ToList();
foreach (var documentElement in documentElements)
{
compilation = compilation.AddSyntaxTrees(CreateSyntaxTree(languageName, documentElement.Value));
}
foreach (var reference in CreateReferenceList(workspace, referencedSource))
{
compilation = compilation.AddReferences(reference);
}
return compilation;
}
private static SyntaxTree CreateSyntaxTree(string languageName, string referencedCode)
{
if (LanguageNames.CSharp == languageName)
{
return Microsoft.CodeAnalysis.CSharp.SyntaxFactory.ParseSyntaxTree(referencedCode);
}
else
{
return Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.ParseSyntaxTree(referencedCode);
}
}
private static IList<MetadataReference> CreateReferenceList(TestWorkspace workspace, XElement element)
{
var references = CreateCommonReferences(workspace, element);
foreach (var reference in element.Elements(MetadataReferenceElementName))
{
references.Add(MetadataReference.CreateFromFile(reference.Value));
}
foreach (var metadataReferenceFromSource in element.Elements(MetadataReferenceFromSourceElementName))
{
references.Add(CreateMetadataReferenceFromSource(workspace, metadataReferenceFromSource));
}
return references;
}
private static IList<AnalyzerReference> CreateAnalyzerList(TestWorkspace workspace, XElement projectElement)
{
var analyzers = new List<AnalyzerReference>();
foreach (var analyzer in projectElement.Elements(AnalyzerElementName))
{
analyzers.Add(
new AnalyzerImageReference(
ImmutableArray<DiagnosticAnalyzer>.Empty,
display: (string)analyzer.Attribute(AnalyzerDisplayAttributeName),
fullPath: (string)analyzer.Attribute(AnalyzerFullPathAttributeName)));
}
return analyzers;
}
private static IList<MetadataReference> CreateCommonReferences(TestWorkspace workspace, XElement element)
{
var references = new List<MetadataReference>();
var net45 = element.Attribute(CommonReferencesNet45AttributeName);
if (net45 != null &&
((bool?)net45).HasValue &&
((bool?)net45).Value)
{
references = new List<MetadataReference> { TestBase.MscorlibRef_v4_0_30316_17626, TestBase.SystemRef_v4_0_30319_17929, TestBase.SystemCoreRef_v4_0_30319_17929 };
if (GetLanguage(workspace, element) == LanguageNames.VisualBasic)
{
references.Add(TestBase.MsvbRef);
references.Add(TestBase.SystemXmlRef);
references.Add(TestBase.SystemXmlLinqRef);
}
}
var commonReferencesAttribute = element.Attribute(CommonReferencesAttributeName);
if (commonReferencesAttribute != null &&
((bool?)commonReferencesAttribute).HasValue &&
((bool?)commonReferencesAttribute).Value)
{
references = new List<MetadataReference> { TestBase.MscorlibRef_v4_0_30316_17626, TestBase.SystemRef_v4_0_30319_17929, TestBase.SystemCoreRef_v4_0_30319_17929 };
if (GetLanguage(workspace, element) == LanguageNames.VisualBasic)
{
references.Add(TestBase.MsvbRef_v4_0_30319_17929);
references.Add(TestBase.SystemXmlRef);
references.Add(TestBase.SystemXmlLinqRef);
}
}
var winRT = element.Attribute(CommonReferencesWinRTAttributeName);
if (winRT != null &&
((bool?)winRT).HasValue &&
((bool?)winRT).Value)
{
references = new List<MetadataReference>(TestBase.WinRtRefs.Length);
references.AddRange(TestBase.WinRtRefs);
if (GetLanguage(workspace, element) == LanguageNames.VisualBasic)
{
references.Add(TestBase.MsvbRef_v4_0_30319_17929);
references.Add(TestBase.SystemXmlRef);
references.Add(TestBase.SystemXmlLinqRef);
}
}
var portable = element.Attribute(CommonReferencesPortableAttributeName);
if (portable != null &&
((bool?)portable).HasValue &&
((bool?)portable).Value)
{
references = new List<MetadataReference>(TestBase.PortableRefsMinimal.Length);
references.AddRange(TestBase.PortableRefsMinimal);
}
var systemRuntimeFacade = element.Attribute(CommonReferenceFacadeSystemRuntimeAttributeName);
if (systemRuntimeFacade != null &&
((bool?)systemRuntimeFacade).HasValue &&
((bool?)systemRuntimeFacade).Value)
{
references.Add(TestBase.SystemRuntimeFacadeRef);
}
return references;
}
public static bool IsWorkspaceElement(string text)
{
return text.TrimStart('\r', '\n', ' ').StartsWith("<Workspace>", StringComparison.Ordinal);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DataFactory.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.DataFactory;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// HDInsight streaming activity type.
/// </summary>
[Newtonsoft.Json.JsonObject("HDInsightStreaming")]
[Rest.Serialization.JsonTransformation]
public partial class HDInsightStreamingActivity : ExecutionActivity
{
/// <summary>
/// Initializes a new instance of the HDInsightStreamingActivity class.
/// </summary>
public HDInsightStreamingActivity()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the HDInsightStreamingActivity class.
/// </summary>
/// <param name="name">Activity name.</param>
/// <param name="mapper">Mapper executable name. Type: string (or
/// Expression with resultType string).</param>
/// <param name="reducer">Reducer executable name. Type: string (or
/// Expression with resultType string).</param>
/// <param name="input">Input blob path. Type: string (or Expression
/// with resultType string).</param>
/// <param name="output">Output blob path. Type: string (or Expression
/// with resultType string).</param>
/// <param name="filePaths">Paths to streaming job files. Can be
/// directories.</param>
/// <param name="description">Activity description.</param>
/// <param name="dependsOn">Activity depends on condition.</param>
/// <param name="linkedServiceName">Linked service reference.</param>
/// <param name="policy">Activity policy.</param>
/// <param name="storageLinkedServices">Storage linked service
/// references.</param>
/// <param name="arguments">User specified arguments to
/// HDInsightActivity.</param>
/// <param name="getDebugInfo">Debug info option. Possible values
/// include: 'None', 'Always', 'Failure'</param>
/// <param name="fileLinkedService">Linked service reference where the
/// files are located.</param>
/// <param name="combiner">Combiner executable name. Type: string (or
/// Expression with resultType string).</param>
/// <param name="commandEnvironment">Command line environment
/// values.</param>
/// <param name="defines">Allows user to specify defines for streaming
/// job request.</param>
public HDInsightStreamingActivity(string name, object mapper, object reducer, object input, object output, IList<object> filePaths, string description = default(string), IList<ActivityDependency> dependsOn = default(IList<ActivityDependency>), LinkedServiceReference linkedServiceName = default(LinkedServiceReference), ActivityPolicy policy = default(ActivityPolicy), IList<LinkedServiceReference> storageLinkedServices = default(IList<LinkedServiceReference>), IList<object> arguments = default(IList<object>), string getDebugInfo = default(string), LinkedServiceReference fileLinkedService = default(LinkedServiceReference), object combiner = default(object), IList<object> commandEnvironment = default(IList<object>), IDictionary<string, object> defines = default(IDictionary<string, object>))
: base(name, description, dependsOn, linkedServiceName, policy)
{
StorageLinkedServices = storageLinkedServices;
Arguments = arguments;
GetDebugInfo = getDebugInfo;
Mapper = mapper;
Reducer = reducer;
Input = input;
Output = output;
FilePaths = filePaths;
FileLinkedService = fileLinkedService;
Combiner = combiner;
CommandEnvironment = commandEnvironment;
Defines = defines;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets storage linked service references.
/// </summary>
[JsonProperty(PropertyName = "typeProperties.storageLinkedServices")]
public IList<LinkedServiceReference> StorageLinkedServices { get; set; }
/// <summary>
/// Gets or sets user specified arguments to HDInsightActivity.
/// </summary>
[JsonProperty(PropertyName = "typeProperties.arguments")]
public IList<object> Arguments { get; set; }
/// <summary>
/// Gets or sets debug info option. Possible values include: 'None',
/// 'Always', 'Failure'
/// </summary>
[JsonProperty(PropertyName = "typeProperties.getDebugInfo")]
public string GetDebugInfo { get; set; }
/// <summary>
/// Gets or sets mapper executable name. Type: string (or Expression
/// with resultType string).
/// </summary>
[JsonProperty(PropertyName = "typeProperties.mapper")]
public object Mapper { get; set; }
/// <summary>
/// Gets or sets reducer executable name. Type: string (or Expression
/// with resultType string).
/// </summary>
[JsonProperty(PropertyName = "typeProperties.reducer")]
public object Reducer { get; set; }
/// <summary>
/// Gets or sets input blob path. Type: string (or Expression with
/// resultType string).
/// </summary>
[JsonProperty(PropertyName = "typeProperties.input")]
public object Input { get; set; }
/// <summary>
/// Gets or sets output blob path. Type: string (or Expression with
/// resultType string).
/// </summary>
[JsonProperty(PropertyName = "typeProperties.output")]
public object Output { get; set; }
/// <summary>
/// Gets or sets paths to streaming job files. Can be directories.
/// </summary>
[JsonProperty(PropertyName = "typeProperties.filePaths")]
public IList<object> FilePaths { get; set; }
/// <summary>
/// Gets or sets linked service reference where the files are located.
/// </summary>
[JsonProperty(PropertyName = "typeProperties.fileLinkedService")]
public LinkedServiceReference FileLinkedService { get; set; }
/// <summary>
/// Gets or sets combiner executable name. Type: string (or Expression
/// with resultType string).
/// </summary>
[JsonProperty(PropertyName = "typeProperties.combiner")]
public object Combiner { get; set; }
/// <summary>
/// Gets or sets command line environment values.
/// </summary>
[JsonProperty(PropertyName = "typeProperties.commandEnvironment")]
public IList<object> CommandEnvironment { get; set; }
/// <summary>
/// Gets or sets allows user to specify defines for streaming job
/// request.
/// </summary>
[JsonProperty(PropertyName = "typeProperties.defines")]
public IDictionary<string, object> Defines { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public override void Validate()
{
base.Validate();
if (Mapper == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Mapper");
}
if (Reducer == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Reducer");
}
if (Input == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Input");
}
if (Output == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Output");
}
if (FilePaths == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "FilePaths");
}
if (StorageLinkedServices != null)
{
foreach (var element in StorageLinkedServices)
{
if (element != null)
{
element.Validate();
}
}
}
if (FileLinkedService != null)
{
FileLinkedService.Validate();
}
}
}
}
| |
/*
Copyright(c) 2009, Stefan Simek
Copyright(c) 2016, Vladyslav Taranov
MIT License
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using TriAxis.RunSharp;
#if FEAT_IKVM
using IKVM.Reflection;
using IKVM.Reflection.Emit;
using Type = IKVM.Reflection.Type;
using MissingMethodException = System.MissingMethodException;
using MissingMemberException = System.MissingMemberException;
using DefaultMemberAttribute = System.Reflection.DefaultMemberAttribute;
using Attribute = IKVM.Reflection.CustomAttributeData;
using BindingFlags = IKVM.Reflection.BindingFlags;
#else
using System.Reflection;
using System.Reflection.Emit;
#endif
namespace TriAxis.RunSharp
{
using Operands;
public interface ICodeGenBasicContext
{
ITypeMapper TypeMapper { get; }
StaticFactory StaticFactory { get; }
ExpressionFactory ExpressionFactory { get; }
}
public interface ICodeGenContext : IMemberInfo, ISignatureGen, ICodeGenBasicContext, IDelayedDefinition, IDelayedCompletion
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Typical implementation invokes XxxBuilder.GetILGenerator() which is a method as well.")]
ILGenerator GetILGenerator();
Type OwnerType { get; }
bool SupportsScopes { get; }
}
public partial class CodeGen : ICodeGenContext
{
readonly bool _isOwner;
#if !PHONE8
readonly ConstructorGen _cg;
#endif
bool _chainCalled;
bool _isReachable = true;
StackTrace _unreachableFrom;
public bool IsReachable
{
get
{
return _isReachable;
}
private set
{
_isReachable = value;
_unreachableFrom = (value || !RunSharpDebug.CaptureStackOnUnreachable)
? null :
#if !SILVERLIGHT
new StackTrace(1, true);
#else
new StackTrace();
#endif
}
}
public void ForceResetUnreachableState()
{
_isReachable = true;
}
bool _hasRetVar, _hasRetLabel;
LocalBuilder _retVar;
Label _retLabel;
readonly Stack<Block> _blocks = new Stack<Block>();
readonly Dictionary<string, Label> _labels = new Dictionary<string, Label>();
readonly Dictionary<string, Operand> _namedLocals = new Dictionary<string, Operand>();
protected internal ILGenerator IL { get; }
protected internal ICodeGenContext Context { get; }
public StaticFactory StaticFactory => Context.StaticFactory;
public ExpressionFactory ExpressionFactory => Context.ExpressionFactory;
public CodeGen(ICodeGenContext context, bool isOwner = true)
{
_isOwner = isOwner;
Context = context;
#if !PHONE8
_cg = context as ConstructorGen;
if (_cg != null && _cg.IsStatic)
// #14 - cg is relevant for instance constructors - it wreaks havoc in a static constructor
_cg = null;
#endif
IL = context.GetILGenerator();
}
#region Arguments
public ContextualOperand This()
{
if (Context.IsStatic)
throw new InvalidOperationException(Properties.Messages.ErrCodeStaticThis);
Type ownerType = Context.OwnerType;
if (Context.OwnerType.IsValueType)
{
var m = Context.Member as MethodInfo;
if (m != null && m.IsVirtual)
ownerType = ownerType.MakeByRefType();
}
Operand arg = new _Arg(0, ownerType);
return new ContextualOperand(arg, TypeMapper);
}
public ContextualOperand Base()
{
if (Context.IsStatic)
return new ContextualOperand(new StaticTarget(Context.OwnerType.BaseType), TypeMapper);
else
return new ContextualOperand(new _Base(Context.OwnerType.BaseType), TypeMapper);
}
int ThisOffset => Context.IsStatic ? 0 : 1;
public ContextualOperand PropertyValue()
{
Type[] parameterTypes = Context.ParameterTypes;
return new ContextualOperand(new _Arg(ThisOffset + parameterTypes.Length - 1, parameterTypes[parameterTypes.Length - 1]), TypeMapper);
}
public ContextualOperand Arg(string name)
{
var param = Context.GetParameterByName(name);
return new ContextualOperand(new _Arg(ThisOffset + param.Position - 1, param.Type), TypeMapper);
}
/// <summary>
/// ThisOffset is applied inside
/// </summary>
/// <param name="parameterIndex"></param>
/// <returns></returns>
public ContextualOperand Arg(int parameterIndex)
{
return new ContextualOperand(new _Arg(ThisOffset + parameterIndex, Context.ParameterTypes[parameterIndex]), TypeMapper);
}
#endregion
#region Locals
protected ContextualOperand WrapExistingLocal(LocalBuilder local)
{
if (local == null) throw new ArgumentNullException(nameof(local));
return new ContextualOperand(new _Local(this, local), TypeMapper);
}
public ContextualOperand Local()
{
return new ContextualOperand(new _Local(this), TypeMapper);
}
public ContextualOperand Local(Operand init)
{
Operand var = Local();
Assign(var, init);
return new ContextualOperand(var, TypeMapper);
}
#if FEAT_IKVM
public ContextualOperand Local(System.Type type)
{
return Local(TypeMapper.MapType(type));
}
#endif
public ContextualOperand Local(Type type)
{
return new ContextualOperand(new _Local(this, type), TypeMapper);
}
#if FEAT_IKVM
public ContextualOperand Local(System.Type type, Operand init)
{
return Local(TypeMapper.MapType(type), init);
}
#endif
internal ContextualOperand LocalInitedFromStack(Type type)
{
var l = new _Local(this, type);
l.EmitSetFromStack(this);
return new ContextualOperand(l, TypeMapper);
}
#if FEAT_IKVM
internal ContextualOperand LocalInitedFromStack(System.Type type)
{
return LocalInitedFromStack(TypeMapper.MapType(type));
}
#endif
public ContextualOperand Local(Type type, Operand init)
{
Operand var = Local(type);
Assign(var, init);
return new ContextualOperand(var, TypeMapper);
}
#endregion
bool HasReturnValue
{
get
{
Type returnType = Context.ReturnType;
return returnType != null && !Helpers.AreTypesEqual(returnType, typeof(void), TypeMapper);
}
}
void EnsureReturnVariable()
{
if (!_isOwner)
throw new InvalidOperationException("CodeGen is not an owner of the context");
if (_hasRetVar)
return;
_retLabel = IL.DefineLabel();
if (HasReturnValue)
_retVar = IL.DeclareLocal(Context.ReturnType);
_hasRetVar = true;
}
public bool IsCompleted => _blocks.Count == 0 && (!_isOwner || !IsReachable) && _hasRetVar == _hasRetLabel;
internal void Complete()
{
if (_blocks.Count > 0)
throw new InvalidOperationException(Properties.Messages.ErrOpenBlocksRemaining);
if (IsReachable)
{
if (HasReturnValue)
throw new InvalidOperationException(string.Format(null, Properties.Messages.ErrMethodMustReturnValue, Context));
else if (_isOwner)
Return();
}
if (_hasRetVar && !_hasRetLabel)
{
IL.MarkLabel(_retLabel);
if (_retVar != null)
IL.Emit(OpCodes.Ldloc, _retVar);
IL.Emit(OpCodes.Ret);
_hasRetLabel = true;
}
}
class _Base : _Arg
{
public _Base(Type type) : base(0, type) { }
protected internal override bool SuppressVirtual => true;
}
class _Arg : Operand
{
protected override bool DetectsLeaking => false;
readonly ushort _index;
readonly Type _type;
public _Arg(int index, Type type)
{
_index = checked((ushort)index);
_type = type;
}
protected internal override void EmitGet(CodeGen g)
{
OperandExtensions.SetLeakedState(this, false);
g.EmitLdargHelper(_index);
if (IsReference)
g.EmitLdindHelper(GetReturnType(g.TypeMapper));
}
protected internal override void EmitSet(CodeGen g, Operand value, bool allowExplicitConversion)
{
OperandExtensions.SetLeakedState(this, false);
if (IsReference)
{
g.EmitLdargHelper(_index);
g.EmitStindHelper(GetReturnType(g.TypeMapper), value, allowExplicitConversion);
}
else
{
g.EmitGetHelper(value, GetReturnType(g.TypeMapper), allowExplicitConversion);
g.EmitStargHelper(_index);
}
}
protected internal override void EmitAddressOf(CodeGen g)
{
OperandExtensions.SetLeakedState(this, false);
if (IsReference)
{
g.EmitLdargHelper(_index);
}
else
{
if (_index <= byte.MaxValue)
g.IL.Emit(OpCodes.Ldarga_S, (byte)_index);
else
g.IL.Emit(OpCodes.Ldarga, _index);
}
}
bool IsReference => _type.IsByRef;
public override Type GetReturnType(ITypeMapper typeMapper) => IsReference ? _type.GetElementType() : _type;
protected internal override bool TrivialAccess => true;
}
internal class _Local : Operand
{
protected override bool DetectsLeaking => false;
readonly CodeGen _owner;
LocalBuilder _var;
readonly Block _scope;
Type _t, _tHint;
public _Local(CodeGen owner)
{
_owner = owner;
_scope = owner.GetBlockForVariable();
}
public _Local(CodeGen owner, Type t)
{
_owner = owner; _t = t;
_scope = owner.GetBlockForVariable();
}
public _Local(CodeGen owner, LocalBuilder var)
{
_owner = owner;
_var = var;
_t = var.LocalType;
}
void CheckScope(CodeGen g)
{
if (g != _owner)
throw new InvalidOperationException(Properties.Messages.ErrInvalidVariableContext);
if (_scope != null && !_owner._blocks.Contains(_scope))
throw new InvalidOperationException(Properties.Messages.ErrInvalidVariableScope);
}
internal void EmitSetFromStack(CodeGen g)
{
OperandExtensions.SetLeakedState(this, false);
if (_var == null)
{
if (_t == null) throw new InvalidOperationException("Can't set value from stack for local when no type was specified");
_var = g.IL.DeclareLocal(_t);
}
switch (_var.LocalIndex)
{
case 0:
g.IL.Emit(OpCodes.Stloc_0);
break;
case 1:
g.IL.Emit(OpCodes.Stloc_1);
break;
case 2:
g.IL.Emit(OpCodes.Stloc_2);
break;
case 3:
g.IL.Emit(OpCodes.Stloc_3);
break;
default:
g.IL.Emit(OpCodes.Stloc, _var);
break;
}
}
protected internal override void EmitGet(CodeGen g)
{
OperandExtensions.SetLeakedState(this, false);
CheckScope(g);
if (_var == null)
throw new InvalidOperationException(Properties.Messages.ErrUninitializedVarAccess);
switch (_var.LocalIndex)
{
case 0:
g.IL.Emit(OpCodes.Ldloc_0);
break;
case 1:
g.IL.Emit(OpCodes.Ldloc_1);
break;
case 2:
g.IL.Emit(OpCodes.Ldloc_2);
break;
case 3:
g.IL.Emit(OpCodes.Ldloc_3);
break;
default:
g.IL.Emit(OpCodes.Ldloc, _var);
break;
}
}
protected internal override void EmitSet(CodeGen g, Operand value, bool allowExplicitConversion)
{
OperandExtensions.SetLeakedState(this, false);
CheckScope(g);
if (_t == null)
_t = value.GetReturnType(g.TypeMapper);
if (_var == null)
_var = g.IL.DeclareLocal(_t);
Type nullableUnderlyingType = Helpers.GetNullableUnderlyingType(_t);
if (ReferenceEquals(value, null))
{
if (nullableUnderlyingType != null)
{
g.InitObj(this);
return;
}
}
else if (nullableUnderlyingType == value.GetReturnType(g.TypeMapper))
{
EmitAddressOf(g);
g.EmitGetHelper(value, nullableUnderlyingType, false);
ConstructorInfo ctor = _t.GetConstructor(new [] { nullableUnderlyingType});
g.IL.Emit(OpCodes.Call, ctor);
return;
}
g.EmitGetHelper(value, _t, allowExplicitConversion);
EmitSetFromStack(g);
}
protected internal override void EmitAddressOf(CodeGen g)
{
OperandExtensions.SetLeakedState(this, false);
CheckScope(g);
if (_var == null)
{
RequireType();
_var = g.IL.DeclareLocal(_t);
}
g.IL.Emit(OpCodes.Ldloca, _var);
}
public override Type GetReturnType(ITypeMapper typeMapper)
{
RequireType();
return _t;
}
void RequireType()
{
if (_t == null)
{
if (_tHint != null)
_t = _tHint;
else
throw new InvalidOperationException(Properties.Messages.ErrUntypedVarAccess);
}
}
protected internal override bool TrivialAccess => true;
protected internal override void AssignmentHint(Operand op)
{
if (_tHint == null)
_tHint = GetType(op, _owner.TypeMapper);
}
}
class StaticTarget : Operand
{
public StaticTarget(Type t) { _type = t; }
readonly Type _type;
public override Type GetReturnType(ITypeMapper typeMapper)
{
return _type;
}
protected internal override bool IsStaticTarget => true;
}
public Operand this[string localName] // Named locals support.
{
get
{
Operand target;
if (!_namedLocals.TryGetValue(localName, out target))
throw new InvalidOperationException(Properties.Messages.ErrUninitializedVarAccess);
return target;
}
set
{
Operand target;
if (_namedLocals.TryGetValue(localName, out target))
// run in statement form; C# left-to-right evaluation semantics "just work"
Assign(target, value);
else
_namedLocals.Add(localName, Local(value));
}
}
public Label Label(string labelName)
{
Label label;
if (!_labels.TryGetValue(labelName, out label))
_labels.Add(labelName, label = IL.DefineLabel());
IL.MarkLabel(label);
return label;
}
public Label DefineLabel()
{
return IL.DefineLabel();
}
public void MarkLabel(Label label)
{
IL.MarkLabel(label);
}
public void Goto(string labelName)
{
Label label;
if (!_labels.TryGetValue(labelName, out label))
_labels.Add(labelName, label = IL.DefineLabel());
Goto(label);
}
public void Goto(Label label)
{
IL.Emit(OpCodes.Br, label);
}
#region Context explicit delegation
MemberInfo IMemberInfo.Member { get { return Context.Member; } }
string IMemberInfo.Name { get { return Context.Name; } }
Type IMemberInfo.ReturnType { get { return Context.ReturnType; } }
Type[] IMemberInfo.ParameterTypes { get { return Context.ParameterTypes; } }
bool IMemberInfo.IsParameterArray { get { return Context.IsParameterArray; } }
bool IMemberInfo.IsStatic { get { return Context.IsStatic; } }
bool IMemberInfo.IsOverride { get { return Context.IsOverride; } }
ParameterBuilder ISignatureGen.DefineParameter(int position, ParameterAttributes attributes, string parameterName)
{
return Context.DefineParameter(position, attributes, parameterName);
}
IParameterBasicInfo ISignatureGen.GetParameterByName(string parameterName)
{
return Context.GetParameterByName(parameterName);
}
StaticFactory ICodeGenBasicContext.StaticFactory { get { return Context.StaticFactory; } }
ExpressionFactory ICodeGenBasicContext.ExpressionFactory { get { return Context.ExpressionFactory; } }
void IDelayedDefinition.EndDefinition()
{
Context.EndDefinition();
}
void IDelayedCompletion.Complete()
{
Context.Complete();
}
ILGenerator ICodeGenContext.GetILGenerator()
{
return Context.GetILGenerator();
}
Type ICodeGenContext.OwnerType { get { return Context.OwnerType; } }
bool ICodeGenContext.SupportsScopes { get { return Context.SupportsScopes; } }
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Reactive.Linq;
using System.Text.RegularExpressions;
using Microsoft.Its.Recipes;
namespace Microsoft.Its.Domain
{
public static class EventHandler
{
private static readonly ConcurrentDictionary<Type, ReflectedEventHandlerBinder[]> reflectedBinders =
new ConcurrentDictionary<Type, ReflectedEventHandlerBinder[]>();
private static readonly ConcurrentDictionary<Type, string> handlerTypeNames = new ConcurrentDictionary<Type, string>();
public static IEventHandler WrapAll(
this object eventHandler,
Handle<IEvent> proxy,
string aliasForCatchup = null)
{
var compositeProjector = new EventHandlerWrapper(eventHandler);
compositeProjector.WrapAll(proxy);
return compositeProjector;
}
public static IEventHandler Named(this IEventHandler handler, string name)
{
// TODO: (Named) make this more generalizable
handler.IfTypeIs<EventHandlerWrapper>()
.ThenDo(h => h.Name = name)
.ElseDo(() => handler.IfTypeIs<CompositeEventHandler>()
.ThenDo(h => h.Name = name)
.ElseDo(() => { throw new NotImplementedException(string.Format("Handlers of type {0} do not support naming yet.", handler)); }));
return handler;
}
public static IHaveConsequencesWhen<TEvent> Named<TEvent>(this IHaveConsequencesWhen<TEvent> consequenter, string name)
where TEvent : IEvent
{
var named = consequenter as AnonymousConsequenter<TEvent>;
if (named == null)
{
// TODO: (Named)
throw new NotImplementedException(string.Format("Handlers of type {0} do not support naming yet.", consequenter));
}
named.Name = name;
return consequenter;
}
public static IUpdateProjectionWhen<TEvent> Named<TEvent>(this IUpdateProjectionWhen<TEvent> projector, string name)
where TEvent : IEvent
{
var named = projector as AnonymousProjector<TEvent>;
if (named == null)
{
// TODO: (Named)
throw new NotImplementedException(string.Format("Handlers of type {0} do not support naming yet.", projector));
}
named.Name = name;
return projector;
}
public static IEnumerable<IEventHandlerBinder> GetBinders(object handler)
{
return handler.IfTypeIs<IEventHandler>()
.Then(h => h.GetBinders())
.Else(() => GetBindersUsingReflection(handler));
}
public static bool IsEventHandlerType(this Type type)
{
return type.IsConsequenterType() ||
type.IsProjectorType() ||
type.GetInterfaces().Any(i => i == typeof (IEventHandler));
}
/// <summary>
/// Gets a short (non-namespace qualified) name for the specified event handler.
/// </summary>
/// <param name="handler">The event handler.</param>
public static string Name(object handler)
{
EnsureIsHandler(handler);
var named = handler as INamedEventHandler;
if (named != null && !string.IsNullOrWhiteSpace(named.Name))
{
return named.Name;
}
return handlerTypeNames.GetOrAdd(handler.InnerHandler().GetType(),
t =>
{
if (t == typeof (EventHandlerWrapper))
{
return null;
}
if (t.IsConstructedGenericType)
{
if (t.GetGenericTypeDefinition() == typeof (AnonymousConsequenter<>))
{
return "AnonymousConsequenter";
}
if (t.GetGenericTypeDefinition() == typeof (AnonymousProjector<>))
{
return "AnonymousProjector";
}
}
return t.Name;
});
}
public static string FullName(object handler)
{
EnsureIsHandler(handler);
var named = handler as INamedEventHandler;
if (named != null && !string.IsNullOrWhiteSpace(named.Name))
{
return named.Name;
}
return AttributedModelServices.GetContractName(handler.GetType());
}
private static void EnsureIsHandler(object handler)
{
if (handler == null)
{
throw new ArgumentNullException("handler");
}
if (!handler.GetType().IsEventHandlerType())
{
throw new ArgumentException(string.Format("Type {0} is not an event handler.", handler));
}
}
private static IEnumerable<IEventHandlerBinder> GetBindersUsingReflection(object handler)
{
return reflectedBinders
.GetOrAdd(handler.GetType(),
t =>
{
// find the handler's implementations
var bindings = t.ImplementedHandlerInterfaces()
.Select(i => new ReflectedEventHandlerBinder(i.GetGenericArguments().First(), i))
.ToArray();
if (bindings.Length == 0)
{
throw new ArgumentException(String.Format("Type {0} does not implement any event handler interfaces.", handler.GetType()));
}
return bindings;
});
}
internal static IEnumerable<MatchEvent> MatchesEvents(this object handler)
{
return GetBinders(handler)
.SelectMany(binder =>
binder.IfTypeIs<IEventQuery>()
.Then(q => q.IncludedEventTypes)
.Else(() => binder.IfTypeIs<ReflectedEventHandlerBinder>()
.Then(b => MatchBasedOnEventType(b.EventType))
.Else(() =>
{
return Enumerable.Empty<MatchEvent>();
})));
}
private static IEnumerable<MatchEvent> MatchBasedOnEventType(Type eventType)
{
var eventTypes = Event.ConcreteTypesOf(eventType)
.ToArray();
var matchBasedOnEventType = eventTypes.Select(e => new MatchEvent(type: e.EventName(),
streamName: e.AggregateTypeForEventType()
.IfNotNull()
.Then(AggregateType.EventStreamName)
.Else(() => MatchEvent.Wildcard)));
return matchBasedOnEventType;
}
/// <summary>
/// Gets the innermost handler in a handler chain, or the handler itself if it is not chained.
/// </summary>
/// <param name="handler">The handler.</param>
public static object InnerHandler(this object handler)
{
return handler.IfTypeIs<IEventHandlerWrapper>()
.Then(b => b.InnerHandler.InnerHandler())
.Else(() => handler);
}
internal static IDisposable SubscribeProjector<TEvent, TProjector>(
TProjector handler,
IObservable<TEvent> observable,
IEventBus bus)
where TEvent : IEvent
where TProjector : class, IUpdateProjectionWhen<TEvent>
{
return observable
.Subscribe(
onNext: e =>
{
try
{
handler.UpdateProjection(e);
}
catch (Exception exception)
{
var error = new EventHandlingError(exception, handler, e);
bus.PublishErrorAsync(error).Wait();
}
},
onError: exception => bus.PublishErrorAsync(new EventHandlingError(exception, handler))
.Wait());
}
internal static IDisposable SubscribeConsequences<TEvent>(
IHaveConsequencesWhen<TEvent> handler,
IObservable<TEvent> observable,
IEventBus bus)
where TEvent : IEvent
{
return
observable
.Subscribe(
onNext: e =>
{
try
{
handler.HaveConsequences(e);
}
catch (Exception exception)
{
var error = new EventHandlingError(exception, handler, e);
bus.PublishErrorAsync(error).Wait();
}
},
onError: exception => bus.PublishErrorAsync(new EventHandlingError(exception, handler))
.Wait());
}
internal static IDisposable SubscribeDurablyAndPublishErrors<THandler, TEvent>(
this IObservable<TEvent> events,
THandler handler,
Action<TEvent> handle,
IEventBus bus)
where TEvent : IEvent
{
return
events.Subscribe(
onNext: e =>
{
try
{
handle(e);
}
catch (Exception exception)
{
var error = new EventHandlingError(exception, handler, e);
bus.PublishErrorAsync(error).Wait();
}
},
onError: exception => bus.PublishErrorAsync(new EventHandlingError(exception, handler))
.Wait());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//------------------------------------------------------------------------------
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Text;
using Res = System.SR;
namespace System.Data.SqlClient
{
internal enum CallbackType
{
Read = 0,
Write = 1
}
internal enum EncryptionOptions
{
OFF,
ON,
NOT_SUP,
REQ,
LOGIN
}
internal enum PreLoginHandshakeStatus
{
Successful,
InstanceFailure
}
internal enum PreLoginOptions
{
VERSION,
ENCRYPT,
INSTANCE,
THREADID,
MARS,
TRACEID,
NUMOPT,
LASTOPT = 255
}
internal enum RunBehavior
{
UntilDone = 1, // 0001 binary
ReturnImmediately = 2, // 0010 binary
Clean = 5, // 0101 binary - Clean AND UntilDone
Attention = 13 // 1101 binary - Clean AND UntilDone AND Attention
}
internal enum TdsParserState
{
Closed,
OpenNotLoggedIn,
OpenLoggedIn,
Broken,
}
sealed internal class SqlCollation
{
// First 20 bits of info field represent the lcid, bits 21-25 are compare options
private const uint IgnoreCase = 1 << 20; // bit 21 - IgnoreCase
private const uint IgnoreNonSpace = 1 << 21; // bit 22 - IgnoreNonSpace / IgnoreAccent
private const uint IgnoreWidth = 1 << 22; // bit 23 - IgnoreWidth
private const uint IgnoreKanaType = 1 << 23; // bit 24 - IgnoreKanaType
private const uint BinarySort = 1 << 24; // bit 25 - BinarySort
internal const uint MaskLcid = 0xfffff;
private const int LcidVersionBitOffset = 28;
private const uint MaskLcidVersion = unchecked((uint)(0xf << LcidVersionBitOffset));
private const uint MaskCompareOpt = IgnoreCase | IgnoreNonSpace | IgnoreWidth | IgnoreKanaType | BinarySort;
internal uint info;
internal byte sortId;
private static int FirstSupportedCollationVersion(int lcid)
{
// NOTE: switch-case works ~3 times faster in this case than search with Dictionary
switch (lcid)
{
case 1044: return 2; // Norwegian_100_BIN
case 1047: return 2; // Romansh_100_BIN
case 1056: return 2; // Urdu_100_BIN
case 1065: return 2; // Persian_100_BIN
case 1068: return 2; // Azeri_Latin_100_BIN
case 1070: return 2; // Upper_Sorbian_100_BIN
case 1071: return 1; // Macedonian_FYROM_90_BIN
case 1081: return 1; // Indic_General_90_BIN
case 1082: return 2; // Maltese_100_BIN
case 1083: return 2; // Sami_Norway_100_BIN
case 1087: return 1; // Kazakh_90_BIN
case 1090: return 2; // Turkmen_100_BIN
case 1091: return 1; // Uzbek_Latin_90_BIN
case 1092: return 1; // Tatar_90_BIN
case 1093: return 2; // Bengali_100_BIN
case 1101: return 2; // Assamese_100_BIN
case 1105: return 2; // Tibetan_100_BIN
case 1106: return 2; // Welsh_100_BIN
case 1107: return 2; // Khmer_100_BIN
case 1108: return 2; // Lao_100_BIN
case 1114: return 1; // Syriac_90_BIN
case 1121: return 2; // Nepali_100_BIN
case 1122: return 2; // Frisian_100_BIN
case 1123: return 2; // Pashto_100_BIN
case 1125: return 1; // Divehi_90_BIN
case 1133: return 2; // Bashkir_100_BIN
case 1146: return 2; // Mapudungan_100_BIN
case 1148: return 2; // Mohawk_100_BIN
case 1150: return 2; // Breton_100_BIN
case 1152: return 2; // Uighur_100_BIN
case 1153: return 2; // Maori_100_BIN
case 1155: return 2; // Corsican_100_BIN
case 1157: return 2; // Yakut_100_BIN
case 1164: return 2; // Dari_100_BIN
case 2074: return 2; // Serbian_Latin_100_BIN
case 2092: return 2; // Azeri_Cyrillic_100_BIN
case 2107: return 2; // Sami_Sweden_Finland_100_BIN
case 2143: return 2; // Tamazight_100_BIN
case 3076: return 1; // Chinese_Hong_Kong_Stroke_90_BIN
case 3098: return 2; // Serbian_Cyrillic_100_BIN
case 5124: return 2; // Chinese_Traditional_Pinyin_100_BIN
case 5146: return 2; // Bosnian_Latin_100_BIN
case 8218: return 2; // Bosnian_Cyrillic_100_BIN
default: return 0; // other LCIDs have collation with version 0
}
}
internal int LCID
{
// First 20 bits of info field represent the lcid
get
{
return unchecked((int)(info & MaskLcid));
}
set
{
int lcid = value & (int)MaskLcid;
Debug.Assert(lcid == value, "invalid set_LCID value");
// Some new Katmai LCIDs do not have collation with version = 0
// since user has no way to specify collation version, we set the first (minimal) supported version for these collations
int versionBits = FirstSupportedCollationVersion(lcid) << LcidVersionBitOffset;
Debug.Assert((versionBits & MaskLcidVersion) == versionBits, "invalid version returned by FirstSupportedCollationVersion");
// combine the current compare options with the new locale ID and its first supported version
info = (info & MaskCompareOpt) | unchecked((uint)lcid) | unchecked((uint)versionBits);
}
}
internal SqlCompareOptions SqlCompareOptions
{
get
{
SqlCompareOptions options = SqlCompareOptions.None;
if (0 != (info & IgnoreCase))
options |= SqlCompareOptions.IgnoreCase;
if (0 != (info & IgnoreNonSpace))
options |= SqlCompareOptions.IgnoreNonSpace;
if (0 != (info & IgnoreWidth))
options |= SqlCompareOptions.IgnoreWidth;
if (0 != (info & IgnoreKanaType))
options |= SqlCompareOptions.IgnoreKanaType;
if (0 != (info & BinarySort))
options |= SqlCompareOptions.BinarySort;
return options;
}
set
{
Debug.Assert((value & SqlString.x_iValidSqlCompareOptionMask) == value, "invalid set_SqlCompareOptions value");
uint tmp = 0;
if (0 != (value & SqlCompareOptions.IgnoreCase))
tmp |= IgnoreCase;
if (0 != (value & SqlCompareOptions.IgnoreNonSpace))
tmp |= IgnoreNonSpace;
if (0 != (value & SqlCompareOptions.IgnoreWidth))
tmp |= IgnoreWidth;
if (0 != (value & SqlCompareOptions.IgnoreKanaType))
tmp |= IgnoreKanaType;
if (0 != (value & SqlCompareOptions.BinarySort))
tmp |= BinarySort;
info = (info & MaskLcid) | tmp;
}
}
static internal bool AreSame(SqlCollation a, SqlCollation b)
{
if (a == null || b == null)
{
return a == b;
}
else
{
return a.info == b.info && a.sortId == b.sortId;
}
}
}
internal class RoutingInfo
{
internal byte Protocol { get; private set; }
internal UInt16 Port { get; private set; }
internal string ServerName { get; private set; }
internal RoutingInfo(byte protocol, UInt16 port, string servername)
{
Protocol = protocol;
Port = port;
ServerName = servername;
}
}
sealed internal class SqlEnvChange
{
internal byte type;
internal byte oldLength;
internal int newLength; // 7206 TDS changes makes this length an int
internal int length;
internal string newValue;
internal string oldValue;
internal byte[] newBinValue;
internal byte[] oldBinValue;
internal long newLongValue;
internal long oldLongValue;
internal SqlCollation newCollation;
internal SqlCollation oldCollation;
internal RoutingInfo newRoutingInfo;
}
sealed internal class SqlLogin
{
internal int timeout; // login timeout
internal bool userInstance = false; // user instance
internal string hostName = ""; // client machine name
internal string userName = ""; // user id
internal string password = ""; // password
internal string applicationName = ""; // application name
internal string serverName = ""; // server name
internal string language = ""; // initial language
internal string database = ""; // initial database
internal string attachDBFilename = ""; // DB filename to be attached
internal bool useReplication = false; // user login for replication
internal bool useSSPI = false; // use integrated security
internal int packetSize = SqlConnectionString.DEFAULT.Packet_Size; // packet size
internal bool readOnlyIntent = false; // read-only intent
}
sealed internal class SqlLoginAck
{
internal byte majorVersion;
internal byte minorVersion;
internal short buildNum;
internal UInt32 tdsVersion;
}
sealed internal class _SqlMetaData : SqlMetaDataPriv
{
internal string column;
internal MultiPartTableName multiPartTableName;
internal readonly int ordinal;
internal byte updatability; // two bit field (0 is read only, 1 is updatable, 2 is updatability unknown)
internal bool isDifferentName;
internal bool isKey;
internal bool isHidden;
internal bool isExpression;
internal bool isIdentity;
internal _SqlMetaData(int ordinal) : base()
{
this.ordinal = ordinal;
}
internal string serverName
{
get
{
return multiPartTableName.ServerName;
}
}
internal string catalogName
{
get
{
return multiPartTableName.CatalogName;
}
}
internal string schemaName
{
get
{
return multiPartTableName.SchemaName;
}
}
internal string tableName
{
get
{
return multiPartTableName.TableName;
}
}
internal bool IsNewKatmaiDateTimeType
{
get
{
return SqlDbType.Date == type || SqlDbType.Time == type || SqlDbType.DateTime2 == type || SqlDbType.DateTimeOffset == type;
}
}
internal bool IsLargeUdt
{
get
{
return type == SqlDbType.Udt && length == Int32.MaxValue;
}
}
public object Clone()
{
_SqlMetaData result = new _SqlMetaData(ordinal);
result.CopyFrom(this);
result.column = column;
result.multiPartTableName = multiPartTableName;
result.updatability = updatability;
result.isKey = isKey;
result.isHidden = isHidden;
result.isIdentity = isIdentity;
return result;
}
}
sealed internal class _SqlMetaDataSet
{
internal ushort id; // for altrow-columns only
internal int[] indexMap;
internal int visibleColumns;
private readonly _SqlMetaData[] _metaDataArray;
internal _SqlMetaDataSet(int count)
{
_metaDataArray = new _SqlMetaData[count];
for (int i = 0; i < _metaDataArray.Length; ++i)
{
_metaDataArray[i] = new _SqlMetaData(i);
}
}
private _SqlMetaDataSet(_SqlMetaDataSet original)
{
this.id = original.id;
// although indexMap is not immutable, in practice it is initialized once and then passed around
this.indexMap = original.indexMap;
this.visibleColumns = original.visibleColumns;
if (original._metaDataArray == null)
{
_metaDataArray = null;
}
else
{
_metaDataArray = new _SqlMetaData[original._metaDataArray.Length];
for (int idx = 0; idx < _metaDataArray.Length; idx++)
{
_metaDataArray[idx] = (_SqlMetaData)original._metaDataArray[idx].Clone();
}
}
}
internal int Length
{
get
{
return _metaDataArray.Length;
}
}
internal _SqlMetaData this[int index]
{
get
{
return _metaDataArray[index];
}
set
{
Debug.Assert(null == value, "used only by SqlBulkCopy");
_metaDataArray[index] = value;
}
}
public object Clone()
{
return new _SqlMetaDataSet(this);
}
}
sealed internal class _SqlMetaDataSetCollection
{
private readonly List<_SqlMetaDataSet> _altMetaDataSetArray;
internal _SqlMetaDataSet metaDataSet;
internal _SqlMetaDataSetCollection()
{
_altMetaDataSetArray = new List<_SqlMetaDataSet>();
}
internal void SetAltMetaData(_SqlMetaDataSet altMetaDataSet)
{
// If altmetadata with same id is found, override it rather than adding a new one
int newId = altMetaDataSet.id;
for (int i = 0; i < _altMetaDataSetArray.Count; i++)
{
if (_altMetaDataSetArray[i].id == newId)
{
// override the existing metadata with the same id
_altMetaDataSetArray[i] = altMetaDataSet;
return;
}
}
// if we did not find metadata to override, add as new
_altMetaDataSetArray.Add(altMetaDataSet);
}
internal _SqlMetaDataSet GetAltMetaData(int id)
{
foreach (_SqlMetaDataSet altMetaDataSet in _altMetaDataSetArray)
{
if (altMetaDataSet.id == id)
{
return altMetaDataSet;
}
}
Debug.Assert(false, "Can't match up altMetaDataSet with given id");
return null;
}
public object Clone()
{
_SqlMetaDataSetCollection result = new _SqlMetaDataSetCollection();
result.metaDataSet = metaDataSet == null ? null : (_SqlMetaDataSet)metaDataSet.Clone();
foreach (_SqlMetaDataSet set in _altMetaDataSetArray)
{
result._altMetaDataSetArray.Add((_SqlMetaDataSet)set.Clone());
}
return result;
}
}
internal class SqlMetaDataPriv
{
internal SqlDbType type; // SqlDbType enum value
internal byte tdsType; // underlying tds type
internal byte precision = TdsEnums.UNKNOWN_PRECISION_SCALE; // give default of unknown (-1)
internal byte scale = TdsEnums.UNKNOWN_PRECISION_SCALE; // give default of unknown (-1)
internal int length;
internal SqlCollation collation;
internal int codePage;
internal Encoding encoding;
internal bool isNullable;
// Xml specific metadata
internal string xmlSchemaCollectionDatabase;
internal string xmlSchemaCollectionOwningSchema;
internal string xmlSchemaCollectionName;
internal MetaType metaType; // cached metaType
internal SqlMetaDataPriv()
{
}
internal virtual void CopyFrom(SqlMetaDataPriv original)
{
this.type = original.type;
this.tdsType = original.tdsType;
this.precision = original.precision;
this.scale = original.scale;
this.length = original.length;
this.collation = original.collation;
this.codePage = original.codePage;
this.encoding = original.encoding;
this.isNullable = original.isNullable;
this.xmlSchemaCollectionDatabase = original.xmlSchemaCollectionDatabase;
this.xmlSchemaCollectionOwningSchema = original.xmlSchemaCollectionOwningSchema;
this.xmlSchemaCollectionName = original.xmlSchemaCollectionName;
this.metaType = original.metaType;
}
}
sealed internal class _SqlRPC
{
internal string rpcName;
internal ushort ProcID; // Used instead of name
internal ushort options;
internal SqlParameter[] parameters;
internal byte[] paramoptions;
}
sealed internal class SqlReturnValue : SqlMetaDataPriv
{
internal string parameter;
internal readonly SqlBuffer value;
internal SqlReturnValue() : base()
{
value = new SqlBuffer();
}
}
internal struct MultiPartTableName
{
private string _multipartName;
private string _serverName;
private string _catalogName;
private string _schemaName;
private string _tableName;
internal MultiPartTableName(string[] parts)
{
_multipartName = null;
_serverName = parts[0];
_catalogName = parts[1];
_schemaName = parts[2];
_tableName = parts[3];
}
internal MultiPartTableName(string multipartName)
{
_multipartName = multipartName;
_serverName = null;
_catalogName = null;
_schemaName = null;
_tableName = null;
}
internal string ServerName
{
get
{
ParseMultipartName();
return _serverName;
}
set { _serverName = value; }
}
internal string CatalogName
{
get
{
ParseMultipartName();
return _catalogName;
}
set { _catalogName = value; }
}
internal string SchemaName
{
get
{
ParseMultipartName();
return _schemaName;
}
set { _schemaName = value; }
}
internal string TableName
{
get
{
ParseMultipartName();
return _tableName;
}
set { _tableName = value; }
}
private void ParseMultipartName()
{
if (null != _multipartName)
{
string[] parts = MultipartIdentifier.ParseMultipartIdentifier(_multipartName, "[\"", "]\"", Res.SQL_TDSParserTableName, false);
_serverName = parts[0];
_catalogName = parts[1];
_schemaName = parts[2];
_tableName = parts[3];
_multipartName = null;
}
}
internal static readonly MultiPartTableName Null = new MultiPartTableName(new string[] { null, null, null, null });
}
}
| |
using System;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using Duende.IdentityServer.Services;
using Duende.IdentityServer.Validation;
using IdentityExpress.Identity;
using IdentityExpress.Manager.Api.AccessTokenValidation;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Logging;
using Rsk.Samples.IdentityServer4.AdminUiIntegration.Demo;
using Rsk.Samples.IdentityServer4.AdminUiIntegration.Middleware;
using Rsk.Samples.IdentityServer4.AdminUiIntegration.Services;
namespace Rsk.Samples.IdentityServer4.AdminUiIntegration
{
public class Startup
{
public Startup(IWebHostEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", true, true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", true)
.AddEnvironmentVariables();
Configuration = builder.Build();
IsDemo = Configuration.GetValue("IsDemo", false);
}
public IConfigurationRoot Configuration { get; }
private bool IsDemo { get; }
public void ConfigureServices(IServiceCollection services)
{
//add memory cache for custom identity server event sink
//limit cache to preserving the last 10 error or failure identity server events
services.AddMemoryCache(options =>
{
options.SizeLimit = 10;
});
// configure databases
Action<DbContextOptionsBuilder> identityBuilder;
Action<DbContextOptionsBuilder> identityServerBuilder;
var identityConnectionString = Configuration.GetValue("IdentityConnectionString", Configuration.GetValue<string>("DbConnectionString"));
var identityServerConnectionString = Configuration.GetValue("IdentityServerConnectionString", Configuration.GetValue<string>("DbConnectionString"));
var migrationAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
switch (Configuration.GetValue<string>("DbProvider"))
{
case "SqlServer":
identityBuilder = x => x.UseSqlServer(identityConnectionString, options => options.MigrationsAssembly(migrationAssembly));
identityServerBuilder = x => x.UseSqlServer(identityServerConnectionString, options => options.MigrationsAssembly(migrationAssembly));
break;
case "MySql":
identityBuilder = x => x.UseMySql(identityConnectionString, new MySqlServerVersion(new Version(5, 6, 49)), options => options.MigrationsAssembly(migrationAssembly));
identityServerBuilder = x => x.UseMySql(identityServerConnectionString, new MySqlServerVersion(new Version(5, 6, 49)),options => options.MigrationsAssembly(migrationAssembly));
break;
case "PostgreSql":
identityBuilder = x => x.UseNpgsql(identityConnectionString, options => options.MigrationsAssembly(migrationAssembly));
identityServerBuilder = x => x.UseNpgsql(identityServerConnectionString, options => options.MigrationsAssembly(migrationAssembly));
break;
default:
identityBuilder = x => x.UseSqlite(identityConnectionString, options => options.MigrationsAssembly(migrationAssembly));
identityServerBuilder = x => x.UseSqlite(identityServerConnectionString, options => options.MigrationsAssembly(migrationAssembly));
break;
}
// configure test-suitable X-Forwarded headers and CORS policy
services.AddSingleton<XForwardedPrefixMiddleware>();
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost;
options.RequireHeaderSymmetry = false;
options.ForwardLimit = 10;
options.KnownNetworks.Clear();
options.KnownProxies.Clear();
});
services.AddCors(options =>
{
options.AddDefaultPolicy(builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
});
// configure ASP.NET Identity
services
.AddIdentityExpressAdminUiConfiguration(identityBuilder) // ASP.NET Core Identity Registrations for AdminUI
.AddDefaultTokenProviders()
.AddIdentityExpressUserClaimsPrincipalFactory(); // Claims Principal Factory for loading AdminUI users as .NET Identities
services.AddScoped<IUserStore<IdentityExpressUser>>(
x => new IdentityExpressUserStore(x.GetService<IdentityExpressDbContext>())
{
AutoSaveChanges = true
});
// configure IdentityServer
services.AddIdentityServer(options =>
{
options.KeyManagement.Enabled = false; // disabled to only use test cert
options.LicenseKey = null; // for development only
options.Events.RaiseErrorEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;
})
.AddOperationalStore(options => options.ConfigureDbContext = identityServerBuilder)
.AddConfigurationStore(options => options.ConfigureDbContext = identityServerBuilder)
.AddAspNetIdentity<IdentityExpressUser>() // configure IdentityServer to use ASP.NET Identity
.AddSigningCredential(GetEmbeddedCertificate()); // embedded test cert for testing only
// Demo services - DO NOT USE IN PRODUCTION
if (IsDemo)
{
services.AddTransient<ICorsPolicyService, DemoCorsPolicy>();
services.AddTransient<IRedirectUriValidator, DemoRedirectUriValidator>();
}
// configure the ASP.NET Identity cookie to work on HTTP for testing only
services.Configure<CookieAuthenticationOptions>(IdentityConstants.ApplicationScheme, options =>
{
options.Cookie.SameSite = SameSiteMode.Lax;
options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
options.Cookie.IsEssential = true;
});
// optional Google authentication
var googleClientId = Configuration.GetValue<string>("Google_ClientId");
var googleClientSecret = Configuration.GetValue<string>("Google_ClientSecret");
if (!string.IsNullOrWhiteSpace(googleClientId) && !string.IsNullOrWhiteSpace(googleClientSecret))
{
services
.AddAuthentication()
.AddGoogle(options =>
{
options.SignInScheme = "Identity.External"; // ASP.NET Core Identity Extneral User Cookie
options.ClientId = googleClientId; // ClientId Configured within Google Admin
options.ClientSecret = googleClientSecret; // ClientSecret Generated within Google Admin
});
}
services.AddMvc();
services.AddMvcCore().AddAuthorization();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "https://localhost:5001";
options.TokenValidationParameters.ValidTypes = new[] { "at+jwt" };
options.Audience = "admin_ui_webhooks";
// if token does not contain a dot, it is a reference token
options.ForwardDefaultSelector = Selector.ForwardReferenceToken("introspection");
})
.AddOAuth2Introspection("introspection", options =>
{
options.Authority = "https://localhost:5001";
options.ClientId = "admin_ui_webhooks";
options.ClientSecret = "adminUiWebhooksSecret";
});
services.AddAuthorization(options =>
{
options.AddPolicy("webhook", builder =>
{
builder.AddAuthenticationSchemes("Bearer");
builder.RequireScope("admin_ui_webhooks");
});
});
services.AddSingleton<IEventSink, CustomEventSink>();
services.AddSingleton<IEventStore, ErrorEventStore>();
}
public void Configure(IApplicationBuilder app)
{
app.UseDeveloperExceptionPage();
app.UseMiddleware<XForwardedPrefixMiddleware>();
app.UseForwardedHeaders();
app.UseStaticFiles();
app.UseRouting();
app.UseCors();
app.UseIdentityServer();
app.UseAuthorization();
app.UseEndpoints(endpoints => endpoints.MapDefaultControllerRoute());
}
private static X509Certificate2 GetEmbeddedCertificate()
{
try
{
using (var certStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(@"Rsk.Samples.IdentityServer4.AdminUiIntegration.CN=RSKSampleIdentityServer.pfx"))
{
var rawBytes = new byte[certStream.Length];
for (var index = 0; index < certStream.Length; index++)
{
rawBytes[index] = (byte)certStream.ReadByte();
}
return new X509Certificate2(rawBytes, "Password123!", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
}
}
catch (Exception)
{
return new X509Certificate2(AppDomain.CurrentDomain.BaseDirectory + "CN=RSKSampleIdentityServer.pfx", "Password123!");
}
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Javax.Security.Auth.cs
//
// 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.
#pragma warning disable 1717
namespace Javax.Security.Auth
{
/// <summary>
/// <para>Legacy security code; do not use. </para>
/// </summary>
/// <java-name>
/// javax/security/auth/PrivateCredentialPermission
/// </java-name>
[Dot42.DexImport("javax/security/auth/PrivateCredentialPermission", AccessFlags = 49)]
public sealed partial class PrivateCredentialPermission : global::Java.Security.Permission
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)]
public PrivateCredentialPermission(string name, string action) /* MethodBuilder.Create */
{
}
/// <java-name>
/// getPrincipals
/// </java-name>
[Dot42.DexImport("getPrincipals", "()[[Ljava/lang/String;", AccessFlags = 1)]
public string[][] GetPrincipals() /* MethodBuilder.Create */
{
return default(string[][]);
}
/// <java-name>
/// getActions
/// </java-name>
[Dot42.DexImport("getActions", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetActions() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getCredentialClass
/// </java-name>
[Dot42.DexImport("getCredentialClass", "()Ljava/lang/String;", AccessFlags = 1)]
public string GetCredentialClass() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// hashCode
/// </java-name>
[Dot42.DexImport("hashCode", "()I", AccessFlags = 1)]
public override int GetHashCode() /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// equals
/// </java-name>
[Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 1)]
public override bool Equals(object @object) /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// implies
/// </java-name>
[Dot42.DexImport("implies", "(Ljava/security/Permission;)Z", AccessFlags = 1)]
public override bool Implies(global::Java.Security.Permission permission) /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// newPermissionCollection
/// </java-name>
[Dot42.DexImport("newPermissionCollection", "()Ljava/security/PermissionCollection;", AccessFlags = 1)]
public override global::Java.Security.PermissionCollection NewPermissionCollection() /* MethodBuilder.Create */
{
return default(global::Java.Security.PermissionCollection);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal PrivateCredentialPermission() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <java-name>
/// getPrincipals
/// </java-name>
public string[][] Principals
{
[Dot42.DexImport("getPrincipals", "()[[Ljava/lang/String;", AccessFlags = 1)]
get{ return GetPrincipals(); }
}
/// <java-name>
/// getActions
/// </java-name>
public string Actions
{
[Dot42.DexImport("getActions", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetActions(); }
}
/// <java-name>
/// getCredentialClass
/// </java-name>
public string CredentialClass
{
[Dot42.DexImport("getCredentialClass", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetCredentialClass(); }
}
}
/// <summary>
/// <para>Allows for special treatment of sensitive information, when it comes to destroying or clearing of the data. </para>
/// </summary>
/// <java-name>
/// javax/security/auth/Destroyable
/// </java-name>
[Dot42.DexImport("javax/security/auth/Destroyable", AccessFlags = 1537)]
public partial interface IDestroyable
/* scope: __dot42__ */
{
/// <summary>
/// <para>Erases the sensitive information. Once an object is destroyed any calls to its methods will throw an <c> IllegalStateException </c> . If it does not succeed a DestroyFailedException is thrown.</para><para></para>
/// </summary>
/// <java-name>
/// destroy
/// </java-name>
[Dot42.DexImport("destroy", "()V", AccessFlags = 1025)]
void Destroy() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns <c> true </c> once an object has been safely destroyed.</para><para></para>
/// </summary>
/// <returns>
/// <para>whether the object has been safely destroyed. </para>
/// </returns>
/// <java-name>
/// isDestroyed
/// </java-name>
[Dot42.DexImport("isDestroyed", "()Z", AccessFlags = 1025)]
bool IsDestroyed() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>The central class of the <c> javax.security.auth </c> package representing an authenticated user or entity (both referred to as "subject"). IT defines also the static methods that allow code to be run, and do modifications according to the subject's permissions. </para><para>A subject has the following features: <ul><li><para>A set of <c> Principal </c> objects specifying the identities bound to a <c> Subject </c> that distinguish it. </para></li><li><para>Credentials (public and private) such as certificates, keys, or authentication proofs such as tickets </para></li></ul></para>
/// </summary>
/// <java-name>
/// javax/security/auth/Subject
/// </java-name>
[Dot42.DexImport("javax/security/auth/Subject", AccessFlags = 49)]
public sealed partial class Subject : global::Java.Io.ISerializable
/* scope: __dot42__ */
{
/// <summary>
/// <para>The default constructor initializing the sets of public and private credentials and principals with the empty set. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public Subject() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>The constructor for the subject, setting its public and private credentials and principals according to the arguments.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(ZLjava/util/Set;Ljava/util/Set;Ljava/util/Set;)V", AccessFlags = 1, Signature = "(ZLjava/util/Set<+Ljava/security/Principal;>;Ljava/util/Set<*>;Ljava/util/Set<*>;" +
")V")]
public Subject(bool readOnly, global::Java.Util.ISet<global::Java.Security.IPrincipal> subjPrincipals, global::Java.Util.ISet<object> pubCredentials, global::Java.Util.ISet<object> privCredentials) /* MethodBuilder.Create */
{
}
/// <java-name>
/// doAs
/// </java-name>
[Dot42.DexImport("doAs", "(Ljavax/security/auth/Subject;Ljava/security/PrivilegedAction;)Ljava/lang/Object;" +
"", AccessFlags = 9, Signature = "<T:Ljava/lang/Object;>(Ljavax/security/auth/Subject;Ljava/security/PrivilegedActi" +
"on<TT;>;)TT;")]
public static T DoAs<T>(global::Javax.Security.Auth.Subject subject, global::Java.Security.IPrivilegedAction<T> privilegedAction) /* MethodBuilder.Create */
{
return default(T);
}
/// <java-name>
/// doAsPrivileged
/// </java-name>
[Dot42.DexImport("doAsPrivileged", "(Ljavax/security/auth/Subject;Ljava/security/PrivilegedAction;Ljava/security/Acce" +
"ssControlContext;)Ljava/lang/Object;", AccessFlags = 9, Signature = "<T:Ljava/lang/Object;>(Ljavax/security/auth/Subject;Ljava/security/PrivilegedActi" +
"on<TT;>;Ljava/security/AccessControlContext;)TT;")]
public static T DoAsPrivileged<T>(global::Javax.Security.Auth.Subject subject, global::Java.Security.IPrivilegedAction<T> privilegedAction, global::Java.Security.AccessControlContext accessControlContext) /* MethodBuilder.Create */
{
return default(T);
}
/// <java-name>
/// doAs
/// </java-name>
[Dot42.DexImport("doAs", "(Ljavax/security/auth/Subject;Ljava/security/PrivilegedExceptionAction;)Ljava/lan" +
"g/Object;", AccessFlags = 9, Signature = "<T:Ljava/lang/Object;>(Ljavax/security/auth/Subject;Ljava/security/PrivilegedExce" +
"ptionAction<TT;>;)TT;")]
public static T DoAs<T>(global::Javax.Security.Auth.Subject subject, global::Java.Security.IPrivilegedExceptionAction<T> privilegedExceptionAction) /* MethodBuilder.Create */
{
return default(T);
}
/// <java-name>
/// doAsPrivileged
/// </java-name>
[Dot42.DexImport("doAsPrivileged", "(Ljavax/security/auth/Subject;Ljava/security/PrivilegedExceptionAction;Ljava/secu" +
"rity/AccessControlContext;)Ljava/lang/Object;", AccessFlags = 9, Signature = "<T:Ljava/lang/Object;>(Ljavax/security/auth/Subject;Ljava/security/PrivilegedExce" +
"ptionAction<TT;>;Ljava/security/AccessControlContext;)TT;")]
public static T DoAsPrivileged<T>(global::Javax.Security.Auth.Subject subject, global::Java.Security.IPrivilegedExceptionAction<T> privilegedExceptionAction, global::Java.Security.AccessControlContext accessControlContext) /* MethodBuilder.Create */
{
return default(T);
}
/// <summary>
/// <para>Checks two Subjects for equality. More specifically if the principals, public and private credentials are equal, equality for two <c> Subjects </c> is implied.</para><para></para>
/// </summary>
/// <returns>
/// <para><c> true </c> if the specified <c> Subject </c> is equal to this one. </para>
/// </returns>
/// <java-name>
/// equals
/// </java-name>
[Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 1)]
public override bool Equals(object obj) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Returns this <c> Subject </c> 's Principal.</para><para></para>
/// </summary>
/// <returns>
/// <para>this <c> Subject </c> 's Principal. </para>
/// </returns>
/// <java-name>
/// getPrincipals
/// </java-name>
[Dot42.DexImport("getPrincipals", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/security/Principal;>;")]
public global::Java.Util.ISet<global::Java.Security.IPrincipal> GetPrincipals() /* MethodBuilder.Create */
{
return default(global::Java.Util.ISet<global::Java.Security.IPrincipal>);
}
/// <summary>
/// <para>Returns this <c> Subject </c> 's Principal which is a subclass of the <c> Class </c> provided.</para><para></para>
/// </summary>
/// <returns>
/// <para>this <c> Subject </c> 's Principal. Modifications to the returned set of <c> Principal </c> s do not affect this <c> Subject </c> 's set. </para>
/// </returns>
/// <java-name>
/// getPrincipals
/// </java-name>
[Dot42.DexImport("getPrincipals", "(Ljava/lang/Class;)Ljava/util/Set;", AccessFlags = 1, Signature = "<T::Ljava/security/Principal;>(Ljava/lang/Class<TT;>;)Ljava/util/Set<TT;>;")]
public global::Java.Util.ISet<T> GetPrincipals<T>(global::System.Type c) /* MethodBuilder.Create */
{
return default(global::Java.Util.ISet<T>);
}
/// <summary>
/// <para>Returns the private credentials associated with this <c> Subject </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the private credentials associated with this <c> Subject </c> . </para>
/// </returns>
/// <java-name>
/// getPrivateCredentials
/// </java-name>
[Dot42.DexImport("getPrivateCredentials", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/lang/Object;>;")]
public global::Java.Util.ISet<object> GetPrivateCredentials() /* MethodBuilder.Create */
{
return default(global::Java.Util.ISet<object>);
}
/// <summary>
/// <para>Returns this <c> Subject </c> 's private credentials which are a subclass of the <c> Class </c> provided.</para><para></para>
/// </summary>
/// <returns>
/// <para>this <c> Subject </c> 's private credentials. Modifications to the returned set of credentials do not affect this <c> Subject </c> 's credentials. </para>
/// </returns>
/// <java-name>
/// getPrivateCredentials
/// </java-name>
[Dot42.DexImport("getPrivateCredentials", "(Ljava/lang/Class;)Ljava/util/Set;", AccessFlags = 1, Signature = "<T:Ljava/lang/Object;>(Ljava/lang/Class<TT;>;)Ljava/util/Set<TT;>;")]
public global::Java.Util.ISet<T> GetPrivateCredentials<T>(global::System.Type c) /* MethodBuilder.Create */
{
return default(global::Java.Util.ISet<T>);
}
/// <summary>
/// <para>Returns the public credentials associated with this <c> Subject </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the public credentials associated with this <c> Subject </c> . </para>
/// </returns>
/// <java-name>
/// getPublicCredentials
/// </java-name>
[Dot42.DexImport("getPublicCredentials", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/lang/Object;>;")]
public global::Java.Util.ISet<object> GetPublicCredentials() /* MethodBuilder.Create */
{
return default(global::Java.Util.ISet<object>);
}
/// <summary>
/// <para>Returns this <c> Subject </c> 's public credentials which are a subclass of the <c> Class </c> provided.</para><para></para>
/// </summary>
/// <returns>
/// <para>this <c> Subject </c> 's public credentials. Modifications to the returned set of credentials do not affect this <c> Subject </c> 's credentials. </para>
/// </returns>
/// <java-name>
/// getPublicCredentials
/// </java-name>
[Dot42.DexImport("getPublicCredentials", "(Ljava/lang/Class;)Ljava/util/Set;", AccessFlags = 1, Signature = "<T:Ljava/lang/Object;>(Ljava/lang/Class<TT;>;)Ljava/util/Set<TT;>;")]
public global::Java.Util.ISet<T> GetPublicCredentials<T>(global::System.Type c) /* MethodBuilder.Create */
{
return default(global::Java.Util.ISet<T>);
}
/// <summary>
/// <para>Returns a hash code of this <c> Subject </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>a hash code of this <c> Subject </c> . </para>
/// </returns>
/// <java-name>
/// hashCode
/// </java-name>
[Dot42.DexImport("hashCode", "()I", AccessFlags = 1)]
public override int GetHashCode() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Prevents from modifications being done to the credentials and Principal sets. After setting it to read-only this <c> Subject </c> can not be made writable again. The destroy method on the credentials still works though. </para>
/// </summary>
/// <java-name>
/// setReadOnly
/// </java-name>
[Dot42.DexImport("setReadOnly", "()V", AccessFlags = 1)]
public void SetReadOnly() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns whether this <c> Subject </c> is read-only or not.</para><para></para>
/// </summary>
/// <returns>
/// <para>whether this <c> Subject </c> is read-only or not. </para>
/// </returns>
/// <java-name>
/// isReadOnly
/// </java-name>
[Dot42.DexImport("isReadOnly", "()Z", AccessFlags = 1)]
public bool IsReadOnly() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Returns a <c> String </c> representation of this <c> Subject </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>a <c> String </c> representation of this <c> Subject </c> . </para>
/// </returns>
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the <c> Subject </c> that was last associated with the <c> context </c> provided as argument.</para><para></para>
/// </summary>
/// <returns>
/// <para>the <c> Subject </c> that was last associated with the <c> context </c> provided as argument. </para>
/// </returns>
/// <java-name>
/// getSubject
/// </java-name>
[Dot42.DexImport("getSubject", "(Ljava/security/AccessControlContext;)Ljavax/security/auth/Subject;", AccessFlags = 9)]
public static global::Javax.Security.Auth.Subject GetSubject(global::Java.Security.AccessControlContext context) /* MethodBuilder.Create */
{
return default(global::Javax.Security.Auth.Subject);
}
/// <summary>
/// <para>Returns this <c> Subject </c> 's Principal.</para><para></para>
/// </summary>
/// <returns>
/// <para>this <c> Subject </c> 's Principal. </para>
/// </returns>
/// <java-name>
/// getPrincipals
/// </java-name>
public global::Java.Util.ISet<global::Java.Security.IPrincipal> Principals
{
[Dot42.DexImport("getPrincipals", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/security/Principal;>;")]
get{ return GetPrincipals(); }
}
/// <summary>
/// <para>Returns the private credentials associated with this <c> Subject </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the private credentials associated with this <c> Subject </c> . </para>
/// </returns>
/// <java-name>
/// getPrivateCredentials
/// </java-name>
public global::Java.Util.ISet<object> PrivateCredentials
{
[Dot42.DexImport("getPrivateCredentials", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/lang/Object;>;")]
get{ return GetPrivateCredentials(); }
}
/// <summary>
/// <para>Returns the public credentials associated with this <c> Subject </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the public credentials associated with this <c> Subject </c> . </para>
/// </returns>
/// <java-name>
/// getPublicCredentials
/// </java-name>
public global::Java.Util.ISet<object> PublicCredentials
{
[Dot42.DexImport("getPublicCredentials", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/lang/Object;>;")]
get{ return GetPublicCredentials(); }
}
}
/// <summary>
/// <para>Legacy security code; do not use. </para>
/// </summary>
/// <java-name>
/// javax/security/auth/AuthPermission
/// </java-name>
[Dot42.DexImport("javax/security/auth/AuthPermission", AccessFlags = 49)]
public sealed partial class AuthPermission : global::Java.Security.BasicPermission
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public AuthPermission(string name) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)]
public AuthPermission(string name, string actions) /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal AuthPermission() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para>Legacy security code; do not use. </para>
/// </summary>
/// <java-name>
/// javax/security/auth/SubjectDomainCombiner
/// </java-name>
[Dot42.DexImport("javax/security/auth/SubjectDomainCombiner", AccessFlags = 33)]
public partial class SubjectDomainCombiner : global::Java.Security.IDomainCombiner
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Ljavax/security/auth/Subject;)V", AccessFlags = 1)]
public SubjectDomainCombiner(global::Javax.Security.Auth.Subject subject) /* MethodBuilder.Create */
{
}
/// <java-name>
/// getSubject
/// </java-name>
[Dot42.DexImport("getSubject", "()Ljavax/security/auth/Subject;", AccessFlags = 1)]
public virtual global::Javax.Security.Auth.Subject GetSubject() /* MethodBuilder.Create */
{
return default(global::Javax.Security.Auth.Subject);
}
/// <summary>
/// <para>Returns a combination of the two provided <c> ProtectionDomain </c> arrays. Implementers can simply merge the two arrays into one, remove duplicates and perform other optimizations.</para><para></para>
/// </summary>
/// <returns>
/// <para>a single <c> ProtectionDomain </c> array computed from the two provided arrays. </para>
/// </returns>
/// <java-name>
/// combine
/// </java-name>
[Dot42.DexImport("combine", "([Ljava/security/ProtectionDomain;[Ljava/security/ProtectionDomain;)[Ljava/securi" +
"ty/ProtectionDomain;", AccessFlags = 1)]
public virtual global::Java.Security.ProtectionDomain[] Combine(global::Java.Security.ProtectionDomain[] current, global::Java.Security.ProtectionDomain[] assigned) /* MethodBuilder.Create */
{
return default(global::Java.Security.ProtectionDomain[]);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal SubjectDomainCombiner() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <java-name>
/// getSubject
/// </java-name>
public global::Javax.Security.Auth.Subject Subject
{
[Dot42.DexImport("getSubject", "()Ljavax/security/auth/Subject;", AccessFlags = 1)]
get{ return GetSubject(); }
}
}
/// <summary>
/// <para>Signals that the Destroyable#destroy() method failed. </para>
/// </summary>
/// <java-name>
/// javax/security/auth/DestroyFailedException
/// </java-name>
[Dot42.DexImport("javax/security/auth/DestroyFailedException", AccessFlags = 33)]
public partial class DestroyFailedException : global::System.Exception
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates an exception of type <c> DestroyFailedException </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public DestroyFailedException() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates an exception of type <c> DestroyFailedException </c> .</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public DestroyFailedException(string message) /* MethodBuilder.Create */
{
}
}
}
| |
using System;
using System.Data;
using System.Data.Common;
using System.Text;
using BLToolkit.Common;
using BLToolkit.Mapping;
namespace BLToolkit.Data.DataProvider
{
#if FW3
using Sql.SqlProvider;
#endif
/// <summary>
/// The <b>DataProviderBase</b> is a class that provides specific data provider information
/// for the <see cref="DbManager"/> class.
/// </summary>
/// <remarks>
/// See the <see cref="DbManager.AddDataProvider(DataProviderBase)"/> method to find an example.
/// </remarks>
/// <seealso cref="DbManager.AddDataProvider(DataProviderBase)">AddDataManager Method</seealso>
public abstract class DataProviderBase
{
#region Abstract Properties
/// <summary>
/// Returns an actual type of the connection object used by this instance of the <see cref="DbManager"/>.
/// </summary>
/// <remarks>
/// See the <see cref="DbManager.AddDataProvider(DataProviderBase)"/> method to find an example.
/// </remarks>
/// <seealso cref="DbManager.AddDataProvider(DataProviderBase)">AddDataManager Method</seealso>
/// <value>An instance of the <see cref="Type"/> class.</value>
public abstract Type ConnectionType { get; }
/// <summary>
/// Returns the data manager name.
/// </summary>
/// <remarks>
/// See the <see cref="DbManager.AddDataProvider(DataProviderBase)"/> method to find an example.
/// </remarks>
/// <seealso cref="DbManager.AddDataProvider(DataProviderBase)">AddDataManager Method</seealso>
/// <value>The data manager name.</value>
public abstract string Name { get; }
private string _uniqueName;
/// <summary>
/// Same as <see cref="Name"/>, but may be overridden to add two or more providers of same type.
/// </summary>
public string UniqueName
{
get { return _uniqueName ?? Name; }
internal set { _uniqueName = value; }
}
#endregion
#region Abstract Methods
/// <summary>
/// Creates a new instance of the <see cref="IDbConnection"/>.
/// </summary>
/// <remarks>
/// See the <see cref="DbManager.AddDataProvider(DataProviderBase)"/> method to find an example.
/// </remarks>
/// <seealso cref="DbManager.AddDataProvider(DataProviderBase)">AddDataManager Method</seealso>
/// <returns>The <see cref="IDbConnection"/> object.</returns>
public abstract IDbConnection CreateConnectionObject();
/// <summary>
/// Creates a new connection object with same connection string.
/// </summary>
/// <param name="connection">A connection object used as prototype.</param>
/// <returns>New connection instance.</returns>
public virtual IDbConnection CloneConnection(IDbConnection connection)
{
if (connection == null)
throw new ArgumentNullException("connection");
ICloneable cloneable = connection as ICloneable;
if (cloneable != null)
return (IDbConnection)cloneable.Clone();
IDbConnection newConnection = CreateConnectionObject();
// This is definitelly not enought when PersistSecurityInfo set to false.
//
newConnection.ConnectionString = connection.ConnectionString;
return newConnection;
}
/// <summary>
/// Creates an instance of the <see cref="DbDataAdapter"/>.
/// </summary>
/// <remarks>
/// See the <see cref="DbManager.AddDataProvider(DataProviderBase)"/> method to find an example.
/// </remarks>
/// <seealso cref="DbManager.AddDataProvider(DataProviderBase)">AddDataManager Method</seealso>
/// <returns>The <see cref="DbDataAdapter"/> object.</returns>
public abstract DbDataAdapter CreateDataAdapterObject();
/// <summary>
/// Populates the specified <see cref="IDbCommand"/> object's Parameters collection with
/// parameter information for the stored procedure specified in the <see cref="IDbCommand"/>.
/// </summary>
/// <remarks>
/// See the <see cref="DbManager.AddDataProvider(DataProviderBase)"/> method to find an example.
/// </remarks>
/// <seealso cref="DbManager.AddDataProvider(DataProviderBase)">AddDataManager Method</seealso>
/// <param name="command">The <see cref="IDbCommand"/> referencing the stored procedure
/// for which the parameter information is to be derived.
/// The derived parameters will be populated into the Parameters of this command.</param>
/// <returns>true - parameters can be derive.</returns>
public abstract bool DeriveParameters(IDbCommand command);
#endregion
#region Factory methods
public virtual IDbCommand CreateCommandObject(IDbConnection connection)
{
return connection.CreateCommand();
}
public virtual IDbDataParameter CreateParameterObject(IDbCommand command)
{
return command.CreateParameter();
}
#endregion
#region IDbDataParameter methods
public virtual IDbDataParameter GetParameter(
IDbCommand command,
NameOrIndexParameter nameOrIndex)
{
return (IDbDataParameter)(nameOrIndex.ByName?
command.Parameters[nameOrIndex.Name]: command.Parameters[nameOrIndex.Index]);
}
public virtual void AttachParameter(
IDbCommand command,
IDbDataParameter parameter)
{
command.Parameters.Add(parameter);
}
public virtual void SetUserDefinedType(IDbDataParameter parameter, string typeName)
{
throw new NotSupportedException(Name + " data provider does not support UDT.");
}
public virtual bool IsValueParameter(IDbDataParameter parameter)
{
return parameter.Direction != ParameterDirection.ReturnValue;
}
public virtual IDbDataParameter CloneParameter(IDbDataParameter parameter)
{
return (IDbDataParameter)((ICloneable)parameter).Clone();
}
public virtual bool InitParameter(IDbDataParameter parameter)
{
return false;
}
#endregion
#region Virtual Members
public virtual object Convert(object value, ConvertType convertType)
{
return value;
}
public virtual void InitDbManager(DbManager dbManager)
{
MappingSchema schema = MappingSchema;
if (schema != null)
dbManager.MappingSchema = schema;
}
/// <summary>
/// One time initialization from a configuration file.
/// </summary>
/// <param name="attributes">Provider specific attributes.</param>
public virtual void Configure(System.Collections.Specialized.NameValueCollection attributes)
{
}
private MappingSchema _mappingSchema;
public virtual MappingSchema MappingSchema
{
get { return _mappingSchema; }
set { _mappingSchema = value; }
}
public virtual void PrepareCommand(ref CommandType commandType, ref string commandText, ref IDbDataParameter[] commandParameters)
{
#if FW3
/*
if (commandParameters != null) foreach (var p in commandParameters)
{
if (p.Value is System.Data.Linq.Binary)
{
var arr = ((System.Data.Linq.Binary)p.Value).ToArray();
p.Value = arr;
p.DbType = DbType.Binary;
p.Size = arr.Length;
}
}
*/
#endif
}
public virtual void SetParameterValue(IDbDataParameter parameter, object value)
{
#if FW3
if (value is System.Data.Linq.Binary)
{
var arr = ((System.Data.Linq.Binary)value).ToArray();
parameter.Value = arr;
parameter.DbType = DbType.Binary;
parameter.Size = arr.Length;
}
else
#endif
parameter.Value = value;
}
#if FW3
public virtual ISqlProvider CreateSqlProvider()
{
return new BasicSqlProvider(this);
}
#endif
public virtual IDataReader GetDataReader(MappingSchema schema, IDataReader dataReader)
{
return dataReader;
}
public virtual StringBuilder BuildTableName(StringBuilder sb, string database, string owner, string table)
{
if (database != null)
{
if (owner == null) sb.Append(database).Append("..");
else sb.Append(database).Append(".").Append(owner).Append(".");
}
else if (owner != null) sb.Append(owner).Append(".");
return sb.Append(table);
}
public virtual string ProviderName { get { return ConnectionType.Namespace; } }
public virtual int MaxParameters { get { return 100; } }
public virtual int MaxBatchSize { get { return 65536; } }
public virtual string EndOfSql { get { return ";"; } }
#endregion
#region DataReaderEx
protected class DataReaderBase<T> : IDataReader
where T: IDataReader
{
public readonly T DataReader;
protected DataReaderBase(T rd)
{
DataReader = rd;
}
#region Implementation of IDisposable
public void Dispose()
{
DataReader.Dispose();
}
#endregion
#region Implementation of IDataRecord
public string GetName (int i) { return DataReader.GetName (i); }
public string GetDataTypeName(int i) { return DataReader.GetDataTypeName(i); }
public Type GetFieldType (int i) { return DataReader.GetFieldType (i); }
public object GetValue (int i) { return DataReader.GetValue (i); }
public int GetValues (object[] values) { return DataReader.GetValues (values); }
public int GetOrdinal (string name) { return DataReader.GetOrdinal (name); }
public bool GetBoolean (int i) { return DataReader.GetBoolean (i); }
public byte GetByte (int i) { return DataReader.GetByte (i); }
public char GetChar (int i) { return DataReader.GetChar (i); }
public Guid GetGuid (int i) { return DataReader.GetGuid (i); }
public short GetInt16 (int i) { return DataReader.GetInt16 (i); }
public int GetInt32 (int i) { return DataReader.GetInt32 (i); }
public long GetInt64 (int i) { return DataReader.GetInt64 (i); }
public float GetFloat (int i) { return DataReader.GetFloat (i); }
public double GetDouble (int i) { return DataReader.GetDouble (i); }
public string GetString (int i) { return DataReader.GetString (i); }
public decimal GetDecimal (int i) { return DataReader.GetDecimal (i); }
public DateTime GetDateTime (int i) { return DataReader.GetDateTime (i); }
public IDataReader GetData (int i) { return DataReader.GetData (i); }
public bool IsDBNull (int i) { return DataReader.IsDBNull (i); }
public int FieldCount { get { return DataReader.FieldCount; } }
object IDataRecord.this[int i] { get { return DataReader[i]; } }
object IDataRecord.this[string name] { get { return DataReader[name]; } }
public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length)
{
return DataReader.GetBytes(i, fieldOffset, buffer, bufferoffset, length);
}
public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length)
{
return DataReader.GetChars(i, fieldoffset, buffer, bufferoffset, length);
}
#endregion
#region Implementation of IDataReader
public void Close () { DataReader.Close (); }
public DataTable GetSchemaTable() { return DataReader.GetSchemaTable(); }
public bool NextResult () { return DataReader.NextResult (); }
public bool Read () { return DataReader.Read (); }
public int Depth { get { return DataReader.Depth; } }
public bool IsClosed { get { return DataReader.IsClosed; } }
public int RecordsAffected { get { return DataReader.RecordsAffected; } }
#endregion
}
protected abstract class DataReaderEx<T> : DataReaderBase<T>, IDataReaderEx
where T: IDataReader
{
protected DataReaderEx(T rd) : base(rd)
{
}
#region Implementation of IDataReaderEx
#if FW3
public abstract DateTimeOffset GetDateTimeOffset(int i);
#endif
#endregion
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void MaxSingle()
{
var test = new SimpleBinaryOpTest__MaxSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__MaxSingle
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(Single);
private const int Op2ElementCount = VectorSize / sizeof(Single);
private const int RetElementCount = VectorSize / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector256<Single> _clsVar1;
private static Vector256<Single> _clsVar2;
private Vector256<Single> _fld1;
private Vector256<Single> _fld2;
private SimpleBinaryOpTest__DataTable<Single, Single, Single> _dataTable;
static SimpleBinaryOpTest__MaxSingle()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__MaxSingle()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); }
_dataTable = new SimpleBinaryOpTest__DataTable<Single, Single, Single>(_data1, _data2, new Single[RetElementCount], VectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx.Max(
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx.Max(
Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx.Max(
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx).GetMethod(nameof(Avx.Max), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx).GetMethod(nameof(Avx.Max), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx).GetMethod(nameof(Avx.Max), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx.Max(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr);
var result = Avx.Max(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr));
var result = Avx.Max(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr));
var result = Avx.Max(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__MaxSingle();
var result = Avx.Max(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx.Max(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Single> left, Vector256<Single> right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
if (BitConverter.SingleToInt32Bits(MathF.Max(left[0], right[0])) != BitConverter.SingleToInt32Bits(result[0]))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(MathF.Max(left[i], right[i])) != BitConverter.SingleToInt32Bits(result[i]))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.Max)}<Single>(Vector256<Single>, Vector256<Single>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.Versioning;
using NuGet.Resources;
namespace NuGet
{
public static class PackageRepositoryExtensions
{
public static IDisposable StartOperation(this IPackageRepository self, string operation, string mainPackageId, string mainPackageVersion)
{
IOperationAwareRepository repo = self as IOperationAwareRepository;
if (repo != null)
{
return repo.StartOperation(operation, mainPackageId, mainPackageVersion);
}
return DisposableAction.NoOp;
}
public static bool Exists(this IPackageRepository repository, IPackageName package)
{
return repository.Exists(package.Id, package.Version);
}
public static bool Exists(this IPackageRepository repository, string packageId)
{
return Exists(repository, packageId, version: null);
}
public static bool Exists(this IPackageRepository repository, string packageId, SemanticVersion version)
{
IPackageLookup packageLookup = repository as IPackageLookup;
if ((packageLookup != null) && !String.IsNullOrEmpty(packageId) && (version != null))
{
return packageLookup.Exists(packageId, version);
}
return repository.FindPackage(packageId, version) != null;
}
public static bool TryFindPackage(this IPackageRepository repository, string packageId, SemanticVersion version, out IPackage package)
{
package = repository.FindPackage(packageId, version);
return package != null;
}
public static IPackage FindPackage(this IPackageRepository repository, string packageId)
{
return repository.FindPackage(packageId, version: null);
}
public static IPackage FindPackage(this IPackageRepository repository, string packageId, SemanticVersion version)
{
// Default allow pre release versions to true here because the caller typically wants to find all packages in this scenario for e.g when checking if a
// a package is already installed in the local repository. The same applies to allowUnlisted.
return FindPackage(repository, packageId, version, NullConstraintProvider.Instance, allowPrereleaseVersions: true, allowUnlisted: true);
}
public static IPackage FindPackage(this IPackageRepository repository, string packageId, SemanticVersion version, bool allowPrereleaseVersions, bool allowUnlisted)
{
return FindPackage(repository, packageId, version, NullConstraintProvider.Instance, allowPrereleaseVersions, allowUnlisted);
}
public static IPackage FindPackage(
this IPackageRepository repository,
string packageId,
SemanticVersion version,
IPackageConstraintProvider constraintProvider,
bool allowPrereleaseVersions,
bool allowUnlisted)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
if (packageId == null)
{
throw new ArgumentNullException("packageId");
}
// if an explicit version is specified, disregard the 'allowUnlisted' argument
// and always allow unlisted packages.
if (version != null)
{
allowUnlisted = true;
}
else if (!allowUnlisted && (constraintProvider == null || constraintProvider == NullConstraintProvider.Instance))
{
var packageLatestLookup = repository as ILatestPackageLookup;
if (packageLatestLookup != null)
{
IPackage package;
if (packageLatestLookup.TryFindLatestPackageById(packageId, allowPrereleaseVersions, out package))
{
return package;
}
}
}
// If the repository implements it's own lookup then use that instead.
// This is an optimization that we use so we don't have to enumerate packages for
// sources that don't need to.
var packageLookup = repository as IPackageLookup;
if (packageLookup != null && version != null)
{
return packageLookup.FindPackage(packageId, version);
}
IEnumerable<IPackage> packages = repository.FindPackagesById(packageId);
packages = packages.ToList()
.OrderByDescending(p => p.Version);
if (!allowUnlisted)
{
packages = packages.Where(PackageExtensions.IsListed);
}
if (version != null)
{
packages = packages.Where(p => p.Version == version);
}
else if (constraintProvider != null)
{
packages = FilterPackagesByConstraints(constraintProvider, packages, packageId, allowPrereleaseVersions);
}
return packages.FirstOrDefault();
}
public static IPackage FindPackage(this IPackageRepository repository, string packageId, IVersionSpec versionSpec,
IPackageConstraintProvider constraintProvider, bool allowPrereleaseVersions, bool allowUnlisted)
{
var packages = repository.FindPackages(packageId, versionSpec, allowPrereleaseVersions, allowUnlisted);
if (constraintProvider != null)
{
packages = FilterPackagesByConstraints(constraintProvider, packages, packageId, allowPrereleaseVersions);
}
return packages.FirstOrDefault();
}
public static IEnumerable<IPackage> FindPackages(this IPackageRepository repository, IEnumerable<string> packageIds)
{
if (packageIds == null)
{
throw new ArgumentNullException("packageIds");
}
return FindPackages(repository, packageIds, GetFilterExpression);
}
public static IEnumerable<IPackage> FindPackagesById(this IPackageRepository repository, string packageId)
{
var serviceBasedRepository = repository as IPackageLookup;
if (serviceBasedRepository != null)
{
return serviceBasedRepository.FindPackagesById(packageId).ToList();
}
else
{
return FindPackagesByIdCore(repository, packageId);
}
}
internal static IEnumerable<IPackage> FindPackagesByIdCore(IPackageRepository repository, string packageId)
{
var cultureRepository = repository as ICultureAwareRepository;
if (cultureRepository != null)
{
packageId = packageId.ToLower(cultureRepository.Culture);
}
else
{
packageId = packageId.ToLower(CultureInfo.CurrentCulture);
}
return (from p in repository.GetPackages()
where p.Id.ToLower() == packageId
orderby p.Id
select p).ToList();
}
/// <summary>
/// Since Odata dies when our query for updates is too big. We query for updates 10 packages at a time
/// and return the full list of packages.
/// </summary>
private static IEnumerable<IPackage> FindPackages<T>(
this IPackageRepository repository,
IEnumerable<T> items,
Func<IEnumerable<T>, Expression<Func<IPackage, bool>>> filterSelector)
{
const int batchSize = 10;
while (items.Any())
{
IEnumerable<T> currentItems = items.Take(batchSize);
Expression<Func<IPackage, bool>> filterExpression = filterSelector(currentItems);
var query = repository.GetPackages()
.Where(filterExpression)
.OrderBy(p => p.Id);
foreach (var package in query)
{
yield return package;
}
items = items.Skip(batchSize);
}
}
public static IEnumerable<IPackage> FindPackages(
this IPackageRepository repository,
string packageId,
IVersionSpec versionSpec,
bool allowPrereleaseVersions,
bool allowUnlisted)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
if (packageId == null)
{
throw new ArgumentNullException("packageId");
}
IEnumerable<IPackage> packages = repository.FindPackagesById(packageId)
.OrderByDescending(p => p.Version);
if (!allowUnlisted)
{
packages = packages.Where(PackageExtensions.IsListed);
}
if (versionSpec != null)
{
packages = packages.FindByVersion(versionSpec);
}
packages = FilterPackagesByConstraints(NullConstraintProvider.Instance, packages, packageId, allowPrereleaseVersions);
return packages;
}
public static IPackage FindPackage(
this IPackageRepository repository,
string packageId,
IVersionSpec versionSpec,
bool allowPrereleaseVersions,
bool allowUnlisted)
{
return repository.FindPackages(packageId, versionSpec, allowPrereleaseVersions, allowUnlisted).FirstOrDefault();
}
public static IEnumerable<IPackage> FindCompatiblePackages(this IPackageRepository repository,
IPackageConstraintProvider constraintProvider,
IEnumerable<string> packageIds,
IPackage package,
FrameworkName targetFramework,
bool allowPrereleaseVersions)
{
return (from p in repository.FindPackages(packageIds)
where allowPrereleaseVersions || p.IsReleaseVersion()
let dependency = p.FindDependency(package.Id, targetFramework)
let otherConstaint = constraintProvider.GetConstraint(p.Id)
where dependency != null &&
dependency.VersionSpec.Satisfies(package.Version) &&
(otherConstaint == null || otherConstaint.Satisfies(package.Version))
select p);
}
public static PackageDependency FindDependency(this IPackageMetadata package, string packageId, FrameworkName targetFramework)
{
return (from dependency in package.GetCompatiblePackageDependencies(targetFramework)
where dependency.Id.Equals(packageId, StringComparison.OrdinalIgnoreCase)
select dependency).FirstOrDefault();
}
public static IQueryable<IPackage> Search(this IPackageRepository repository, string searchTerm, bool allowPrereleaseVersions)
{
return Search(repository, searchTerm, targetFrameworks: Enumerable.Empty<string>(), allowPrereleaseVersions: allowPrereleaseVersions);
}
public static IQueryable<IPackage> Search(this IPackageRepository repository, string searchTerm, IEnumerable<string> targetFrameworks, bool allowPrereleaseVersions)
{
if (targetFrameworks == null)
{
throw new ArgumentNullException("targetFrameworks");
}
var serviceBasedRepository = repository as IServiceBasedRepository;
if (serviceBasedRepository != null)
{
return serviceBasedRepository.Search(searchTerm, targetFrameworks, allowPrereleaseVersions);
}
// Ignore the target framework if the repository doesn't support searching
return repository.GetPackages().Find(searchTerm)
.FilterByPrerelease(allowPrereleaseVersions)
.AsQueryable();
}
public static IPackage ResolveDependency(this IPackageRepository repository, PackageDependency dependency, bool allowPrereleaseVersions, bool preferListedPackages)
{
return ResolveDependency(repository, dependency, constraintProvider: null, allowPrereleaseVersions: allowPrereleaseVersions, preferListedPackages: preferListedPackages);
}
public static IPackage ResolveDependency(this IPackageRepository repository, PackageDependency dependency, IPackageConstraintProvider constraintProvider, bool allowPrereleaseVersions, bool preferListedPackages)
{
IDependencyResolver dependencyResolver = repository as IDependencyResolver;
if (dependencyResolver != null)
{
return dependencyResolver.ResolveDependency(dependency, constraintProvider, allowPrereleaseVersions, preferListedPackages);
}
return ResolveDependencyCore(repository, dependency, constraintProvider, allowPrereleaseVersions, preferListedPackages);
}
internal static IPackage ResolveDependencyCore(
this IPackageRepository repository,
PackageDependency dependency,
IPackageConstraintProvider constraintProvider,
bool allowPrereleaseVersions,
bool preferListedPackages)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
if (dependency == null)
{
throw new ArgumentNullException("dependency");
}
IEnumerable<IPackage> packages = repository.FindPackagesById(dependency.Id).ToList();
// Always filter by constraints when looking for dependencies
packages = FilterPackagesByConstraints(constraintProvider, packages, dependency.Id, allowPrereleaseVersions);
IList<IPackage> candidates = packages.ToList();
if (preferListedPackages)
{
// pick among Listed packages first
IPackage listedSelectedPackage = ResolveDependencyCore(candidates.Where(PackageExtensions.IsListed),
dependency);
if (listedSelectedPackage != null)
{
return listedSelectedPackage;
}
}
return ResolveDependencyCore(candidates, dependency);
}
private static IPackage ResolveDependencyCore(IEnumerable<IPackage> packages, PackageDependency dependency)
{
// If version info was specified then use it
if (dependency.VersionSpec != null)
{
packages = packages.FindByVersion(dependency.VersionSpec);
return packages.ResolveSafeVersion();
}
else
{
// BUG 840: If no version info was specified then pick the latest
return packages.OrderByDescending(p => p.Version)
.FirstOrDefault();
}
}
/// <summary>
/// Returns updates for packages from the repository
/// </summary>
/// <param name="repository">The repository to search for updates</param>
/// <param name="packages">Packages to look for updates</param>
/// <param name="includePrerelease">Indicates whether to consider prerelease updates.</param>
/// <param name="includeAllVersions">Indicates whether to include all versions of an update as opposed to only including the latest version.</param>
public static IEnumerable<IPackage> GetUpdates(
this IPackageRepository repository,
IEnumerable<IPackageName> packages,
bool includePrerelease,
bool includeAllVersions,
IEnumerable<FrameworkName> targetFrameworks = null,
IEnumerable<IVersionSpec> versionConstraints = null)
{
if (packages.IsEmpty())
{
return Enumerable.Empty<IPackage>();
}
var serviceBasedRepository = repository as IServiceBasedRepository;
return serviceBasedRepository != null ? serviceBasedRepository.GetUpdates(packages, includePrerelease, includeAllVersions, targetFrameworks, versionConstraints) :
repository.GetUpdatesCore(packages, includePrerelease, includeAllVersions, targetFrameworks, versionConstraints);
}
public static IEnumerable<IPackage> GetUpdatesCore(
this IPackageRepository repository,
IEnumerable<IPackageName> packages,
bool includePrerelease,
bool includeAllVersions,
IEnumerable<FrameworkName> targetFramework,
IEnumerable<IVersionSpec> versionConstraints)
{
List<IPackageName> packageList = packages.ToList();
if (!packageList.Any())
{
return Enumerable.Empty<IPackage>();
}
IList<IVersionSpec> versionConstraintList;
if (versionConstraints == null)
{
versionConstraintList = new IVersionSpec[packageList.Count];
}
else
{
versionConstraintList = versionConstraints.ToList();
}
if (packageList.Count != versionConstraintList.Count)
{
throw new ArgumentException(NuGetResources.GetUpdatesParameterMismatch);
}
// These are the packages that we need to look at for potential updates.
ILookup<string, IPackage> sourcePackages = GetUpdateCandidates(repository, packageList, includePrerelease)
.ToList()
.ToLookup(package => package.Id, StringComparer.OrdinalIgnoreCase);
var results = new List<IPackage>();
for (int i = 0; i < packageList.Count; i++)
{
var package = packageList[i];
var constraint = versionConstraintList[i];
var updates = from candidate in sourcePackages[package.Id]
where (candidate.Version > package.Version) &&
SupportsTargetFrameworks(targetFramework, candidate) &&
(constraint == null || constraint.Satisfies(candidate.Version))
select candidate;
results.AddRange(updates);
}
if (!includeAllVersions)
{
return results.CollapseById();
}
return results;
}
private static bool SupportsTargetFrameworks(IEnumerable<FrameworkName> targetFramework, IPackage package)
{
return targetFramework.IsEmpty() || targetFramework.Any(t => VersionUtility.IsCompatible(t, package.GetSupportedFrameworks()));
}
public static IPackageRepository Clone(this IPackageRepository repository)
{
var cloneableRepository = repository as ICloneableRepository;
if (cloneableRepository != null)
{
return cloneableRepository.Clone();
}
return repository;
}
/// <summary>
/// Since odata dies when our query for updates is too big. We query for updates 10 packages at a time
/// and return the full list of candidates for updates.
/// </summary>
private static IEnumerable<IPackage> GetUpdateCandidates(
IPackageRepository repository,
IEnumerable<IPackageName> packages,
bool includePrerelease)
{
var query = FindPackages(repository, packages, GetFilterExpression);
if (!includePrerelease)
{
query = query.Where(p => p.IsReleaseVersion());
}
// for updates, we never consider unlisted packages
query = query.Where(PackageExtensions.IsListed);
return query;
}
/// <summary>
/// For the list of input packages generate an expression like:
/// p => p.Id == 'package1id' or p.Id == 'package2id' or p.Id == 'package3id'... up to package n
/// </summary>
private static Expression<Func<IPackage, bool>> GetFilterExpression(IEnumerable<IPackageName> packages)
{
return GetFilterExpression(packages.Select(p => p.Id));
}
[SuppressMessage("Microsoft.Globalization", "CA1304:SpecifyCultureInfo", MessageId = "System.String.ToLower", Justification = "This is for a linq query")]
private static Expression<Func<IPackage, bool>> GetFilterExpression(IEnumerable<string> ids)
{
ParameterExpression parameterExpression = Expression.Parameter(typeof(IPackageName));
Expression expressionBody = ids.Select(id => GetCompareExpression(parameterExpression, id.ToLower()))
.Aggregate(Expression.OrElse);
return Expression.Lambda<Func<IPackage, bool>>(expressionBody, parameterExpression);
}
/// <summary>
/// Builds the expression: package.Id.ToLower() == "somepackageid"
/// </summary>
private static Expression GetCompareExpression(Expression parameterExpression, object value)
{
// package.Id
Expression propertyExpression = Expression.Property(parameterExpression, "Id");
// .ToLower()
Expression toLowerExpression = Expression.Call(propertyExpression, typeof(string).GetMethod("ToLower", Type.EmptyTypes));
// == localPackage.Id
return Expression.Equal(toLowerExpression, Expression.Constant(value));
}
private static IEnumerable<IPackage> FilterPackagesByConstraints(
IPackageConstraintProvider constraintProvider,
IEnumerable<IPackage> packages,
string packageId,
bool allowPrereleaseVersions)
{
constraintProvider = constraintProvider ?? NullConstraintProvider.Instance;
// Filter packages by this constraint
IVersionSpec constraint = constraintProvider.GetConstraint(packageId);
if (constraint != null)
{
packages = packages.FindByVersion(constraint);
}
if (!allowPrereleaseVersions)
{
packages = packages.Where(p => p.IsReleaseVersion());
}
return packages;
}
internal static IPackage ResolveSafeVersion(this IEnumerable<IPackage> packages)
{
// Return null if there's no packages
if (packages == null || !packages.Any())
{
return null;
}
// We want to take the biggest build and revision number for the smallest
// major and minor combination (we want to make some versioning assumptions that the 3rd number is a non-breaking bug fix). This is so that we get the closest version
// to the dependency, but also get bug fixes without requiring people to manually update the nuspec.
// For example, if A -> B 1.0.0 and the feed has B 1.0.0 and B 1.0.1 then the more correct choice is B 1.0.1.
// If we don't do this, A will always end up getting the 'buggy' 1.0.0,
// unless someone explicitly changes it to ask for 1.0.1, which is very painful if many packages are using B 1.0.0.
var groups = from p in packages
group p by new { p.Version.Version.Major, p.Version.Version.Minor } into g
orderby g.Key.Major, g.Key.Minor
select g;
return (from p in groups.First()
orderby p.Version descending
select p).FirstOrDefault();
}
}
}
| |
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Util.Caching
{
using System;
using System.Runtime.Caching;
using System.Threading;
using System.Threading.Tasks;
public class LazyMemoryCache<TKey, TValue> :
IDisposable
where TValue : class
{
/// <summary>
/// Formats a key as a string
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public delegate string KeyFormatter(TKey key);
/// <summary>
/// Provides the policy for the cache item
/// </summary>
/// <param name="selector"></param>
/// <returns></returns>
public delegate ICacheExpiration PolicyProvider(ICacheExpirationSelector selector);
/// <summary>
/// Returns the value for a key
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public delegate Task<TValue> ValueFactory(TKey key);
/// <summary>
/// The callback when an item is removed from the cache
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="reason"></param>
/// <returns></returns>
public delegate Task ValueRemoved(string key, TValue value, string reason);
readonly MemoryCache _cache;
readonly KeyFormatter _keyFormatter;
readonly PolicyProvider _policyProvider;
readonly LimitedConcurrencyLevelTaskScheduler _scheduler;
readonly ValueFactory _valueFactory;
readonly ValueRemoved _valueRemoved;
public LazyMemoryCache(string name, ValueFactory valueFactory, PolicyProvider policyProvider = null, KeyFormatter keyFormatter = null,
ValueRemoved valueRemoved = null)
{
_valueFactory = valueFactory;
_policyProvider = policyProvider ?? DefaultPolicyProvider;
_keyFormatter = keyFormatter ?? DefaultKeyFormatter;
_valueRemoved = valueRemoved ?? DefaultValueRemoved;
_cache = new MemoryCache(name);
_scheduler = new LimitedConcurrencyLevelTaskScheduler(1);
}
public void Dispose()
{
Task.Factory.StartNew(() => _cache.Dispose(), CancellationToken.None, TaskCreationOptions.HideScheduler, _scheduler);
}
Task DefaultValueRemoved(string key, TValue value, string reason)
{
return TaskUtil.Completed;
}
static string DefaultKeyFormatter(TKey key)
{
return key.ToString();
}
static ICacheExpiration DefaultPolicyProvider(ICacheExpirationSelector selector)
{
return selector.None();
}
void Touch(string textKey)
{
Task.Factory.StartNew(() => _cache.Get(textKey), CancellationToken.None, TaskCreationOptions.HideScheduler, _scheduler);
}
public Task<Cached<TValue>> Get(TKey key)
{
return Task.Factory.StartNew(() =>
{
var textKey = _keyFormatter(key);
var result = _cache.Get(textKey) as Cached<TValue>;
if (result != null)
{
if (!result.Value.IsFaulted && !result.Value.IsCanceled)
return result;
_cache.Remove(textKey);
}
var cacheItemValue = new CachedValue(_valueFactory, key, () => Touch(textKey));
var cacheItem = new CacheItem(textKey, cacheItemValue);
var cacheItemPolicy = _policyProvider(new CacheExpirationSelector(key)).Policy;
cacheItemPolicy.RemovedCallback = OnCacheItemRemoved;
var added = _cache.Add(cacheItem, cacheItemPolicy);
if (!added)
{
throw new InvalidOperationException($"The item was not added to the cache: {key}");
}
return cacheItemValue;
}, CancellationToken.None, TaskCreationOptions.HideScheduler, _scheduler);
}
void OnCacheItemRemoved(CacheEntryRemovedArguments arguments)
{
var existingItem = arguments.CacheItem.Value as CachedValue;
if (existingItem?.IsValueCreated ?? false)
{
CleanupCacheItem(existingItem.Value, arguments.CacheItem.Key, arguments.RemovedReason);
}
}
async void CleanupCacheItem(Task<TValue> valueTask, string textKey, CacheEntryRemovedReason reason)
{
var value = await valueTask.ConfigureAwait(false);
await _valueRemoved(textKey, value, reason.ToString()).ConfigureAwait(false);
var disposable = value as IDisposable;
disposable?.Dispose();
var asyncDisposable = value as IAsyncDisposable;
if (asyncDisposable != null)
await asyncDisposable.DisposeAsync().ConfigureAwait(false);
}
class CachedValue :
Cached<TValue>
{
readonly Action _touch;
readonly Lazy<Task<TValue>> _value;
public CachedValue(ValueFactory valueFactory, TKey key, Action touch)
{
_touch = touch;
_value = new Lazy<Task<TValue>>(() => valueFactory(key), LazyThreadSafetyMode.PublicationOnly);
}
public bool IsValueCreated => _value.IsValueCreated;
public Task<TValue> Value => _value.Value;
public void Touch()
{
_touch();
}
}
public interface ICacheExpiration
{
CacheItemPolicy Policy { get; }
}
public interface ICacheExpirationSelector
{
/// <summary>
/// The key for the cache item
/// </summary>
TKey Key { get; }
/// <summary>
/// The cache item should expire after being usused for the specified time period
/// </summary>
/// <param name="expiration"></param>
/// <returns></returns>
ICacheExpiration SlidingWindow(TimeSpan expiration);
/// <summary>
/// The cache item should expire after a set time period
/// </summary>
/// <param name="expiration"></param>
/// <returns></returns>
ICacheExpiration Absolute(DateTimeOffset expiration);
/// <summary>
/// The cache item should never expire
/// </summary>
/// <returns></returns>
ICacheExpiration None();
}
class CacheExpirationSelector :
ICacheExpirationSelector
{
public CacheExpirationSelector(TKey key)
{
Key = key;
}
public TKey Key { get; }
public ICacheExpiration SlidingWindow(TimeSpan expiration)
{
return new CacheExpiration(new CacheItemPolicy
{
SlidingExpiration = expiration
});
}
public ICacheExpiration Absolute(DateTimeOffset expiration)
{
return new CacheExpiration(new CacheItemPolicy
{
AbsoluteExpiration = expiration
});
}
public ICacheExpiration None()
{
return new CacheExpiration(new CacheItemPolicy());
}
class CacheExpiration :
ICacheExpiration
{
public CacheExpiration(CacheItemPolicy policy)
{
Policy = policy;
}
public CacheItemPolicy Policy { get; }
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics.Tracing;
using Xunit;
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
using Microsoft.Diagnostics.Tracing.Session;
#endif
using System.Diagnostics;
namespace BasicEventSourceTests
{
internal enum Color { Red, Blue, Green };
internal enum ColorUInt32 : uint { Red, Blue, Green };
internal enum ColorByte : byte { Red, Blue, Green };
internal enum ColorSByte : sbyte { Red, Blue, Green };
internal enum ColorInt16 : short { Red, Blue, Green };
internal enum ColorUInt16 : ushort { Red, Blue, Green };
internal enum ColorInt64 : long { Red, Blue, Green };
internal enum ColorUInt64 : ulong { Red, Blue, Green };
public class TestsWrite
{
[EventData]
private struct PartB_UserInfo
{
public string UserName { get; set; }
}
/// <summary>
/// Tests the EventSource.Write[T] method (can only use the self-describing mechanism).
/// Tests the EventListener code path
/// </summary>
[ActiveIssue(4871, PlatformID.AnyUnix)]
[Fact]
public void Test_Write_T_EventListener()
{
Test_Write_T(new EventListenerListener());
}
/// <summary>
/// Tests the EventSource.Write[T] method (can only use the self-describing mechanism).
/// Tests the EventListener code path using events instead of virtual callbacks.
/// </summary>
[ActiveIssue(4871, PlatformID.AnyUnix)]
[Fact]
public void Test_Write_T_EventListener_UseEvents()
{
Test_Write_T(new EventListenerListener(true));
}
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
/// <summary>
/// Tests the EventSource.Write[T] method (can only use the self-describing mechanism).
/// Tests the ETW code path
/// </summary>
[Fact]
public void Test_Write_T_ETW()
{
Test_Write_T(new EtwListener());
}
#endif //USE_ETW
/// <summary>
/// Te
/// </summary>
/// <param name="listener"></param>
private void Test_Write_T(Listener listener)
{
TestUtilities.CheckNoEventSourcesRunning("Start");
using (var logger = new EventSource("EventSourceName"))
{
var tests = new List<SubTest>();
/*************************************************************************/
tests.Add(new SubTest("Write/Basic/String",
delegate ()
{
logger.Write("Greeting", new { msg = "Hello, world!" });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("Greeting", evt.EventName);
Assert.Equal(evt.PayloadValue(0, "msg"), "Hello, world!");
}));
/*************************************************************************/
decimal myMoney = 300;
tests.Add(new SubTest("Write/Basic/decimal",
delegate ()
{
logger.Write("Decimal", new { money = myMoney });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("Decimal", evt.EventName);
var eventMoney = evt.PayloadValue(0, "money");
// TOD FIX ME - Fix TraceEvent to return decimal instead of double.
//Assert.Equal((decimal)eventMoney, (decimal)300);
}));
/*************************************************************************/
DateTime now = DateTime.Now;
tests.Add(new SubTest("Write/Basic/DateTime",
delegate ()
{
logger.Write("DateTime", new { nowTime = now });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("DateTime", evt.EventName);
var eventNow = evt.PayloadValue(0, "nowTime");
Assert.Equal(eventNow, now);
}));
/*************************************************************************/
byte[] byteArray = { 0, 1, 2, 3 };
tests.Add(new SubTest("Write/Basic/byte[]",
delegate ()
{
logger.Write("Bytes", new { bytes = byteArray });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("Bytes", evt.EventName);
var eventArray = evt.PayloadValue(0, "bytes");
Array.Equals(eventArray, byteArray);
}));
/*************************************************************************/
tests.Add(new SubTest("Write/Basic/PartBOnly",
delegate ()
{
// log just a PartB
logger.Write("UserInfo", new EventSourceOptions { Keywords = EventKeywords.None },
new { _1 = new PartB_UserInfo { UserName = "Someone Else" } });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("UserInfo", evt.EventName);
var structValue = evt.PayloadValue(0, "PartB_UserInfo");
var structValueAsDictionary = structValue as IDictionary<string, object>;
Assert.NotNull(structValueAsDictionary);
Assert.Equal(structValueAsDictionary["UserName"], "Someone Else");
}));
/*************************************************************************/
tests.Add(new SubTest("Write/Basic/PartBAndC",
delegate ()
{
// log a PartB and a PartC
logger.Write("Duration", new EventSourceOptions { Keywords = EventKeywords.None },
new { _1 = new PartB_UserInfo { UserName = "Myself" }, msec = 10 });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("Duration", evt.EventName);
var structValue = evt.PayloadValue(0, "PartB_UserInfo");
var structValueAsDictionary = structValue as IDictionary<string, object>;
Assert.NotNull(structValueAsDictionary);
Assert.Equal(structValueAsDictionary["UserName"], "Myself");
Assert.Equal(evt.PayloadValue(1, "msec"), 10);
}));
/*************************************************************************/
/*************************** ENUM TESTING *******************************/
/*************************************************************************/
/*************************************************************************/
GenerateEnumTest<Color>(ref tests, logger, Color.Green);
GenerateEnumTest<ColorUInt32>(ref tests, logger, ColorUInt32.Green);
GenerateEnumTest<ColorByte>(ref tests, logger, ColorByte.Green);
GenerateEnumTest<ColorSByte>(ref tests, logger, ColorSByte.Green);
GenerateEnumTest<ColorInt16>(ref tests, logger, ColorInt16.Green);
GenerateEnumTest<ColorUInt16>(ref tests, logger, ColorUInt16.Green);
GenerateEnumTest<ColorInt64>(ref tests, logger, ColorInt64.Green);
GenerateEnumTest<ColorUInt64>(ref tests, logger, ColorUInt64.Green);
/*************************************************************************/
/*************************** ARRAY TESTING *******************************/
/*************************************************************************/
/*************************************************************************/
GenerateArrayTest<Boolean>(ref tests, logger, new Boolean[] { false, true, false });
GenerateArrayTest<byte>(ref tests, logger, new byte[] { 1, 10, 100 });
GenerateArrayTest<sbyte>(ref tests, logger, new sbyte[] { 1, 10, 100 });
GenerateArrayTest<Int16>(ref tests, logger, new Int16[] { 1, 10, 100 });
GenerateArrayTest<UInt16>(ref tests, logger, new UInt16[] { 1, 10, 100 });
GenerateArrayTest<Int32>(ref tests, logger, new Int32[] { 1, 10, 100 });
GenerateArrayTest<UInt32>(ref tests, logger, new UInt32[] { 1, 10, 100 });
GenerateArrayTest<Int64>(ref tests, logger, new Int64[] { 1, 10, 100 });
GenerateArrayTest<UInt64>(ref tests, logger, new UInt64[] { 1, 10, 100 });
GenerateArrayTest<Char>(ref tests, logger, new Char[] { 'a', 'c', 'b' });
GenerateArrayTest<Double>(ref tests, logger, new Double[] { 1, 10, 100 });
GenerateArrayTest<Single>(ref tests, logger, new Single[] { 1, 10, 100 });
GenerateArrayTest<IntPtr>(ref tests, logger, new IntPtr[] { (IntPtr)1, (IntPtr)10, (IntPtr)100 });
GenerateArrayTest<UIntPtr>(ref tests, logger, new UIntPtr[] { (UIntPtr)1, (UIntPtr)10, (UIntPtr)100 });
GenerateArrayTest<Guid>(ref tests, logger, new Guid[] { Guid.Empty, new Guid("121a11ee-3bcb-49cc-b425-f4906fb14f72") });
/*************************************************************************/
/*********************** DICTIONARY TESTING ******************************/
/*************************************************************************/
var dict = new Dictionary<string, string>() { { "elem1", "10" }, { "elem2", "20" } };
var dictInt = new Dictionary<string, int>() { { "elem1", 10 }, { "elem2", 20 } };
/*************************************************************************/
#if false // TODO: enable when dictionary events are working again. GitHub issue #4867.
tests.Add(new SubTest("Write/Dict/EventWithStringDict_C",
delegate()
{
// log a dictionary
logger.Write("EventWithStringDict_C", new {
myDict = dict,
s = "end" });
},
delegate(Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EventWithStringDict_C", evt.EventName);
var keyValues = evt.PayloadValue(0, "myDict");
IDictionary<string, object> vDict = GetDictionaryFromKeyValueArray(keyValues);
Assert.Equal(vDict["elem1"], "10");
Assert.Equal(vDict["elem2"], "20");
Assert.Equal(evt.PayloadValue(1, "s"), "end");
}));
/*************************************************************************/
tests.Add(new SubTest("Write/Dict/EventWithStringDict_BC",
delegate()
{
// log a PartB and a dictionary as a PartC
logger.Write("EventWithStringDict_BC", new {
PartB_UserInfo = new { UserName = "Me", LogTime = "Now" },
PartC_Dict = dict,
s = "end" });
},
delegate(Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EventWithStringDict_BC", evt.EventName);
var structValue = evt.PayloadValue(0, "PartB_UserInfo");
var structValueAsDictionary = structValue as IDictionary<string, object>;
Assert.NotNull(structValueAsDictionary);
Assert.Equal(structValueAsDictionary["UserName"], "Me");
Assert.Equal(structValueAsDictionary["LogTime"], "Now");
var keyValues = evt.PayloadValue(1, "PartC_Dict");
var vDict = GetDictionaryFromKeyValueArray(keyValues);
Assert.NotNull(dict);
Assert.Equal(vDict["elem1"], "10"); // string values.
Assert.Equal(vDict["elem2"], "20");
Assert.Equal(evt.PayloadValue(2, "s"), "end");
}));
/*************************************************************************/
tests.Add(new SubTest("Write/Dict/EventWithIntDict_BC",
delegate()
{
// log a Dict<string, int> as a PartC
logger.Write("EventWithIntDict_BC", new {
PartB_UserInfo = new { UserName = "Me", LogTime = "Now" },
PartC_Dict = dictInt,
s = "end" });
},
delegate(Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EventWithIntDict_BC", evt.EventName);
var structValue = evt.PayloadValue(0, "PartB_UserInfo");
var structValueAsDictionary = structValue as IDictionary<string, object>;
Assert.NotNull(structValueAsDictionary);
Assert.Equal(structValueAsDictionary["UserName"], "Me");
Assert.Equal(structValueAsDictionary["LogTime"], "Now");
var keyValues = evt.PayloadValue(1, "PartC_Dict");
var vDict = GetDictionaryFromKeyValueArray(keyValues);
Assert.NotNull(vDict);
Assert.Equal(vDict["elem1"], 10); // Notice they are integers, not strings.
Assert.Equal(vDict["elem2"], 20);
Assert.Equal(evt.PayloadValue(2, "s"), "end");
}));
#endif // false
/*************************************************************************/
/**************************** Empty Event TESTING ************************/
/*************************************************************************/
tests.Add(new SubTest("Write/Basic/Message",
delegate ()
{
logger.Write("EmptyEvent");
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EmptyEvent", evt.EventName);
}));
/*************************************************************************/
/**************************** EventSourceOptions TESTING *****************/
/*************************************************************************/
EventSourceOptions options = new EventSourceOptions();
options.Level = EventLevel.LogAlways;
options.Keywords = EventKeywords.All;
options.Opcode = EventOpcode.Info;
options.Tags = EventTags.None;
tests.Add(new SubTest("Write/Basic/MessageOptions",
delegate ()
{
logger.Write("EmptyEvent", options);
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EmptyEvent", evt.EventName);
}));
tests.Add(new SubTest("Write/Basic/WriteOfTWithOptios",
delegate ()
{
logger.Write("OptionsEvent", options, new { OptionsEvent = "test options!" });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("OptionsEvent", evt.EventName);
Assert.Equal(evt.PayloadValue(0, "OptionsEvent"), "test options!");
}));
tests.Add(new SubTest("Write/Basic/WriteOfTWithRefOptios",
delegate ()
{
var v = new { OptionsEvent = "test ref options!" };
logger.Write("RefOptionsEvent", ref options, ref v);
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("RefOptionsEvent", evt.EventName);
Assert.Equal(evt.PayloadValue(0, "OptionsEvent"), "test ref options!");
}));
tests.Add(new SubTest("Write/Basic/WriteOfTWithNullString",
delegate ()
{
string nullString = null;
logger.Write("NullStringEvent", new { a = (string)null, b = nullString });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("NullStringEvent", evt.EventName);
Assert.Equal(evt.PayloadValue(0, "a"), "");
Assert.Equal(evt.PayloadValue(1, "b"), "");
}));
Guid activityId = new Guid("00000000-0000-0000-0000-000000000001");
Guid relActivityId = new Guid("00000000-0000-0000-0000-000000000002");
tests.Add(new SubTest("Write/Basic/WriteOfTWithOptios",
delegate ()
{
var v = new { ActivityMsg = "test activity!" };
logger.Write("ActivityEvent", ref options, ref activityId, ref relActivityId, ref v);
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("ActivityEvent", evt.EventName);
Assert.Equal(evt.PayloadValue(0, "ActivityMsg"), "test activity!");
}));
// If you only wish to run one or several of the tests you can filter them here by
// Uncommenting the following line.
// tests = tests.FindAll(test => Regex.IsMatch(test.Name, "Write/Basic/EventII"));
// Here is where we actually run tests. First test the ETW path
EventTestHarness.RunTests(tests, listener, logger);
}
TestUtilities.CheckNoEventSourcesRunning("Stop");
}
/// <summary>
/// This is not a user error but it is something unusual.
/// You can use the Write API in a EventSource that was did not
/// Declare SelfDescribingSerialization. In that case THOSE
/// events MUST use SelfDescribing serialization.
/// </summary>
[ActiveIssue(4871, PlatformID.AnyUnix)]
[Fact]
public void Test_Write_T_In_Manifest_Serialization()
{
var listenerGenerators = new Func<Listener>[]
{
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
() => new EtwListener(),
#endif // USE_ETW
() => new EventListenerListener()
};
foreach (Func<Listener> listenerGenerator in listenerGenerators)
{
var events = new List<Event>();
using (var listener = listenerGenerator())
{
Debug.WriteLine("Testing Listener " + listener);
// Create an eventSource with manifest based serialization
using (var logger = new SdtEventSources.EventSourceTest())
{
listener.OnEvent = delegate (Event data) { events.Add(data); };
listener.EventSourceSynchronousEnable(logger);
// Use the Write<T> API. This is OK
logger.Write("MyTestEvent", new { arg1 = 3, arg2 = "hi" });
}
}
Assert.Equal(events.Count, 1);
Event _event = events[0];
Assert.Equal("MyTestEvent", _event.EventName);
Assert.Equal(3, (int)_event.PayloadValue(0, "arg1"));
Assert.Equal("hi", (string)_event.PayloadValue(1, "arg2"));
}
}
private void GenerateEnumTest<T>(ref List<SubTest> tests, EventSource logger, T enumValue)
{
string subTestName = enumValue.GetType().ToString();
tests.Add(new SubTest("Write/Enum/EnumEvent" + subTestName,
delegate ()
{
T c = enumValue;
// log an array
logger.Write("EnumEvent" + subTestName, new { b = "start", v = c, s = "end" });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EnumEvent" + subTestName, evt.EventName);
Assert.Equal(evt.PayloadValue(0, "b"), "start");
if (evt.IsEtw)
{
var value = evt.PayloadValue(1, "v");
Assert.Equal(2, int.Parse(value.ToString())); // Green has the int value of 2.
}
else
{
Assert.Equal(evt.PayloadValue(1, "v"), enumValue);
}
Assert.Equal(evt.PayloadValue(2, "s"), "end");
}));
}
private void GenerateArrayTest<T>(ref List<SubTest> tests, EventSource logger, T[] array)
{
string typeName = array.GetType().GetElementType().ToString();
tests.Add(new SubTest("Write/Array/" + typeName,
delegate ()
{
// log an array
logger.Write("SomeEvent" + typeName, new { a = array, s = "end" });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("SomeEvent" + typeName, evt.EventName);
var eventArray = evt.PayloadValue(0, "a");
Array.Equals(array, eventArray);
Assert.Equal("end", evt.PayloadValue(1, "s"));
}));
}
/// <summary>
/// Convert an array of key value pairs (as ETW structs) into a dictionary with those values.
/// </summary>
/// <param name="structValue"></param>
/// <returns></returns>
private IDictionary<string, object> GetDictionaryFromKeyValueArray(object structValue)
{
var ret = new Dictionary<string, object>();
var asArray = structValue as object[];
Assert.NotNull(asArray);
foreach (var item in asArray)
{
var keyValue = item as IDictionary<string, object>;
Assert.Equal(keyValue.Count, 2);
ret.Add((string)keyValue["Key"], keyValue["Value"]);
}
return ret;
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using System;
using System.Collections.Generic;
using System.Linq;
using Twilio.Base;
using Twilio.Converters;
namespace Twilio.Rest.Chat.V1.Service
{
/// <summary>
/// FetchRoleOptions
/// </summary>
public class FetchRoleOptions : IOptions<RoleResource>
{
/// <summary>
/// The SID of the Service to fetch the resource from
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The unique string that identifies the resource
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new FetchRoleOptions
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to fetch the resource from </param>
/// <param name="pathSid"> The unique string that identifies the resource </param>
public FetchRoleOptions(string pathServiceSid, string pathSid)
{
PathServiceSid = pathServiceSid;
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// DeleteRoleOptions
/// </summary>
public class DeleteRoleOptions : IOptions<RoleResource>
{
/// <summary>
/// The SID of the Service to delete the resource from
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The unique string that identifies the resource
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new DeleteRoleOptions
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to delete the resource from </param>
/// <param name="pathSid"> The unique string that identifies the resource </param>
public DeleteRoleOptions(string pathServiceSid, string pathSid)
{
PathServiceSid = pathServiceSid;
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// CreateRoleOptions
/// </summary>
public class CreateRoleOptions : IOptions<RoleResource>
{
/// <summary>
/// The SID of the Service to create the resource under
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// A string to describe the new resource
/// </summary>
public string FriendlyName { get; }
/// <summary>
/// The type of role
/// </summary>
public RoleResource.RoleTypeEnum Type { get; }
/// <summary>
/// A permission the role should have
/// </summary>
public List<string> Permission { get; }
/// <summary>
/// Construct a new CreateRoleOptions
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to create the resource under </param>
/// <param name="friendlyName"> A string to describe the new resource </param>
/// <param name="type"> The type of role </param>
/// <param name="permission"> A permission the role should have </param>
public CreateRoleOptions(string pathServiceSid,
string friendlyName,
RoleResource.RoleTypeEnum type,
List<string> permission)
{
PathServiceSid = pathServiceSid;
FriendlyName = friendlyName;
Type = type;
Permission = permission;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (FriendlyName != null)
{
p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName));
}
if (Type != null)
{
p.Add(new KeyValuePair<string, string>("Type", Type.ToString()));
}
if (Permission != null)
{
p.AddRange(Permission.Select(prop => new KeyValuePair<string, string>("Permission", prop)));
}
return p;
}
}
/// <summary>
/// ReadRoleOptions
/// </summary>
public class ReadRoleOptions : ReadOptions<RoleResource>
{
/// <summary>
/// The SID of the Service to read the resources from
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// Construct a new ReadRoleOptions
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to read the resources from </param>
public ReadRoleOptions(string pathServiceSid)
{
PathServiceSid = pathServiceSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public override List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (PageSize != null)
{
p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString()));
}
return p;
}
}
/// <summary>
/// UpdateRoleOptions
/// </summary>
public class UpdateRoleOptions : IOptions<RoleResource>
{
/// <summary>
/// The SID of the Service to update the resource from
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The unique string that identifies the resource
/// </summary>
public string PathSid { get; }
/// <summary>
/// A permission the role should have
/// </summary>
public List<string> Permission { get; }
/// <summary>
/// Construct a new UpdateRoleOptions
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to update the resource from </param>
/// <param name="pathSid"> The unique string that identifies the resource </param>
/// <param name="permission"> A permission the role should have </param>
public UpdateRoleOptions(string pathServiceSid, string pathSid, List<string> permission)
{
PathServiceSid = pathServiceSid;
PathSid = pathSid;
Permission = permission;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Permission != null)
{
p.AddRange(Permission.Select(prop => new KeyValuePair<string, string>("Permission", prop)));
}
return p;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using ILCompiler.DependencyAnalysisFramework;
using Xunit;
namespace ILCompiler.DependencyAnalysisFramework.Tests
{
public class DependencyTests
{
public DependencyTests()
{
}
/// <summary>
/// Test on every graph type. Used to ensure that the behavior of the various markers is consistent
/// </summary>
/// <param name="testGraph"></param>
private void TestOnGraphTypes(Action<TestGraph, DependencyAnalyzerBase<TestGraph>> testGraph)
{
// Test using the full logging strategy
TestGraph testGraphFull = new TestGraph();
DependencyAnalyzerBase<TestGraph> analyzerFull = new DependencyAnalyzer<FullGraphLogStrategy<TestGraph>, TestGraph>(testGraphFull, null);
testGraphFull.AttachToDependencyAnalyzer(analyzerFull);
testGraph(testGraphFull, analyzerFull);
TestGraph testGraphFirstMark = new TestGraph();
DependencyAnalyzerBase<TestGraph> analyzerFirstMark = new DependencyAnalyzer<FirstMarkLogStrategy<TestGraph>, TestGraph>(testGraphFirstMark, null);
testGraphFirstMark.AttachToDependencyAnalyzer(analyzerFirstMark);
testGraph(testGraphFirstMark, analyzerFirstMark);
TestGraph testGraphNoLog = new TestGraph();
DependencyAnalyzerBase<TestGraph> analyzerNoLog = new DependencyAnalyzer<NoLogStrategy<TestGraph>, TestGraph>(testGraphNoLog, null);
testGraphNoLog.AttachToDependencyAnalyzer(analyzerNoLog);
testGraph(testGraphNoLog, analyzerNoLog);
}
[Fact]
public void TestADependsOnB()
{
TestOnGraphTypes((TestGraph testGraph, DependencyAnalyzerBase<TestGraph> analyzer) =>
{
testGraph.AddStaticRule("A", "B", "A depends on B");
testGraph.AddRoot("A", "A is root");
List<string> results = testGraph.AnalysisResults;
Assert.True(results.Contains("A"));
Assert.True(results.Contains("B"));
});
}
[Fact]
public void TestADependsOnBIfC_NoC()
{
TestOnGraphTypes((TestGraph testGraph, DependencyAnalyzerBase<TestGraph> analyzer) =>
{
testGraph.AddConditionalRule("A", "C", "B", "A depends on B if C");
testGraph.AddRoot("A", "A is root");
List<string> results = testGraph.AnalysisResults;
Assert.True(results.Contains("A"));
Assert.False(results.Contains("B"));
Assert.False(results.Contains("C"));
Assert.True(results.Count == 1);
});
}
[Fact]
public void TestADependsOnBIfC_HasC()
{
TestOnGraphTypes((TestGraph testGraph, DependencyAnalyzerBase<TestGraph> analyzer) =>
{
testGraph.AddConditionalRule("A", "C", "B", "A depends on B if C");
testGraph.AddRoot("A", "A is root");
testGraph.AddRoot("C", "C is root");
List<string> results = testGraph.AnalysisResults;
Assert.True(results.Contains("A"));
Assert.True(results.Contains("B"));
Assert.True(results.Contains("C"));
Assert.True(results.Count == 3);
});
}
[Fact]
public void TestSimpleDynamicRule()
{
TestOnGraphTypes((TestGraph testGraph, DependencyAnalyzerBase<TestGraph> analyzer) =>
{
testGraph.SetDynamicDependencyRule((string nodeA, string nodeB) =>
{
if (nodeA.EndsWith("*") && nodeB.StartsWith("*"))
{
return new Tuple<string, string>(nodeA + nodeB, "DynamicRule");
}
return null;
});
testGraph.AddRoot("A*", "A* is root");
testGraph.AddRoot("B*", "B* is root");
testGraph.AddRoot("*C", "*C is root");
testGraph.AddRoot("*D", "*D is root");
testGraph.AddRoot("A*B", "A*B is root");
List<string> results = testGraph.AnalysisResults;
Assert.Contains("A*", results);
Assert.Contains("B*", results);
Assert.Contains("*C", results);
Assert.Contains("*D", results);
Assert.Contains("A*B", results);
Assert.Contains("A**C", results);
Assert.Contains("A**D", results);
Assert.Contains("B**C", results);
Assert.Contains("B**D", results);
Assert.True(results.Count == 9);
});
}
private void BuildGraphUsingAllTypesOfRules(TestGraph testGraph, DependencyAnalyzerBase<TestGraph> analyzer)
{
testGraph.SetDynamicDependencyRule((string nodeA, string nodeB) =>
{
if (nodeA.EndsWith("*") && nodeB.StartsWith("*"))
{
return new Tuple<string, string>(nodeA + nodeB, "DynamicRule");
}
return null;
});
testGraph.AddConditionalRule("A**C", "B**D", "D", "A**C depends on D if B**D");
testGraph.AddStaticRule("D", "E", "D depends on E");
// Rules to ensure that there are some nodes that have multiple reasons to exist
testGraph.AddStaticRule("A*", "E", "A* depends on E");
testGraph.AddStaticRule("*C", "E", "*C depends on E");
testGraph.AddRoot("A*", "A* is root");
testGraph.AddRoot("B*", "B* is root");
testGraph.AddRoot("*C", "*C is root");
testGraph.AddRoot("*D", "*D is root");
testGraph.AddRoot("A*B", "A*B is root");
List<string> results = testGraph.AnalysisResults;
Assert.Contains("A*", results);
Assert.Contains("B*", results);
Assert.Contains("*C", results);
Assert.Contains("*D", results);
Assert.Contains("A*B", results);
Assert.Contains("A**C", results);
Assert.Contains("A**D", results);
Assert.Contains("B**C", results);
Assert.Contains("B**D", results);
Assert.Contains("D", results);
Assert.Contains("E", results);
Assert.True(results.Count == 11);
}
[Fact]
public void TestDGMLOutput()
{
Dictionary<string, string> dgmlOutputs = new Dictionary<string, string>();
TestOnGraphTypes((TestGraph testGraph, DependencyAnalyzerBase<TestGraph> analyzer) =>
{
BuildGraphUsingAllTypesOfRules(testGraph, analyzer);
MemoryStream dgmlOutput = new MemoryStream();
DgmlWriter.WriteDependencyGraphToStream(dgmlOutput, analyzer, testGraph);
dgmlOutput.Seek(0, SeekOrigin.Begin);
TextReader tr = new StreamReader(dgmlOutput);
dgmlOutputs[analyzer.GetType().FullName] = tr.ReadToEnd();
});
foreach (var pair in dgmlOutputs)
{
int nodeCount = pair.Value.Split(new string[] { "<Node " }, StringSplitOptions.None).Length - 1;
int edgeCount = pair.Value.Split(new string[] { "<Link " }, StringSplitOptions.None).Length - 1;
if (pair.Key.Contains("FullGraph"))
{
Assert.Equal(21, nodeCount);
Assert.Equal(23, edgeCount);
}
else if (pair.Key.Contains("FirstMark"))
{
// There are 2 edges in the all types of rules graph that are duplicates. Note that the edge count is
// 2 less than the full graph edge count
Assert.Equal(21, nodeCount);
Assert.Equal(21, edgeCount);
}
else
{
Assert.Contains("NoLog", pair.Key);
Assert.Equal(11, nodeCount);
Assert.Equal(0, edgeCount);
}
}
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Accidents Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class SADDataSet : EduHubDataSet<SAD>
{
/// <inheritdoc />
public override string Name { get { return "SAD"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal SADDataSet(EduHubContext Context)
: base(Context)
{
Index_AREA_DUTY_TEACHER = new Lazy<NullDictionary<string, IReadOnlyList<SAD>>>(() => this.ToGroupedNullDictionary(i => i.AREA_DUTY_TEACHER));
Index_CAMPUS = new Lazy<NullDictionary<int?, IReadOnlyList<SAD>>>(() => this.ToGroupedNullDictionary(i => i.CAMPUS));
Index_ROOM = new Lazy<NullDictionary<string, IReadOnlyList<SAD>>>(() => this.ToGroupedNullDictionary(i => i.ROOM));
Index_SADKEY = new Lazy<Dictionary<int, SAD>>(() => this.ToDictionary(i => i.SADKEY));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="SAD" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="SAD" /> fields for each CSV column header</returns>
internal override Action<SAD, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<SAD, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "SADKEY":
mapper[i] = (e, v) => e.SADKEY = int.Parse(v);
break;
case "DETAIL_OUTLINE":
mapper[i] = (e, v) => e.DETAIL_OUTLINE = v;
break;
case "ACCIDENT_DATE":
mapper[i] = (e, v) => e.ACCIDENT_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "ACCIDENT_TIME":
mapper[i] = (e, v) => e.ACCIDENT_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "GENERAL_ACTIVITY":
mapper[i] = (e, v) => e.GENERAL_ACTIVITY = v == null ? (short?)null : short.Parse(v);
break;
case "DETAILED_ACTIVITY":
mapper[i] = (e, v) => e.DETAILED_ACTIVITY = v == null ? (short?)null : short.Parse(v);
break;
case "OTHER_ACTIVITY_INFO":
mapper[i] = (e, v) => e.OTHER_ACTIVITY_INFO = v;
break;
case "DESCRIPTION":
mapper[i] = (e, v) => e.DESCRIPTION = v == null ? (short?)null : short.Parse(v);
break;
case "OTHER_DESC_INFO":
mapper[i] = (e, v) => e.OTHER_DESC_INFO = v;
break;
case "ACCIDENT_SITE":
mapper[i] = (e, v) => e.ACCIDENT_SITE = v == null ? (short?)null : short.Parse(v);
break;
case "CAMPUS":
mapper[i] = (e, v) => e.CAMPUS = v == null ? (int?)null : int.Parse(v);
break;
case "EXTERNAL_ADDRESS":
mapper[i] = (e, v) => e.EXTERNAL_ADDRESS = v;
break;
case "ROOM":
mapper[i] = (e, v) => e.ROOM = v;
break;
case "AREA_DUTY_TEACHER":
mapper[i] = (e, v) => e.AREA_DUTY_TEACHER = v;
break;
case "DUTY_TEACHER_FULL_NAME":
mapper[i] = (e, v) => e.DUTY_TEACHER_FULL_NAME = v;
break;
case "TEACHERS_ON_DUTY":
mapper[i] = (e, v) => e.TEACHERS_ON_DUTY = v == null ? (short?)null : short.Parse(v);
break;
case "CREATION_DATE":
mapper[i] = (e, v) => e.CREATION_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "MAILED":
mapper[i] = (e, v) => e.MAILED = v;
break;
case "FIRST_INJURED_PARTY":
mapper[i] = (e, v) => e.FIRST_INJURED_PARTY = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="SAD" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="SAD" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="SAD" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{SAD}"/> of entities</returns>
internal override IEnumerable<SAD> ApplyDeltaEntities(IEnumerable<SAD> Entities, List<SAD> DeltaEntities)
{
HashSet<int> Index_SADKEY = new HashSet<int>(DeltaEntities.Select(i => i.SADKEY));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.SADKEY;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_SADKEY.Remove(entity.SADKEY);
if (entity.SADKEY.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<NullDictionary<string, IReadOnlyList<SAD>>> Index_AREA_DUTY_TEACHER;
private Lazy<NullDictionary<int?, IReadOnlyList<SAD>>> Index_CAMPUS;
private Lazy<NullDictionary<string, IReadOnlyList<SAD>>> Index_ROOM;
private Lazy<Dictionary<int, SAD>> Index_SADKEY;
#endregion
#region Index Methods
/// <summary>
/// Find SAD by AREA_DUTY_TEACHER field
/// </summary>
/// <param name="AREA_DUTY_TEACHER">AREA_DUTY_TEACHER value used to find SAD</param>
/// <returns>List of related SAD entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<SAD> FindByAREA_DUTY_TEACHER(string AREA_DUTY_TEACHER)
{
return Index_AREA_DUTY_TEACHER.Value[AREA_DUTY_TEACHER];
}
/// <summary>
/// Attempt to find SAD by AREA_DUTY_TEACHER field
/// </summary>
/// <param name="AREA_DUTY_TEACHER">AREA_DUTY_TEACHER value used to find SAD</param>
/// <param name="Value">List of related SAD entities</param>
/// <returns>True if the list of related SAD entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByAREA_DUTY_TEACHER(string AREA_DUTY_TEACHER, out IReadOnlyList<SAD> Value)
{
return Index_AREA_DUTY_TEACHER.Value.TryGetValue(AREA_DUTY_TEACHER, out Value);
}
/// <summary>
/// Attempt to find SAD by AREA_DUTY_TEACHER field
/// </summary>
/// <param name="AREA_DUTY_TEACHER">AREA_DUTY_TEACHER value used to find SAD</param>
/// <returns>List of related SAD entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<SAD> TryFindByAREA_DUTY_TEACHER(string AREA_DUTY_TEACHER)
{
IReadOnlyList<SAD> value;
if (Index_AREA_DUTY_TEACHER.Value.TryGetValue(AREA_DUTY_TEACHER, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find SAD by CAMPUS field
/// </summary>
/// <param name="CAMPUS">CAMPUS value used to find SAD</param>
/// <returns>List of related SAD entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<SAD> FindByCAMPUS(int? CAMPUS)
{
return Index_CAMPUS.Value[CAMPUS];
}
/// <summary>
/// Attempt to find SAD by CAMPUS field
/// </summary>
/// <param name="CAMPUS">CAMPUS value used to find SAD</param>
/// <param name="Value">List of related SAD entities</param>
/// <returns>True if the list of related SAD entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByCAMPUS(int? CAMPUS, out IReadOnlyList<SAD> Value)
{
return Index_CAMPUS.Value.TryGetValue(CAMPUS, out Value);
}
/// <summary>
/// Attempt to find SAD by CAMPUS field
/// </summary>
/// <param name="CAMPUS">CAMPUS value used to find SAD</param>
/// <returns>List of related SAD entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<SAD> TryFindByCAMPUS(int? CAMPUS)
{
IReadOnlyList<SAD> value;
if (Index_CAMPUS.Value.TryGetValue(CAMPUS, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find SAD by ROOM field
/// </summary>
/// <param name="ROOM">ROOM value used to find SAD</param>
/// <returns>List of related SAD entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<SAD> FindByROOM(string ROOM)
{
return Index_ROOM.Value[ROOM];
}
/// <summary>
/// Attempt to find SAD by ROOM field
/// </summary>
/// <param name="ROOM">ROOM value used to find SAD</param>
/// <param name="Value">List of related SAD entities</param>
/// <returns>True if the list of related SAD entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByROOM(string ROOM, out IReadOnlyList<SAD> Value)
{
return Index_ROOM.Value.TryGetValue(ROOM, out Value);
}
/// <summary>
/// Attempt to find SAD by ROOM field
/// </summary>
/// <param name="ROOM">ROOM value used to find SAD</param>
/// <returns>List of related SAD entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<SAD> TryFindByROOM(string ROOM)
{
IReadOnlyList<SAD> value;
if (Index_ROOM.Value.TryGetValue(ROOM, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find SAD by SADKEY field
/// </summary>
/// <param name="SADKEY">SADKEY value used to find SAD</param>
/// <returns>Related SAD entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public SAD FindBySADKEY(int SADKEY)
{
return Index_SADKEY.Value[SADKEY];
}
/// <summary>
/// Attempt to find SAD by SADKEY field
/// </summary>
/// <param name="SADKEY">SADKEY value used to find SAD</param>
/// <param name="Value">Related SAD entity</param>
/// <returns>True if the related SAD entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindBySADKEY(int SADKEY, out SAD Value)
{
return Index_SADKEY.Value.TryGetValue(SADKEY, out Value);
}
/// <summary>
/// Attempt to find SAD by SADKEY field
/// </summary>
/// <param name="SADKEY">SADKEY value used to find SAD</param>
/// <returns>Related SAD entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public SAD TryFindBySADKEY(int SADKEY)
{
SAD value;
if (Index_SADKEY.Value.TryGetValue(SADKEY, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a SAD table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SAD]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[SAD](
[SADKEY] int IDENTITY NOT NULL,
[DETAIL_OUTLINE] varchar(MAX) NULL,
[ACCIDENT_DATE] datetime NULL,
[ACCIDENT_TIME] smallint NULL,
[GENERAL_ACTIVITY] smallint NULL,
[DETAILED_ACTIVITY] smallint NULL,
[OTHER_ACTIVITY_INFO] varchar(MAX) NULL,
[DESCRIPTION] smallint NULL,
[OTHER_DESC_INFO] varchar(MAX) NULL,
[ACCIDENT_SITE] smallint NULL,
[CAMPUS] int NULL,
[EXTERNAL_ADDRESS] varchar(MAX) NULL,
[ROOM] varchar(4) NULL,
[AREA_DUTY_TEACHER] varchar(4) NULL,
[DUTY_TEACHER_FULL_NAME] varchar(64) NULL,
[TEACHERS_ON_DUTY] smallint NULL,
[CREATION_DATE] datetime NULL,
[MAILED] varchar(1) NULL,
[FIRST_INJURED_PARTY] varchar(64) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [SAD_Index_SADKEY] PRIMARY KEY CLUSTERED (
[SADKEY] ASC
)
);
CREATE NONCLUSTERED INDEX [SAD_Index_AREA_DUTY_TEACHER] ON [dbo].[SAD]
(
[AREA_DUTY_TEACHER] ASC
);
CREATE NONCLUSTERED INDEX [SAD_Index_CAMPUS] ON [dbo].[SAD]
(
[CAMPUS] ASC
);
CREATE NONCLUSTERED INDEX [SAD_Index_ROOM] ON [dbo].[SAD]
(
[ROOM] ASC
);
END");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes.
/// Typically called before <see cref="SqlBulkCopy"/> to improve performance.
/// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SAD]') AND name = N'SAD_Index_AREA_DUTY_TEACHER')
ALTER INDEX [SAD_Index_AREA_DUTY_TEACHER] ON [dbo].[SAD] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SAD]') AND name = N'SAD_Index_CAMPUS')
ALTER INDEX [SAD_Index_CAMPUS] ON [dbo].[SAD] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SAD]') AND name = N'SAD_Index_ROOM')
ALTER INDEX [SAD_Index_ROOM] ON [dbo].[SAD] DISABLE;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SAD]') AND name = N'SAD_Index_AREA_DUTY_TEACHER')
ALTER INDEX [SAD_Index_AREA_DUTY_TEACHER] ON [dbo].[SAD] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SAD]') AND name = N'SAD_Index_CAMPUS')
ALTER INDEX [SAD_Index_CAMPUS] ON [dbo].[SAD] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SAD]') AND name = N'SAD_Index_ROOM')
ALTER INDEX [SAD_Index_ROOM] ON [dbo].[SAD] REBUILD PARTITION = ALL;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="SAD"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="SAD"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<SAD> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<int> Index_SADKEY = new List<int>();
foreach (var entity in Entities)
{
Index_SADKEY.Add(entity.SADKEY);
}
builder.AppendLine("DELETE [dbo].[SAD] WHERE");
// Index_SADKEY
builder.Append("[SADKEY] IN (");
for (int index = 0; index < Index_SADKEY.Count; index++)
{
if (index != 0)
builder.Append(", ");
// SADKEY
var parameterSADKEY = $"@p{parameterIndex++}";
builder.Append(parameterSADKEY);
command.Parameters.Add(parameterSADKEY, SqlDbType.Int).Value = Index_SADKEY[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the SAD data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the SAD data set</returns>
public override EduHubDataSetDataReader<SAD> GetDataSetDataReader()
{
return new SADDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the SAD data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the SAD data set</returns>
public override EduHubDataSetDataReader<SAD> GetDataSetDataReader(List<SAD> Entities)
{
return new SADDataReader(new EduHubDataSetLoadedReader<SAD>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class SADDataReader : EduHubDataSetDataReader<SAD>
{
public SADDataReader(IEduHubDataSetReader<SAD> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 22; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // SADKEY
return Current.SADKEY;
case 1: // DETAIL_OUTLINE
return Current.DETAIL_OUTLINE;
case 2: // ACCIDENT_DATE
return Current.ACCIDENT_DATE;
case 3: // ACCIDENT_TIME
return Current.ACCIDENT_TIME;
case 4: // GENERAL_ACTIVITY
return Current.GENERAL_ACTIVITY;
case 5: // DETAILED_ACTIVITY
return Current.DETAILED_ACTIVITY;
case 6: // OTHER_ACTIVITY_INFO
return Current.OTHER_ACTIVITY_INFO;
case 7: // DESCRIPTION
return Current.DESCRIPTION;
case 8: // OTHER_DESC_INFO
return Current.OTHER_DESC_INFO;
case 9: // ACCIDENT_SITE
return Current.ACCIDENT_SITE;
case 10: // CAMPUS
return Current.CAMPUS;
case 11: // EXTERNAL_ADDRESS
return Current.EXTERNAL_ADDRESS;
case 12: // ROOM
return Current.ROOM;
case 13: // AREA_DUTY_TEACHER
return Current.AREA_DUTY_TEACHER;
case 14: // DUTY_TEACHER_FULL_NAME
return Current.DUTY_TEACHER_FULL_NAME;
case 15: // TEACHERS_ON_DUTY
return Current.TEACHERS_ON_DUTY;
case 16: // CREATION_DATE
return Current.CREATION_DATE;
case 17: // MAILED
return Current.MAILED;
case 18: // FIRST_INJURED_PARTY
return Current.FIRST_INJURED_PARTY;
case 19: // LW_DATE
return Current.LW_DATE;
case 20: // LW_TIME
return Current.LW_TIME;
case 21: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // DETAIL_OUTLINE
return Current.DETAIL_OUTLINE == null;
case 2: // ACCIDENT_DATE
return Current.ACCIDENT_DATE == null;
case 3: // ACCIDENT_TIME
return Current.ACCIDENT_TIME == null;
case 4: // GENERAL_ACTIVITY
return Current.GENERAL_ACTIVITY == null;
case 5: // DETAILED_ACTIVITY
return Current.DETAILED_ACTIVITY == null;
case 6: // OTHER_ACTIVITY_INFO
return Current.OTHER_ACTIVITY_INFO == null;
case 7: // DESCRIPTION
return Current.DESCRIPTION == null;
case 8: // OTHER_DESC_INFO
return Current.OTHER_DESC_INFO == null;
case 9: // ACCIDENT_SITE
return Current.ACCIDENT_SITE == null;
case 10: // CAMPUS
return Current.CAMPUS == null;
case 11: // EXTERNAL_ADDRESS
return Current.EXTERNAL_ADDRESS == null;
case 12: // ROOM
return Current.ROOM == null;
case 13: // AREA_DUTY_TEACHER
return Current.AREA_DUTY_TEACHER == null;
case 14: // DUTY_TEACHER_FULL_NAME
return Current.DUTY_TEACHER_FULL_NAME == null;
case 15: // TEACHERS_ON_DUTY
return Current.TEACHERS_ON_DUTY == null;
case 16: // CREATION_DATE
return Current.CREATION_DATE == null;
case 17: // MAILED
return Current.MAILED == null;
case 18: // FIRST_INJURED_PARTY
return Current.FIRST_INJURED_PARTY == null;
case 19: // LW_DATE
return Current.LW_DATE == null;
case 20: // LW_TIME
return Current.LW_TIME == null;
case 21: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // SADKEY
return "SADKEY";
case 1: // DETAIL_OUTLINE
return "DETAIL_OUTLINE";
case 2: // ACCIDENT_DATE
return "ACCIDENT_DATE";
case 3: // ACCIDENT_TIME
return "ACCIDENT_TIME";
case 4: // GENERAL_ACTIVITY
return "GENERAL_ACTIVITY";
case 5: // DETAILED_ACTIVITY
return "DETAILED_ACTIVITY";
case 6: // OTHER_ACTIVITY_INFO
return "OTHER_ACTIVITY_INFO";
case 7: // DESCRIPTION
return "DESCRIPTION";
case 8: // OTHER_DESC_INFO
return "OTHER_DESC_INFO";
case 9: // ACCIDENT_SITE
return "ACCIDENT_SITE";
case 10: // CAMPUS
return "CAMPUS";
case 11: // EXTERNAL_ADDRESS
return "EXTERNAL_ADDRESS";
case 12: // ROOM
return "ROOM";
case 13: // AREA_DUTY_TEACHER
return "AREA_DUTY_TEACHER";
case 14: // DUTY_TEACHER_FULL_NAME
return "DUTY_TEACHER_FULL_NAME";
case 15: // TEACHERS_ON_DUTY
return "TEACHERS_ON_DUTY";
case 16: // CREATION_DATE
return "CREATION_DATE";
case 17: // MAILED
return "MAILED";
case 18: // FIRST_INJURED_PARTY
return "FIRST_INJURED_PARTY";
case 19: // LW_DATE
return "LW_DATE";
case 20: // LW_TIME
return "LW_TIME";
case 21: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "SADKEY":
return 0;
case "DETAIL_OUTLINE":
return 1;
case "ACCIDENT_DATE":
return 2;
case "ACCIDENT_TIME":
return 3;
case "GENERAL_ACTIVITY":
return 4;
case "DETAILED_ACTIVITY":
return 5;
case "OTHER_ACTIVITY_INFO":
return 6;
case "DESCRIPTION":
return 7;
case "OTHER_DESC_INFO":
return 8;
case "ACCIDENT_SITE":
return 9;
case "CAMPUS":
return 10;
case "EXTERNAL_ADDRESS":
return 11;
case "ROOM":
return 12;
case "AREA_DUTY_TEACHER":
return 13;
case "DUTY_TEACHER_FULL_NAME":
return 14;
case "TEACHERS_ON_DUTY":
return 15;
case "CREATION_DATE":
return 16;
case "MAILED":
return 17;
case "FIRST_INJURED_PARTY":
return 18;
case "LW_DATE":
return 19;
case "LW_TIME":
return 20;
case "LW_USER":
return 21;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using NLog.LayoutRenderers;
using NLog.Targets;
#if !SILVERLIGHT
using Xunit.Extensions;
#endif
namespace NLog.UnitTests.Config
{
using System;
using System.Globalization;
using System.Threading;
using Xunit;
using NLog.Config;
public class CultureInfoTests : NLogTestBase
{
[Fact]
public void WhenInvariantCultureDefinedThenDefaultCultureIsInvariantCulture()
{
var configuration = CreateConfigurationFromString("<nlog useInvariantCulture='true'></nlog>");
Assert.Equal(CultureInfo.InvariantCulture, configuration.DefaultCultureInfo);
}
[Fact]
public void DifferentConfigurations_UseDifferentDefaultCulture()
{
var currentCulture = CultureInfo.CurrentCulture;
try
{
// set the current thread culture to be definitely different from the InvariantCulture
Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");
var configurationTemplate = @"<nlog useInvariantCulture='{0}'>
<targets>
<target name='debug' type='Debug' layout='${{message}}' />
</targets>
<rules>
<logger name='*' writeTo='debug'/>
</rules>
</nlog>";
// configuration with current culture
var configuration1 = CreateConfigurationFromString(string.Format(configurationTemplate, false));
Assert.Equal(null, configuration1.DefaultCultureInfo);
// configuration with invariant culture
var configuration2 = CreateConfigurationFromString(string.Format(configurationTemplate, true));
Assert.Equal(CultureInfo.InvariantCulture, configuration2.DefaultCultureInfo);
Assert.NotEqual(configuration1.DefaultCultureInfo, configuration2.DefaultCultureInfo);
var testNumber = 3.14;
var testDate = DateTime.Now;
const string formatString = "{0},{1:d}";
AssertMessageFormattedWithCulture(configuration1, CultureInfo.CurrentCulture, formatString, testNumber, testDate);
AssertMessageFormattedWithCulture(configuration2, CultureInfo.InvariantCulture, formatString, testNumber, testDate);
}
finally
{
// restore current thread culture
Thread.CurrentThread.CurrentCulture = currentCulture;
}
}
private void AssertMessageFormattedWithCulture(LoggingConfiguration configuration, CultureInfo culture, string formatString, params object[] parameters)
{
var expected = string.Format(culture, formatString, parameters);
using (var logFactory = new LogFactory(configuration))
{
var logger = logFactory.GetLogger("test");
logger.Debug(formatString, parameters);
Assert.Equal(expected, GetDebugLastMessage("debug", configuration));
}
}
#if !SILVERLIGHT
[Fact]
public void EventPropRendererCultureTest()
{
string cultureName = "de-DE";
string expected = "1,23"; // with decimal comma
var logEventInfo = CreateLogEventInfo(cultureName);
logEventInfo.Properties["ADouble"] = 1.23;
var renderer = new EventPropertiesLayoutRenderer();
renderer.Item = "ADouble";
string output = renderer.Render(logEventInfo);
Assert.Equal(expected, output);
}
[Fact]
public void EventContextRendererCultureTest()
{
string cultureName = "de-DE";
string expected = "1,23"; // with decimal comma
var logEventInfo = CreateLogEventInfo(cultureName);
logEventInfo.Properties["ADouble"] = 1.23;
#pragma warning disable 618
var renderer = new EventContextLayoutRenderer();
#pragma warning restore 618
renderer.Item = "ADouble";
string output = renderer.Render(logEventInfo);
Assert.Equal(expected, output);
}
#if !MONO
[Fact(Skip = "TimeSpan tostring isn't culture aware in .NET?")]
public void ProcessInfoLayoutRendererCultureTest()
{
string cultureName = "de-DE";
string expected = ","; // decimal comma as separator for ticks
var logEventInfo = CreateLogEventInfo(cultureName);
var renderer = new ProcessInfoLayoutRenderer();
renderer.Property = ProcessInfoProperty.TotalProcessorTime;
string output = renderer.Render(logEventInfo);
Assert.Contains(expected, output);
Assert.DoesNotContain(".", output);
}
#endif
[Fact]
public void AllEventPropRendererCultureTest()
{
string cultureName = "de-DE";
string expected = "ADouble=1,23"; // with decimal comma
var logEventInfo = CreateLogEventInfo(cultureName);
logEventInfo.Properties["ADouble"] = 1.23;
var renderer = new AllEventPropertiesLayoutRenderer();
string output = renderer.Render(logEventInfo);
Assert.Equal(expected, output);
}
[Theory]
[InlineData(typeof(TimeLayoutRenderer))]
[InlineData(typeof(ProcessTimeLayoutRenderer))]
public void DateTimeCultureTest(Type rendererType)
{
string cultureName = "de-DE";
string expected = ","; // decimal comma as separator for ticks
var logEventInfo = CreateLogEventInfo(cultureName);
var renderer = Activator.CreateInstance(rendererType) as LayoutRenderer;
Assert.NotNull(renderer);
string output = renderer.Render(logEventInfo);
Assert.Contains(expected, output);
Assert.DoesNotContain(".", output);
}
private static LogEventInfo CreateLogEventInfo(string cultureName)
{
var logEventInfo = new LogEventInfo(
LogLevel.Info,
"SomeName",
CultureInfo.GetCultureInfo(cultureName),
"SomeMessage",
null);
return logEventInfo;
}
/// <summary>
/// expected: exactly the same exception message + stack trace regardless of the CurrentUICulture
/// </summary>
[Fact]
public void ExceptionTest()
{
var target = new MemoryTarget { Layout = @"${exception:format=tostring}" };
SimpleConfigurator.ConfigureForTargetLogging(target);
var logger = LogManager.GetCurrentClassLogger();
try
{
throw new InvalidOperationException();
}
catch (Exception ex)
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
logger.Error(ex, "");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("de-DE");
Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");
logger.Error(ex, "");
Assert.Equal(2, target.Logs.Count);
Assert.NotNull(target.Logs[0]);
Assert.NotNull(target.Logs[1]);
Assert.Equal(target.Logs[0], target.Logs[1]);
}
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text;
namespace System.IO.Compression
{
// The disposable fields that this class owns get disposed when the ZipArchive it belongs to gets disposed
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
public partial class ZipArchiveEntry
{
// The maximum index of our buffers, from the maximum index of a byte array
private const int MaxSingleBufferSize = 0x7FFFFFC7;
private ZipArchive _archive;
private readonly bool _originallyInArchive;
private readonly int _diskNumberStart;
private readonly ZipVersionMadeByPlatform _versionMadeByPlatform;
private ZipVersionNeededValues _versionMadeBySpecification;
internal ZipVersionNeededValues _versionToExtract;
private BitFlagValues _generalPurposeBitFlag;
private CompressionMethodValues _storedCompressionMethod;
private DateTimeOffset _lastModified;
private long _compressedSize;
private long _uncompressedSize;
private long _offsetOfLocalHeader;
private long? _storedOffsetOfCompressedData;
private uint _crc32;
// An array of buffers, each a maximum of MaxSingleBufferSize in size
private byte[][]? _compressedBytes;
private MemoryStream? _storedUncompressedData;
private bool _currentlyOpenForWrite;
private bool _everOpenedForWrite;
private Stream? _outstandingWriteStream;
private uint _externalFileAttr;
private string _storedEntryName = null!; // indirectly set in constructor using FullName property
private byte[] _storedEntryNameBytes = null!;
// only apply to update mode
private List<ZipGenericExtraField>? _cdUnknownExtraFields;
private List<ZipGenericExtraField>? _lhUnknownExtraFields;
private readonly byte[]? _fileComment;
private readonly CompressionLevel? _compressionLevel;
// Initializes, attaches it to archive
internal ZipArchiveEntry(ZipArchive archive, ZipCentralDirectoryFileHeader cd)
{
_archive = archive;
_originallyInArchive = true;
_diskNumberStart = cd.DiskNumberStart;
_versionMadeByPlatform = (ZipVersionMadeByPlatform)cd.VersionMadeByCompatibility;
_versionMadeBySpecification = (ZipVersionNeededValues)cd.VersionMadeBySpecification;
_versionToExtract = (ZipVersionNeededValues)cd.VersionNeededToExtract;
_generalPurposeBitFlag = (BitFlagValues)cd.GeneralPurposeBitFlag;
CompressionMethod = (CompressionMethodValues)cd.CompressionMethod;
_lastModified = new DateTimeOffset(ZipHelper.DosTimeToDateTime(cd.LastModified));
_compressedSize = cd.CompressedSize;
_uncompressedSize = cd.UncompressedSize;
_externalFileAttr = cd.ExternalFileAttributes;
_offsetOfLocalHeader = cd.RelativeOffsetOfLocalHeader;
// we don't know this yet: should be _offsetOfLocalHeader + 30 + _storedEntryNameBytes.Length + extrafieldlength
// but entryname/extra length could be different in LH
_storedOffsetOfCompressedData = null;
_crc32 = cd.Crc32;
_compressedBytes = null;
_storedUncompressedData = null;
_currentlyOpenForWrite = false;
_everOpenedForWrite = false;
_outstandingWriteStream = null;
FullName = DecodeEntryName(cd.Filename);
_lhUnknownExtraFields = null;
// the cd should have these as null if we aren't in Update mode
_cdUnknownExtraFields = cd.ExtraFields;
_fileComment = cd.FileComment;
_compressionLevel = null;
}
// Initializes new entry
internal ZipArchiveEntry(ZipArchive archive, string entryName, CompressionLevel compressionLevel)
: this(archive, entryName)
{
_compressionLevel = compressionLevel;
if (_compressionLevel == CompressionLevel.NoCompression)
{
CompressionMethod = CompressionMethodValues.Stored;
}
}
// Initializes new entry
internal ZipArchiveEntry(ZipArchive archive, string entryName)
{
_archive = archive;
_originallyInArchive = false;
_diskNumberStart = 0;
_versionMadeByPlatform = CurrentZipPlatform;
_versionMadeBySpecification = ZipVersionNeededValues.Default;
_versionToExtract = ZipVersionNeededValues.Default; // this must happen before following two assignment
_generalPurposeBitFlag = 0;
CompressionMethod = CompressionMethodValues.Deflate;
_lastModified = DateTimeOffset.Now;
_compressedSize = 0; // we don't know these yet
_uncompressedSize = 0;
_externalFileAttr = 0;
_offsetOfLocalHeader = 0;
_storedOffsetOfCompressedData = null;
_crc32 = 0;
_compressedBytes = null;
_storedUncompressedData = null;
_currentlyOpenForWrite = false;
_everOpenedForWrite = false;
_outstandingWriteStream = null;
FullName = entryName;
_cdUnknownExtraFields = null;
_lhUnknownExtraFields = null;
_fileComment = null;
_compressionLevel = null;
if (_storedEntryNameBytes.Length > ushort.MaxValue)
throw new ArgumentException(SR.EntryNamesTooLong);
// grab the stream if we're in create mode
if (_archive.Mode == ZipArchiveMode.Create)
{
_archive.AcquireArchiveStream(this);
}
}
/// <summary>
/// The ZipArchive that this entry belongs to. If this entry has been deleted, this will return null.
/// </summary>
public ZipArchive Archive => _archive;
[CLSCompliant(false)]
public uint Crc32 => _crc32;
/// <summary>
/// The compressed size of the entry. If the archive that the entry belongs to is in Create mode, attempts to get this property will always throw an exception. If the archive that the entry belongs to is in update mode, this property will only be valid if the entry has not been opened.
/// </summary>
/// <exception cref="InvalidOperationException">This property is not available because the entry has been written to or modified.</exception>
public long CompressedLength
{
get
{
if (_everOpenedForWrite)
throw new InvalidOperationException(SR.LengthAfterWrite);
return _compressedSize;
}
}
public int ExternalAttributes
{
get
{
return (int)_externalFileAttr;
}
set
{
ThrowIfInvalidArchive();
_externalFileAttr = (uint)value;
}
}
/// <summary>
/// The relative path of the entry as stored in the Zip archive. Note that Zip archives allow any string to be the path of the entry, including invalid and absolute paths.
/// </summary>
public string FullName
{
get
{
return _storedEntryName;
}
private set
{
if (value == null)
throw new ArgumentNullException(nameof(FullName));
bool isUTF8;
_storedEntryNameBytes = EncodeEntryName(value, out isUTF8);
_storedEntryName = value;
if (isUTF8)
_generalPurposeBitFlag |= BitFlagValues.UnicodeFileName;
else
_generalPurposeBitFlag &= ~BitFlagValues.UnicodeFileName;
if (ParseFileName(value, _versionMadeByPlatform) == "")
VersionToExtractAtLeast(ZipVersionNeededValues.ExplicitDirectory);
}
}
/// <summary>
/// The last write time of the entry as stored in the Zip archive. When setting this property, the DateTime will be converted to the
/// Zip timestamp format, which supports a resolution of two seconds. If the data in the last write time field is not a valid Zip timestamp,
/// an indicator value of 1980 January 1 at midnight will be returned.
/// </summary>
/// <exception cref="NotSupportedException">An attempt to set this property was made, but the ZipArchive that this entry belongs to was
/// opened in read-only mode.</exception>
/// <exception cref="ArgumentOutOfRangeException">An attempt was made to set this property to a value that cannot be represented in the
/// Zip timestamp format. The earliest date/time that can be represented is 1980 January 1 0:00:00 (midnight), and the last date/time
/// that can be represented is 2107 December 31 23:59:58 (one second before midnight).</exception>
public DateTimeOffset LastWriteTime
{
get
{
return _lastModified;
}
set
{
ThrowIfInvalidArchive();
if (_archive.Mode == ZipArchiveMode.Read)
throw new NotSupportedException(SR.ReadOnlyArchive);
if (_archive.Mode == ZipArchiveMode.Create && _everOpenedForWrite)
throw new IOException(SR.FrozenAfterWrite);
if (value.DateTime.Year < ZipHelper.ValidZipDate_YearMin || value.DateTime.Year > ZipHelper.ValidZipDate_YearMax)
throw new ArgumentOutOfRangeException(nameof(value), SR.DateTimeOutOfRange);
_lastModified = value;
}
}
/// <summary>
/// The uncompressed size of the entry. This property is not valid in Create mode, and it is only valid in Update mode if the entry has not been opened.
/// </summary>
/// <exception cref="InvalidOperationException">This property is not available because the entry has been written to or modified.</exception>
public long Length
{
get
{
if (_everOpenedForWrite)
throw new InvalidOperationException(SR.LengthAfterWrite);
return _uncompressedSize;
}
}
/// <summary>
/// The filename of the entry. This is equivalent to the substring of Fullname that follows the final directory separator character.
/// </summary>
public string Name => ParseFileName(FullName, _versionMadeByPlatform);
/// <summary>
/// Deletes the entry from the archive.
/// </summary>
/// <exception cref="IOException">The entry is already open for reading or writing.</exception>
/// <exception cref="NotSupportedException">The ZipArchive that this entry belongs to was opened in a mode other than ZipArchiveMode.Update. </exception>
/// <exception cref="ObjectDisposedException">The ZipArchive that this entry belongs to has been disposed.</exception>
public void Delete()
{
if (_archive == null)
return;
if (_currentlyOpenForWrite)
throw new IOException(SR.DeleteOpenEntry);
if (_archive.Mode != ZipArchiveMode.Update)
throw new NotSupportedException(SR.DeleteOnlyInUpdate);
_archive.ThrowIfDisposed();
_archive.RemoveEntry(this);
_archive = null!;
UnloadStreams();
}
/// <summary>
/// Opens the entry. If the archive that the entry belongs to was opened in Read mode, the returned stream will be readable, and it may or may not be seekable. If Create mode, the returned stream will be writable and not seekable. If Update mode, the returned stream will be readable, writable, seekable, and support SetLength.
/// </summary>
/// <returns>A Stream that represents the contents of the entry.</returns>
/// <exception cref="IOException">The entry is already currently open for writing. -or- The entry has been deleted from the archive. -or- The archive that this entry belongs to was opened in ZipArchiveMode.Create, and this entry has already been written to once.</exception>
/// <exception cref="InvalidDataException">The entry is missing from the archive or is corrupt and cannot be read. -or- The entry has been compressed using a compression method that is not supported.</exception>
/// <exception cref="ObjectDisposedException">The ZipArchive that this entry belongs to has been disposed.</exception>
public Stream Open()
{
ThrowIfInvalidArchive();
switch (_archive.Mode)
{
case ZipArchiveMode.Read:
return OpenInReadMode(checkOpenable: true);
case ZipArchiveMode.Create:
return OpenInWriteMode();
case ZipArchiveMode.Update:
default:
Debug.Assert(_archive.Mode == ZipArchiveMode.Update);
return OpenInUpdateMode();
}
}
/// <summary>
/// Returns the FullName of the entry.
/// </summary>
/// <returns>FullName of the entry</returns>
public override string ToString()
{
return FullName;
}
// Only allow opening ZipArchives with large ZipArchiveEntries in update mode when running in a 64-bit process.
// This is for compatibility with old behavior that threw an exception for all process bitnesses, because this
// will not work in a 32-bit process.
private static readonly bool s_allowLargeZipArchiveEntriesInUpdateMode = IntPtr.Size > 4;
internal bool EverOpenedForWrite => _everOpenedForWrite;
private long OffsetOfCompressedData
{
get
{
if (_storedOffsetOfCompressedData == null)
{
Debug.Assert(_archive.ArchiveReader != null);
_archive.ArchiveStream.Seek(_offsetOfLocalHeader, SeekOrigin.Begin);
// by calling this, we are using local header _storedEntryNameBytes.Length and extraFieldLength
// to find start of data, but still using central directory size information
if (!ZipLocalFileHeader.TrySkipBlock(_archive.ArchiveReader))
throw new InvalidDataException(SR.LocalFileHeaderCorrupt);
_storedOffsetOfCompressedData = _archive.ArchiveStream.Position;
}
return _storedOffsetOfCompressedData.Value;
}
}
private MemoryStream UncompressedData
{
get
{
if (_storedUncompressedData == null)
{
// this means we have never opened it before
// if _uncompressedSize > int.MaxValue, it's still okay, because MemoryStream will just
// grow as data is copied into it
_storedUncompressedData = new MemoryStream((int)_uncompressedSize);
if (_originallyInArchive)
{
using (Stream decompressor = OpenInReadMode(false))
{
try
{
decompressor.CopyTo(_storedUncompressedData);
}
catch (InvalidDataException)
{
// this is the case where the archive say the entry is deflate, but deflateStream
// throws an InvalidDataException. This property should only be getting accessed in
// Update mode, so we want to make sure _storedUncompressedData stays null so
// that later when we dispose the archive, this entry loads the compressedBytes, and
// copies them straight over
_storedUncompressedData.Dispose();
_storedUncompressedData = null;
_currentlyOpenForWrite = false;
_everOpenedForWrite = false;
throw;
}
}
}
// if they start modifying it and the compression method is not "store", we should make sure it will get deflated
if (CompressionMethod != CompressionMethodValues.Stored)
{
CompressionMethod = CompressionMethodValues.Deflate;
}
}
return _storedUncompressedData;
}
}
private CompressionMethodValues CompressionMethod
{
get { return _storedCompressionMethod; }
set
{
if (value == CompressionMethodValues.Deflate)
VersionToExtractAtLeast(ZipVersionNeededValues.Deflate);
else if (value == CompressionMethodValues.Deflate64)
VersionToExtractAtLeast(ZipVersionNeededValues.Deflate64);
_storedCompressionMethod = value;
}
}
private string DecodeEntryName(byte[] entryNameBytes)
{
Debug.Assert(entryNameBytes != null);
Encoding readEntryNameEncoding;
if ((_generalPurposeBitFlag & BitFlagValues.UnicodeFileName) == 0)
{
readEntryNameEncoding = _archive == null ?
Encoding.UTF8 :
_archive.EntryNameEncoding ?? Encoding.UTF8;
}
else
{
readEntryNameEncoding = Encoding.UTF8;
}
return readEntryNameEncoding.GetString(entryNameBytes);
}
private byte[] EncodeEntryName(string entryName, out bool isUTF8)
{
Debug.Assert(entryName != null);
Encoding writeEntryNameEncoding;
if (_archive != null && _archive.EntryNameEncoding != null)
writeEntryNameEncoding = _archive.EntryNameEncoding;
else
writeEntryNameEncoding = ZipHelper.RequiresUnicode(entryName) ? Encoding.UTF8 : Encoding.ASCII;
isUTF8 = writeEntryNameEncoding.Equals(Encoding.UTF8);
return writeEntryNameEncoding.GetBytes(entryName);
}
// does almost everything you need to do to forget about this entry
// writes the local header/data, gets rid of all the data,
// closes all of the streams except for the very outermost one that
// the user holds on to and is responsible for closing
//
// after calling this, and only after calling this can we be guaranteed
// that we are reading to write the central directory
//
// should only throw an exception in extremely exceptional cases because it is called from dispose
internal void WriteAndFinishLocalEntry()
{
CloseStreams();
WriteLocalFileHeaderAndDataIfNeeded();
UnloadStreams();
}
// should only throw an exception in extremely exceptional cases because it is called from dispose
internal void WriteCentralDirectoryFileHeader()
{
// This part is simple, because we should definitely know the sizes by this time
BinaryWriter writer = new BinaryWriter(_archive.ArchiveStream);
// _entryname only gets set when we read in or call moveTo. MoveTo does a check, and
// reading in should not be able to produce an entryname longer than ushort.MaxValue
Debug.Assert(_storedEntryNameBytes.Length <= ushort.MaxValue);
// decide if we need the Zip64 extra field:
Zip64ExtraField zip64ExtraField = new Zip64ExtraField();
uint compressedSizeTruncated, uncompressedSizeTruncated, offsetOfLocalHeaderTruncated;
bool zip64Needed = false;
if (SizesTooLarge()
#if DEBUG_FORCE_ZIP64
|| _archive._forceZip64
#endif
)
{
zip64Needed = true;
compressedSizeTruncated = ZipHelper.Mask32Bit;
uncompressedSizeTruncated = ZipHelper.Mask32Bit;
// If we have one of the sizes, the other must go in there as speced for LH, but not necessarily for CH, but we do it anyways
zip64ExtraField.CompressedSize = _compressedSize;
zip64ExtraField.UncompressedSize = _uncompressedSize;
}
else
{
compressedSizeTruncated = (uint)_compressedSize;
uncompressedSizeTruncated = (uint)_uncompressedSize;
}
if (_offsetOfLocalHeader > uint.MaxValue
#if DEBUG_FORCE_ZIP64
|| _archive._forceZip64
#endif
)
{
zip64Needed = true;
offsetOfLocalHeaderTruncated = ZipHelper.Mask32Bit;
// If we have one of the sizes, the other must go in there as speced for LH, but not necessarily for CH, but we do it anyways
zip64ExtraField.LocalHeaderOffset = _offsetOfLocalHeader;
}
else
{
offsetOfLocalHeaderTruncated = (uint)_offsetOfLocalHeader;
}
if (zip64Needed)
VersionToExtractAtLeast(ZipVersionNeededValues.Zip64);
// determine if we can fit zip64 extra field and original extra fields all in
int bigExtraFieldLength = (zip64Needed ? zip64ExtraField.TotalSize : 0)
+ (_cdUnknownExtraFields != null ? ZipGenericExtraField.TotalSize(_cdUnknownExtraFields) : 0);
ushort extraFieldLength;
if (bigExtraFieldLength > ushort.MaxValue)
{
extraFieldLength = (ushort)(zip64Needed ? zip64ExtraField.TotalSize : 0);
_cdUnknownExtraFields = null;
}
else
{
extraFieldLength = (ushort)bigExtraFieldLength;
}
writer.Write(ZipCentralDirectoryFileHeader.SignatureConstant); // Central directory file header signature (4 bytes)
writer.Write((byte)_versionMadeBySpecification); // Version made by Specification (version) (1 byte)
writer.Write((byte)CurrentZipPlatform); // Version made by Compatibility (type) (1 byte)
writer.Write((ushort)_versionToExtract); // Minimum version needed to extract (2 bytes)
writer.Write((ushort)_generalPurposeBitFlag); // General Purpose bit flag (2 bytes)
writer.Write((ushort)CompressionMethod); // The Compression method (2 bytes)
writer.Write(ZipHelper.DateTimeToDosTime(_lastModified.DateTime)); // File last modification time and date (4 bytes)
writer.Write(_crc32); // CRC-32 (4 bytes)
writer.Write(compressedSizeTruncated); // Compressed Size (4 bytes)
writer.Write(uncompressedSizeTruncated); // Uncompressed Size (4 bytes)
writer.Write((ushort)_storedEntryNameBytes.Length); // File Name Length (2 bytes)
writer.Write(extraFieldLength); // Extra Field Length (2 bytes)
// This should hold because of how we read it originally in ZipCentralDirectoryFileHeader:
Debug.Assert((_fileComment == null) || (_fileComment.Length <= ushort.MaxValue));
writer.Write(_fileComment != null ? (ushort)_fileComment.Length : (ushort)0); // file comment length
writer.Write((ushort)0); // disk number start
writer.Write((ushort)0); // internal file attributes
writer.Write(_externalFileAttr); // external file attributes
writer.Write(offsetOfLocalHeaderTruncated); // offset of local header
writer.Write(_storedEntryNameBytes);
// write extra fields
if (zip64Needed)
zip64ExtraField.WriteBlock(_archive.ArchiveStream);
if (_cdUnknownExtraFields != null)
ZipGenericExtraField.WriteAllBlocks(_cdUnknownExtraFields, _archive.ArchiveStream);
if (_fileComment != null)
writer.Write(_fileComment);
}
// returns false if fails, will get called on every entry before closing in update mode
// can throw InvalidDataException
internal bool LoadLocalHeaderExtraFieldAndCompressedBytesIfNeeded()
{
// we should have made this exact call in _archive.Init through ThrowIfOpenable
Debug.Assert(IsOpenable(false, true, out string? message));
// load local header's extra fields. it will be null if we couldn't read for some reason
if (_originallyInArchive)
{
_archive.ArchiveStream.Seek(_offsetOfLocalHeader, SeekOrigin.Begin);
Debug.Assert(_archive.ArchiveReader != null);
_lhUnknownExtraFields = ZipLocalFileHeader.GetExtraFields(_archive.ArchiveReader);
}
if (!_everOpenedForWrite && _originallyInArchive)
{
// we know that it is openable at this point
_compressedBytes = new byte[(_compressedSize / MaxSingleBufferSize) + 1][];
for (int i = 0; i < _compressedBytes.Length - 1; i++)
{
_compressedBytes[i] = new byte[MaxSingleBufferSize];
}
_compressedBytes[_compressedBytes.Length - 1] = new byte[_compressedSize % MaxSingleBufferSize];
_archive.ArchiveStream.Seek(OffsetOfCompressedData, SeekOrigin.Begin);
for (int i = 0; i < _compressedBytes.Length - 1; i++)
{
ZipHelper.ReadBytes(_archive.ArchiveStream, _compressedBytes[i], MaxSingleBufferSize);
}
ZipHelper.ReadBytes(_archive.ArchiveStream, _compressedBytes[_compressedBytes.Length - 1], (int)(_compressedSize % MaxSingleBufferSize));
}
return true;
}
internal void ThrowIfNotOpenable(bool needToUncompress, bool needToLoadIntoMemory)
{
if (!IsOpenable(needToUncompress, needToLoadIntoMemory, out string? message))
throw new InvalidDataException(message);
}
private CheckSumAndSizeWriteStream GetDataCompressor(Stream backingStream, bool leaveBackingStreamOpen, EventHandler? onClose)
{
// stream stack: backingStream -> DeflateStream -> CheckSumWriteStream
// By default we compress with deflate, except if compression level is set to NoCompression then stored is used.
// Stored is also used for empty files, but we don't actually call through this function for that - we just write the stored value in the header
// Deflate64 is not supported on all platforms
Debug.Assert(CompressionMethod == CompressionMethodValues.Deflate
|| CompressionMethod == CompressionMethodValues.Stored);
bool isIntermediateStream = true;
Stream compressorStream;
switch (CompressionMethod)
{
case CompressionMethodValues.Stored:
compressorStream = backingStream;
isIntermediateStream = false;
break;
case CompressionMethodValues.Deflate:
case CompressionMethodValues.Deflate64:
default:
compressorStream = new DeflateStream(backingStream, _compressionLevel ?? CompressionLevel.Optimal, leaveBackingStreamOpen);
break;
}
bool leaveCompressorStreamOpenOnClose = leaveBackingStreamOpen && !isIntermediateStream;
var checkSumStream = new CheckSumAndSizeWriteStream(
compressorStream,
backingStream,
leaveCompressorStreamOpenOnClose,
this,
onClose,
(long initialPosition, long currentPosition, uint checkSum, Stream backing, ZipArchiveEntry thisRef, EventHandler? closeHandler) =>
{
thisRef._crc32 = checkSum;
thisRef._uncompressedSize = currentPosition;
thisRef._compressedSize = backing.Position - initialPosition;
closeHandler?.Invoke(thisRef, EventArgs.Empty);
});
return checkSumStream;
}
private Stream GetDataDecompressor(Stream compressedStreamToRead)
{
Stream? uncompressedStream = null;
switch (CompressionMethod)
{
case CompressionMethodValues.Deflate:
uncompressedStream = new DeflateStream(compressedStreamToRead, CompressionMode.Decompress, _uncompressedSize);
break;
case CompressionMethodValues.Deflate64:
uncompressedStream = new DeflateManagedStream(compressedStreamToRead, CompressionMethodValues.Deflate64, _uncompressedSize);
break;
case CompressionMethodValues.Stored:
default:
// we can assume that only deflate/deflate64/stored are allowed because we assume that
// IsOpenable is checked before this function is called
Debug.Assert(CompressionMethod == CompressionMethodValues.Stored);
uncompressedStream = compressedStreamToRead;
break;
}
return uncompressedStream;
}
private Stream OpenInReadMode(bool checkOpenable)
{
if (checkOpenable)
ThrowIfNotOpenable(needToUncompress: true, needToLoadIntoMemory: false);
Stream compressedStream = new SubReadStream(_archive.ArchiveStream, OffsetOfCompressedData, _compressedSize);
return GetDataDecompressor(compressedStream);
}
private Stream OpenInWriteMode()
{
if (_everOpenedForWrite)
throw new IOException(SR.CreateModeWriteOnceAndOneEntryAtATime);
// we assume that if another entry grabbed the archive stream, that it set this entry's _everOpenedForWrite property to true by calling WriteLocalFileHeaderIfNeeed
_archive.DebugAssertIsStillArchiveStreamOwner(this);
_everOpenedForWrite = true;
CheckSumAndSizeWriteStream crcSizeStream = GetDataCompressor(_archive.ArchiveStream, true, (object? o, EventArgs e) =>
{
// release the archive stream
var entry = (ZipArchiveEntry)o!;
entry._archive.ReleaseArchiveStream(entry);
entry._outstandingWriteStream = null;
});
_outstandingWriteStream = new DirectToArchiveWriterStream(crcSizeStream, this);
return new WrappedStream(baseStream: _outstandingWriteStream, closeBaseStream: true);
}
private Stream OpenInUpdateMode()
{
if (_currentlyOpenForWrite)
throw new IOException(SR.UpdateModeOneStream);
ThrowIfNotOpenable(needToUncompress: true, needToLoadIntoMemory: true);
_everOpenedForWrite = true;
_currentlyOpenForWrite = true;
// always put it at the beginning for them
UncompressedData.Seek(0, SeekOrigin.Begin);
return new WrappedStream(UncompressedData, this, thisRef =>
{
// once they close, we know uncompressed length, but still not compressed length
// so we don't fill in any size information
// those fields get figured out when we call GetCompressor as we write it to
// the actual archive
thisRef!._currentlyOpenForWrite = false;
});
}
private bool IsOpenable(bool needToUncompress, bool needToLoadIntoMemory, out string? message)
{
message = null;
if (_originallyInArchive)
{
if (needToUncompress)
{
if (CompressionMethod != CompressionMethodValues.Stored &&
CompressionMethod != CompressionMethodValues.Deflate &&
CompressionMethod != CompressionMethodValues.Deflate64)
{
switch (CompressionMethod)
{
case CompressionMethodValues.BZip2:
case CompressionMethodValues.LZMA:
message = SR.Format(SR.UnsupportedCompressionMethod, CompressionMethod.ToString());
break;
default:
message = SR.UnsupportedCompression;
break;
}
return false;
}
}
if (_diskNumberStart != _archive.NumberOfThisDisk)
{
message = SR.SplitSpanned;
return false;
}
if (_offsetOfLocalHeader > _archive.ArchiveStream.Length)
{
message = SR.LocalFileHeaderCorrupt;
return false;
}
Debug.Assert(_archive.ArchiveReader != null);
_archive.ArchiveStream.Seek(_offsetOfLocalHeader, SeekOrigin.Begin);
if (needToUncompress && !needToLoadIntoMemory)
{
if (!ZipLocalFileHeader.TryValidateBlock(_archive.ArchiveReader, this))
{
message = SR.LocalFileHeaderCorrupt;
return false;
}
}
else
{
if (!ZipLocalFileHeader.TrySkipBlock(_archive.ArchiveReader))
{
message = SR.LocalFileHeaderCorrupt;
return false;
}
}
// when this property gets called, some duplicated work
if (OffsetOfCompressedData + _compressedSize > _archive.ArchiveStream.Length)
{
message = SR.LocalFileHeaderCorrupt;
return false;
}
// This limitation originally existed because a) it is unreasonable to load > 4GB into memory
// but also because the stream reading functions make it hard. This has been updated to handle
// this scenario in a 64-bit process using multiple buffers, delivered first as an OOB for
// compatibility.
if (needToLoadIntoMemory)
{
if (_compressedSize > int.MaxValue)
{
if (!s_allowLargeZipArchiveEntriesInUpdateMode)
{
message = SR.EntryTooLarge;
return false;
}
}
}
}
return true;
}
private bool SizesTooLarge() => _compressedSize > uint.MaxValue || _uncompressedSize > uint.MaxValue;
// return value is true if we allocated an extra field for 64 bit headers, un/compressed size
private bool WriteLocalFileHeader(bool isEmptyFile)
{
BinaryWriter writer = new BinaryWriter(_archive.ArchiveStream);
// _entryname only gets set when we read in or call moveTo. MoveTo does a check, and
// reading in should not be able to produce an entryname longer than ushort.MaxValue
Debug.Assert(_storedEntryNameBytes.Length <= ushort.MaxValue);
// decide if we need the Zip64 extra field:
Zip64ExtraField zip64ExtraField = new Zip64ExtraField();
bool zip64Used = false;
uint compressedSizeTruncated, uncompressedSizeTruncated;
// if we already know that we have an empty file don't worry about anything, just do a straight shot of the header
if (isEmptyFile)
{
CompressionMethod = CompressionMethodValues.Stored;
compressedSizeTruncated = 0;
uncompressedSizeTruncated = 0;
Debug.Assert(_compressedSize == 0);
Debug.Assert(_uncompressedSize == 0);
Debug.Assert(_crc32 == 0);
}
else
{
// if we have a non-seekable stream, don't worry about sizes at all, and just set the right bit
// if we are using the data descriptor, then sizes and crc should be set to 0 in the header
if (_archive.Mode == ZipArchiveMode.Create && _archive.ArchiveStream.CanSeek == false && !isEmptyFile)
{
_generalPurposeBitFlag |= BitFlagValues.DataDescriptor;
zip64Used = false;
compressedSizeTruncated = 0;
uncompressedSizeTruncated = 0;
// the crc should not have been set if we are in create mode, but clear it just to be sure
Debug.Assert(_crc32 == 0);
}
else // if we are not in streaming mode, we have to decide if we want to write zip64 headers
{
// We are in seekable mode so we will not need to write a data descriptor
_generalPurposeBitFlag &= ~BitFlagValues.DataDescriptor;
if (SizesTooLarge()
#if DEBUG_FORCE_ZIP64
|| (_archive._forceZip64 && _archive.Mode == ZipArchiveMode.Update)
#endif
)
{
zip64Used = true;
compressedSizeTruncated = ZipHelper.Mask32Bit;
uncompressedSizeTruncated = ZipHelper.Mask32Bit;
// prepare Zip64 extra field object. If we have one of the sizes, the other must go in there
zip64ExtraField.CompressedSize = _compressedSize;
zip64ExtraField.UncompressedSize = _uncompressedSize;
VersionToExtractAtLeast(ZipVersionNeededValues.Zip64);
}
else
{
zip64Used = false;
compressedSizeTruncated = (uint)_compressedSize;
uncompressedSizeTruncated = (uint)_uncompressedSize;
}
}
}
// save offset
_offsetOfLocalHeader = writer.BaseStream.Position;
// calculate extra field. if zip64 stuff + original extraField aren't going to fit, dump the original extraField, because this is more important
int bigExtraFieldLength = (zip64Used ? zip64ExtraField.TotalSize : 0)
+ (_lhUnknownExtraFields != null ? ZipGenericExtraField.TotalSize(_lhUnknownExtraFields) : 0);
ushort extraFieldLength;
if (bigExtraFieldLength > ushort.MaxValue)
{
extraFieldLength = (ushort)(zip64Used ? zip64ExtraField.TotalSize : 0);
_lhUnknownExtraFields = null;
}
else
{
extraFieldLength = (ushort)bigExtraFieldLength;
}
// write header
writer.Write(ZipLocalFileHeader.SignatureConstant);
writer.Write((ushort)_versionToExtract);
writer.Write((ushort)_generalPurposeBitFlag);
writer.Write((ushort)CompressionMethod);
writer.Write(ZipHelper.DateTimeToDosTime(_lastModified.DateTime)); // uint
writer.Write(_crc32); // uint
writer.Write(compressedSizeTruncated); // uint
writer.Write(uncompressedSizeTruncated); // uint
writer.Write((ushort)_storedEntryNameBytes.Length);
writer.Write(extraFieldLength); // ushort
writer.Write(_storedEntryNameBytes);
if (zip64Used)
zip64ExtraField.WriteBlock(_archive.ArchiveStream);
if (_lhUnknownExtraFields != null)
ZipGenericExtraField.WriteAllBlocks(_lhUnknownExtraFields, _archive.ArchiveStream);
return zip64Used;
}
private void WriteLocalFileHeaderAndDataIfNeeded()
{
// _storedUncompressedData gets frozen here, and is what gets written to the file
if (_storedUncompressedData != null || _compressedBytes != null)
{
if (_storedUncompressedData != null)
{
_uncompressedSize = _storedUncompressedData.Length;
//The compressor fills in CRC and sizes
//The DirectToArchiveWriterStream writes headers and such
using (Stream entryWriter = new DirectToArchiveWriterStream(
GetDataCompressor(_archive.ArchiveStream, true, null),
this))
{
_storedUncompressedData.Seek(0, SeekOrigin.Begin);
_storedUncompressedData.CopyTo(entryWriter);
_storedUncompressedData.Dispose();
_storedUncompressedData = null;
}
}
else
{
if (_uncompressedSize == 0)
{
// reset size to ensure proper central directory size header
_compressedSize = 0;
}
WriteLocalFileHeader(isEmptyFile: _uncompressedSize == 0);
// according to ZIP specs, zero-byte files MUST NOT include file data
if (_uncompressedSize != 0)
{
Debug.Assert(_compressedBytes != null);
foreach (byte[] compressedBytes in _compressedBytes)
{
_archive.ArchiveStream.Write(compressedBytes, 0, compressedBytes.Length);
}
}
}
}
else // there is no data in the file, but if we are in update mode, we still need to write a header
{
if (_archive.Mode == ZipArchiveMode.Update || !_everOpenedForWrite)
{
_everOpenedForWrite = true;
WriteLocalFileHeader(isEmptyFile: true);
}
}
}
// Using _offsetOfLocalHeader, seeks back to where CRC and sizes should be in the header,
// writes them, then seeks back to where you started
// Assumes that the stream is currently at the end of the data
private void WriteCrcAndSizesInLocalHeader(bool zip64HeaderUsed)
{
long finalPosition = _archive.ArchiveStream.Position;
BinaryWriter writer = new BinaryWriter(_archive.ArchiveStream);
bool zip64Needed = SizesTooLarge()
#if DEBUG_FORCE_ZIP64
|| _archive._forceZip64
#endif
;
bool pretendStreaming = zip64Needed && !zip64HeaderUsed;
uint compressedSizeTruncated = zip64Needed ? ZipHelper.Mask32Bit : (uint)_compressedSize;
uint uncompressedSizeTruncated = zip64Needed ? ZipHelper.Mask32Bit : (uint)_uncompressedSize;
// first step is, if we need zip64, but didn't allocate it, pretend we did a stream write, because
// we can't go back and give ourselves the space that the extra field needs.
// we do this by setting the correct property in the bit flag to indicate we have a data descriptor
// and setting the version to Zip64 to indicate that descriptor contains 64-bit values
if (pretendStreaming)
{
VersionToExtractAtLeast(ZipVersionNeededValues.Zip64);
_generalPurposeBitFlag |= BitFlagValues.DataDescriptor;
_archive.ArchiveStream.Seek(_offsetOfLocalHeader + ZipLocalFileHeader.OffsetToVersionFromHeaderStart,
SeekOrigin.Begin);
writer.Write((ushort)_versionToExtract);
writer.Write((ushort)_generalPurposeBitFlag);
}
// next step is fill out the 32-bit size values in the normal header. we can't assume that
// they are correct. we also write the CRC
_archive.ArchiveStream.Seek(_offsetOfLocalHeader + ZipLocalFileHeader.OffsetToCrcFromHeaderStart,
SeekOrigin.Begin);
if (!pretendStreaming)
{
writer.Write(_crc32);
writer.Write(compressedSizeTruncated);
writer.Write(uncompressedSizeTruncated);
}
else // but if we are pretending to stream, we want to fill in with zeroes
{
writer.Write((uint)0);
writer.Write((uint)0);
writer.Write((uint)0);
}
// next step: if we wrote the 64 bit header initially, a different implementation might
// try to read it, even if the 32-bit size values aren't masked. thus, we should always put the
// correct size information in there. note that order of uncomp/comp is switched, and these are
// 64-bit values
// also, note that in order for this to be correct, we have to insure that the zip64 extra field
// is always the first extra field that is written
if (zip64HeaderUsed)
{
_archive.ArchiveStream.Seek(_offsetOfLocalHeader + ZipLocalFileHeader.SizeOfLocalHeader
+ _storedEntryNameBytes.Length + Zip64ExtraField.OffsetToFirstField,
SeekOrigin.Begin);
writer.Write(_uncompressedSize);
writer.Write(_compressedSize);
}
// now go to the where we were. assume that this is the end of the data
_archive.ArchiveStream.Seek(finalPosition, SeekOrigin.Begin);
// if we are pretending we did a stream write, we want to write the data descriptor out
// the data descriptor can have 32-bit sizes or 64-bit sizes. In this case, we always use
// 64-bit sizes
if (pretendStreaming)
{
writer.Write(_crc32);
writer.Write(_compressedSize);
writer.Write(_uncompressedSize);
}
}
private void WriteDataDescriptor()
{
// We enter here because we cannot seek, so the data descriptor bit should be on
Debug.Assert((_generalPurposeBitFlag & BitFlagValues.DataDescriptor) != 0);
// data descriptor can be 32-bit or 64-bit sizes. 32-bit is more compatible, so use that if possible
// signature is optional but recommended by the spec
BinaryWriter writer = new BinaryWriter(_archive.ArchiveStream);
writer.Write(ZipLocalFileHeader.DataDescriptorSignature);
writer.Write(_crc32);
if (SizesTooLarge())
{
writer.Write(_compressedSize);
writer.Write(_uncompressedSize);
}
else
{
writer.Write((uint)_compressedSize);
writer.Write((uint)_uncompressedSize);
}
}
private void UnloadStreams()
{
if (_storedUncompressedData != null)
_storedUncompressedData.Dispose();
_compressedBytes = null;
_outstandingWriteStream = null;
}
private void CloseStreams()
{
// if the user left the stream open, close the underlying stream for them
if (_outstandingWriteStream != null)
{
_outstandingWriteStream.Dispose();
}
}
private void VersionToExtractAtLeast(ZipVersionNeededValues value)
{
if (_versionToExtract < value)
{
_versionToExtract = value;
}
if (_versionMadeBySpecification < value)
{
_versionMadeBySpecification = value;
}
}
private void ThrowIfInvalidArchive()
{
if (_archive == null)
throw new InvalidOperationException(SR.DeletedEntry);
_archive.ThrowIfDisposed();
}
/// <summary>
/// Gets the file name of the path based on Windows path separator characters
/// </summary>
private static string GetFileName_Windows(string path)
{
int length = path.Length;
for (int i = length; --i >= 0;)
{
char ch = path[i];
if (ch == '\\' || ch == '/' || ch == ':')
return path.Substring(i + 1);
}
return path;
}
/// <summary>
/// Gets the file name of the path based on Unix path separator characters
/// </summary>
private static string GetFileName_Unix(string path)
{
int length = path.Length;
for (int i = length; --i >= 0;)
if (path[i] == '/')
return path.Substring(i + 1);
return path;
}
private sealed partial class DirectToArchiveWriterStream : Stream
{
private long _position;
private readonly CheckSumAndSizeWriteStream _crcSizeStream;
private bool _everWritten;
private bool _isDisposed;
private readonly ZipArchiveEntry _entry;
private bool _usedZip64inLH;
private bool _canWrite;
// makes the assumption that somewhere down the line, crcSizeStream is eventually writing directly to the archive
// this class calls other functions on ZipArchiveEntry that write directly to the archive
public DirectToArchiveWriterStream(CheckSumAndSizeWriteStream crcSizeStream, ZipArchiveEntry entry)
{
_position = 0;
_crcSizeStream = crcSizeStream;
_everWritten = false;
_isDisposed = false;
_entry = entry;
_usedZip64inLH = false;
_canWrite = true;
}
public override long Length
{
get
{
ThrowIfDisposed();
throw new NotSupportedException(SR.SeekingNotSupported);
}
}
public override long Position
{
get
{
ThrowIfDisposed();
return _position;
}
set
{
ThrowIfDisposed();
throw new NotSupportedException(SR.SeekingNotSupported);
}
}
public override bool CanRead => false;
public override bool CanSeek => false;
public override bool CanWrite => _canWrite;
private void ThrowIfDisposed()
{
if (_isDisposed)
throw new ObjectDisposedException(GetType().ToString(), SR.HiddenStreamName);
}
public override int Read(byte[] buffer, int offset, int count)
{
ThrowIfDisposed();
throw new NotSupportedException(SR.ReadingNotSupported);
}
public override long Seek(long offset, SeekOrigin origin)
{
ThrowIfDisposed();
throw new NotSupportedException(SR.SeekingNotSupported);
}
public override void SetLength(long value)
{
ThrowIfDisposed();
throw new NotSupportedException(SR.SetLengthRequiresSeekingAndWriting);
}
// careful: assumes that write is the only way to write to the stream, if writebyte/beginwrite are implemented
// they must set _everWritten, etc.
public override void Write(byte[] buffer, int offset, int count)
{
//we can't pass the argument checking down a level
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentNeedNonNegative);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentNeedNonNegative);
if ((buffer.Length - offset) < count)
throw new ArgumentException(SR.OffsetLengthInvalid);
ThrowIfDisposed();
Debug.Assert(CanWrite);
// if we're not actually writing anything, we don't want to trigger the header
if (count == 0)
return;
if (!_everWritten)
{
_everWritten = true;
// write local header, we are good to go
_usedZip64inLH = _entry.WriteLocalFileHeader(isEmptyFile: false);
}
_crcSizeStream.Write(buffer, offset, count);
_position += count;
}
public override void Flush()
{
ThrowIfDisposed();
Debug.Assert(CanWrite);
_crcSizeStream.Flush();
}
protected override void Dispose(bool disposing)
{
if (disposing && !_isDisposed)
{
_crcSizeStream.Dispose(); // now we have size/crc info
if (!_everWritten)
{
// write local header, no data, so we use stored
_entry.WriteLocalFileHeader(isEmptyFile: true);
}
else
{
// go back and finish writing
if (_entry._archive.ArchiveStream.CanSeek)
// finish writing local header if we have seek capabilities
_entry.WriteCrcAndSizesInLocalHeader(_usedZip64inLH);
else
// write out data descriptor if we don't have seek capabilities
_entry.WriteDataDescriptor();
}
_canWrite = false;
_isDisposed = true;
}
base.Dispose(disposing);
}
}
[Flags]
internal enum BitFlagValues : ushort { DataDescriptor = 0x8, UnicodeFileName = 0x800 }
internal enum CompressionMethodValues : ushort { Stored = 0x0, Deflate = 0x8, Deflate64 = 0x9, BZip2 = 0xC, LZMA = 0xE }
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
namespace System.Collections.Immutable
{
/// <summary>
/// An immutable stack.
/// </summary>
/// <typeparam name="T">The type of element stored by the stack.</typeparam>
[DebuggerDisplay("IsEmpty = {IsEmpty}; Top = {_head}")]
[DebuggerTypeProxy(typeof(ImmutableStackDebuggerProxy<>))]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Ignored")]
public sealed class ImmutableStack<T> : IImmutableStack<T>
{
/// <summary>
/// The singleton empty stack.
/// </summary>
/// <remarks>
/// Additional instances representing the empty stack may exist on deserialized stacks.
/// </remarks>
private static readonly ImmutableStack<T> s_EmptyField = new ImmutableStack<T>();
/// <summary>
/// The element on the top of the stack.
/// </summary>
private readonly T _head;
/// <summary>
/// A stack that contains the rest of the elements (under the top element).
/// </summary>
private readonly ImmutableStack<T> _tail;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableStack{T}"/> class
/// that acts as the empty stack.
/// </summary>
private ImmutableStack()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableStack{T}"/> class.
/// </summary>
/// <param name="head">The head element on the stack.</param>
/// <param name="tail">The rest of the elements on the stack.</param>
private ImmutableStack(T head, ImmutableStack<T> tail)
{
Requires.NotNull(tail, "tail");
_head = head;
_tail = tail;
}
/// <summary>
/// Gets the empty stack, upon which all stacks are built.
/// </summary>
public static ImmutableStack<T> Empty
{
get
{
Contract.Ensures(Contract.Result<ImmutableStack<T>>() != null);
Contract.Ensures(Contract.Result<ImmutableStack<T>>().IsEmpty);
Contract.Assume(s_EmptyField.IsEmpty);
return s_EmptyField;
}
}
/// <summary>
/// Gets the empty stack, upon which all stacks are built.
/// </summary>
public ImmutableStack<T> Clear()
{
Contract.Ensures(Contract.Result<ImmutableStack<T>>() != null);
Contract.Ensures(Contract.Result<ImmutableStack<T>>().IsEmpty);
Contract.Assume(s_EmptyField.IsEmpty);
return Empty;
}
/// <summary>
/// Gets an empty stack.
/// </summary>
IImmutableStack<T> IImmutableStack<T>.Clear()
{
return this.Clear();
}
/// <summary>
/// Gets a value indicating whether this instance is empty.
/// </summary>
/// <value>
/// <c>true</c> if this instance is empty; otherwise, <c>false</c>.
/// </value>
public bool IsEmpty
{
get { return _tail == null; }
}
/// <summary>
/// Gets the element on the top of the stack.
/// </summary>
/// <returns>
/// The element on the top of the stack.
/// </returns>
/// <exception cref="InvalidOperationException">Thrown when the stack is empty.</exception>
[Pure]
public T Peek()
{
if (this.IsEmpty)
{
throw new InvalidOperationException(SR.InvalidEmptyOperation);
}
return _head;
}
/// <summary>
/// Pushes an element onto a stack and returns the new stack.
/// </summary>
/// <param name="value">The element to push onto the stack.</param>
/// <returns>The new stack.</returns>
[Pure]
public ImmutableStack<T> Push(T value)
{
Contract.Ensures(Contract.Result<ImmutableStack<T>>() != null);
Contract.Ensures(!Contract.Result<ImmutableStack<T>>().IsEmpty);
return new ImmutableStack<T>(value, this);
}
/// <summary>
/// Pushes an element onto a stack and returns the new stack.
/// </summary>
/// <param name="value">The element to push onto the stack.</param>
/// <returns>The new stack.</returns>
[Pure]
IImmutableStack<T> IImmutableStack<T>.Push(T value)
{
return this.Push(value);
}
/// <summary>
/// Returns a stack that lacks the top element on this stack.
/// </summary>
/// <returns>A stack; never <c>null</c></returns>
/// <exception cref="InvalidOperationException">Thrown when the stack is empty.</exception>
[Pure]
public ImmutableStack<T> Pop()
{
Contract.Ensures(Contract.Result<ImmutableStack<T>>() != null);
if (this.IsEmpty)
{
throw new InvalidOperationException(SR.InvalidEmptyOperation);
}
return _tail;
}
/// <summary>
/// Pops the top element off the stack.
/// </summary>
/// <param name="value">The value that was removed from the stack.</param>
/// <returns>
/// A stack; never <c>null</c>
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#")]
[Pure]
public ImmutableStack<T> Pop(out T value)
{
value = this.Peek();
return this.Pop();
}
/// <summary>
/// Returns a stack that lacks the top element on this stack.
/// </summary>
/// <returns>A stack; never <c>null</c></returns>
/// <exception cref="InvalidOperationException">Thrown when the stack is empty.</exception>
[Pure]
IImmutableStack<T> IImmutableStack<T>.Pop()
{
return this.Pop();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// An <see cref="Enumerator"/> that can be used to iterate through the collection.
/// </returns>
[Pure]
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
[Pure]
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new EnumeratorObject(this);
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
[Pure]
IEnumerator IEnumerable.GetEnumerator()
{
return new EnumeratorObject(this);
}
/// <summary>
/// Reverses the order of a stack.
/// </summary>
/// <returns>The reversed stack.</returns>
[Pure]
internal ImmutableStack<T> Reverse()
{
Contract.Ensures(Contract.Result<ImmutableStack<T>>() != null);
Contract.Ensures(Contract.Result<ImmutableStack<T>>().IsEmpty == this.IsEmpty);
var r = this.Clear();
for (ImmutableStack<T> f = this; !f.IsEmpty; f = f.Pop())
{
r = r.Push(f.Peek());
}
return r;
}
/// <summary>
/// Enumerates a stack with no memory allocations.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public struct Enumerator
{
/// <summary>
/// The original stack being enumerated.
/// </summary>
private readonly ImmutableStack<T> _originalStack;
/// <summary>
/// The remaining stack not yet enumerated.
/// </summary>
private ImmutableStack<T> _remainingStack;
/// <summary>
/// Initializes a new instance of the <see cref="Enumerator"/> struct.
/// </summary>
/// <param name="stack">The stack to enumerator.</param>
internal Enumerator(ImmutableStack<T> stack)
{
Requires.NotNull(stack, "stack");
_originalStack = stack;
_remainingStack = null;
}
/// <summary>
/// Gets the current element.
/// </summary>
public T Current
{
get
{
if (_remainingStack == null || _remainingStack.IsEmpty)
{
throw new InvalidOperationException();
}
else
{
return _remainingStack.Peek();
}
}
}
/// <summary>
/// Moves to the first or next element.
/// </summary>
/// <returns>A value indicating whether there are any more elements.</returns>
public bool MoveNext()
{
if (_remainingStack == null)
{
// initial move
_remainingStack = _originalStack;
}
else if (!_remainingStack.IsEmpty)
{
_remainingStack = _remainingStack.Pop();
}
return !_remainingStack.IsEmpty;
}
}
/// <summary>
/// Enumerates a stack with no memory allocations.
/// </summary>
private class EnumeratorObject : IEnumerator<T>
{
/// <summary>
/// The original stack being enumerated.
/// </summary>
private readonly ImmutableStack<T> _originalStack;
/// <summary>
/// The remaining stack not yet enumerated.
/// </summary>
private ImmutableStack<T> _remainingStack;
/// <summary>
/// A flag indicating whether this enumerator has been disposed.
/// </summary>
private bool _disposed;
/// <summary>
/// Initializes a new instance of the <see cref="EnumeratorObject"/> class.
/// </summary>
/// <param name="stack">The stack to enumerator.</param>
internal EnumeratorObject(ImmutableStack<T> stack)
{
Requires.NotNull(stack, "stack");
_originalStack = stack;
}
/// <summary>
/// Gets the current element.
/// </summary>
public T Current
{
get
{
this.ThrowIfDisposed();
if (_remainingStack == null || _remainingStack.IsEmpty)
{
throw new InvalidOperationException();
}
else
{
return _remainingStack.Peek();
}
}
}
/// <summary>
/// Gets the current element.
/// </summary>
object IEnumerator.Current
{
get { return this.Current; }
}
/// <summary>
/// Moves to the first or next element.
/// </summary>
/// <returns>A value indicating whether there are any more elements.</returns>
public bool MoveNext()
{
this.ThrowIfDisposed();
if (_remainingStack == null)
{
// initial move
_remainingStack = _originalStack;
}
else if (!_remainingStack.IsEmpty)
{
_remainingStack = _remainingStack.Pop();
}
return !_remainingStack.IsEmpty;
}
/// <summary>
/// Resets the position to just before the first element in the list.
/// </summary>
public void Reset()
{
this.ThrowIfDisposed();
_remainingStack = null;
}
/// <summary>
/// Disposes this instance.
/// </summary>
public void Dispose()
{
_disposed = true;
}
/// <summary>
/// Throws an <see cref="ObjectDisposedException"/> if this
/// enumerator has already been disposed.
/// </summary>
private void ThrowIfDisposed()
{
if (_disposed)
{
Requires.FailObjectDisposed(this);
}
}
}
}
/// <summary>
/// A simple view of the immutable collection that the debugger can show to the developer.
/// </summary>
internal class ImmutableStackDebuggerProxy<T>
{
/// <summary>
/// The collection to be enumerated.
/// </summary>
private readonly ImmutableStack<T> _stack;
/// <summary>
/// The simple view of the collection.
/// </summary>
private T[] _contents;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableStackDebuggerProxy{T}"/> class.
/// </summary>
/// <param name="stack">The collection to display in the debugger</param>
public ImmutableStackDebuggerProxy(ImmutableStack<T> stack)
{
Requires.NotNull(stack, "stack");
_stack = stack;
}
/// <summary>
/// Gets a simple debugger-viewable collection.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public T[] Contents
{
get
{
if (_contents == null)
{
_contents = _stack.ToArray();
}
return _contents;
}
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using CookComputing.XmlRpc;
namespace XenAPI
{
/// <summary>
/// A virtual block device
/// First published in XenServer 4.0.
/// </summary>
public partial class VBD : XenObject<VBD>
{
public VBD()
{
}
public VBD(string uuid,
List<vbd_operations> allowed_operations,
Dictionary<string, vbd_operations> current_operations,
XenRef<VM> VM,
XenRef<VDI> VDI,
string device,
string userdevice,
bool bootable,
vbd_mode mode,
vbd_type type,
bool unpluggable,
bool storage_lock,
bool empty,
Dictionary<string, string> other_config,
bool currently_attached,
long status_code,
string status_detail,
Dictionary<string, string> runtime_properties,
string qos_algorithm_type,
Dictionary<string, string> qos_algorithm_params,
string[] qos_supported_algorithms,
XenRef<VBD_metrics> metrics)
{
this.uuid = uuid;
this.allowed_operations = allowed_operations;
this.current_operations = current_operations;
this.VM = VM;
this.VDI = VDI;
this.device = device;
this.userdevice = userdevice;
this.bootable = bootable;
this.mode = mode;
this.type = type;
this.unpluggable = unpluggable;
this.storage_lock = storage_lock;
this.empty = empty;
this.other_config = other_config;
this.currently_attached = currently_attached;
this.status_code = status_code;
this.status_detail = status_detail;
this.runtime_properties = runtime_properties;
this.qos_algorithm_type = qos_algorithm_type;
this.qos_algorithm_params = qos_algorithm_params;
this.qos_supported_algorithms = qos_supported_algorithms;
this.metrics = metrics;
}
/// <summary>
/// Creates a new VBD from a Proxy_VBD.
/// </summary>
/// <param name="proxy"></param>
public VBD(Proxy_VBD proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(VBD update)
{
uuid = update.uuid;
allowed_operations = update.allowed_operations;
current_operations = update.current_operations;
VM = update.VM;
VDI = update.VDI;
device = update.device;
userdevice = update.userdevice;
bootable = update.bootable;
mode = update.mode;
type = update.type;
unpluggable = update.unpluggable;
storage_lock = update.storage_lock;
empty = update.empty;
other_config = update.other_config;
currently_attached = update.currently_attached;
status_code = update.status_code;
status_detail = update.status_detail;
runtime_properties = update.runtime_properties;
qos_algorithm_type = update.qos_algorithm_type;
qos_algorithm_params = update.qos_algorithm_params;
qos_supported_algorithms = update.qos_supported_algorithms;
metrics = update.metrics;
}
internal void UpdateFromProxy(Proxy_VBD proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
allowed_operations = proxy.allowed_operations == null ? null : Helper.StringArrayToEnumList<vbd_operations>(proxy.allowed_operations);
current_operations = proxy.current_operations == null ? null : Maps.convert_from_proxy_string_vbd_operations(proxy.current_operations);
VM = proxy.VM == null ? null : XenRef<VM>.Create(proxy.VM);
VDI = proxy.VDI == null ? null : XenRef<VDI>.Create(proxy.VDI);
device = proxy.device == null ? null : (string)proxy.device;
userdevice = proxy.userdevice == null ? null : (string)proxy.userdevice;
bootable = (bool)proxy.bootable;
mode = proxy.mode == null ? (vbd_mode) 0 : (vbd_mode)Helper.EnumParseDefault(typeof(vbd_mode), (string)proxy.mode);
type = proxy.type == null ? (vbd_type) 0 : (vbd_type)Helper.EnumParseDefault(typeof(vbd_type), (string)proxy.type);
unpluggable = (bool)proxy.unpluggable;
storage_lock = (bool)proxy.storage_lock;
empty = (bool)proxy.empty;
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
currently_attached = (bool)proxy.currently_attached;
status_code = proxy.status_code == null ? 0 : long.Parse((string)proxy.status_code);
status_detail = proxy.status_detail == null ? null : (string)proxy.status_detail;
runtime_properties = proxy.runtime_properties == null ? null : Maps.convert_from_proxy_string_string(proxy.runtime_properties);
qos_algorithm_type = proxy.qos_algorithm_type == null ? null : (string)proxy.qos_algorithm_type;
qos_algorithm_params = proxy.qos_algorithm_params == null ? null : Maps.convert_from_proxy_string_string(proxy.qos_algorithm_params);
qos_supported_algorithms = proxy.qos_supported_algorithms == null ? new string[] {} : (string [])proxy.qos_supported_algorithms;
metrics = proxy.metrics == null ? null : XenRef<VBD_metrics>.Create(proxy.metrics);
}
public Proxy_VBD ToProxy()
{
Proxy_VBD result_ = new Proxy_VBD();
result_.uuid = (uuid != null) ? uuid : "";
result_.allowed_operations = (allowed_operations != null) ? Helper.ObjectListToStringArray(allowed_operations) : new string[] {};
result_.current_operations = Maps.convert_to_proxy_string_vbd_operations(current_operations);
result_.VM = (VM != null) ? VM : "";
result_.VDI = (VDI != null) ? VDI : "";
result_.device = (device != null) ? device : "";
result_.userdevice = (userdevice != null) ? userdevice : "";
result_.bootable = bootable;
result_.mode = vbd_mode_helper.ToString(mode);
result_.type = vbd_type_helper.ToString(type);
result_.unpluggable = unpluggable;
result_.storage_lock = storage_lock;
result_.empty = empty;
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
result_.currently_attached = currently_attached;
result_.status_code = status_code.ToString();
result_.status_detail = (status_detail != null) ? status_detail : "";
result_.runtime_properties = Maps.convert_to_proxy_string_string(runtime_properties);
result_.qos_algorithm_type = (qos_algorithm_type != null) ? qos_algorithm_type : "";
result_.qos_algorithm_params = Maps.convert_to_proxy_string_string(qos_algorithm_params);
result_.qos_supported_algorithms = qos_supported_algorithms;
result_.metrics = (metrics != null) ? metrics : "";
return result_;
}
/// <summary>
/// Creates a new VBD from a Hashtable.
/// </summary>
/// <param name="table"></param>
public VBD(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
allowed_operations = Helper.StringArrayToEnumList<vbd_operations>(Marshalling.ParseStringArray(table, "allowed_operations"));
current_operations = Maps.convert_from_proxy_string_vbd_operations(Marshalling.ParseHashTable(table, "current_operations"));
VM = Marshalling.ParseRef<VM>(table, "VM");
VDI = Marshalling.ParseRef<VDI>(table, "VDI");
device = Marshalling.ParseString(table, "device");
userdevice = Marshalling.ParseString(table, "userdevice");
bootable = Marshalling.ParseBool(table, "bootable");
mode = (vbd_mode)Helper.EnumParseDefault(typeof(vbd_mode), Marshalling.ParseString(table, "mode"));
type = (vbd_type)Helper.EnumParseDefault(typeof(vbd_type), Marshalling.ParseString(table, "type"));
unpluggable = Marshalling.ParseBool(table, "unpluggable");
storage_lock = Marshalling.ParseBool(table, "storage_lock");
empty = Marshalling.ParseBool(table, "empty");
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
currently_attached = Marshalling.ParseBool(table, "currently_attached");
status_code = Marshalling.ParseLong(table, "status_code");
status_detail = Marshalling.ParseString(table, "status_detail");
runtime_properties = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "runtime_properties"));
qos_algorithm_type = Marshalling.ParseString(table, "qos_algorithm_type");
qos_algorithm_params = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "qos_algorithm_params"));
qos_supported_algorithms = Marshalling.ParseStringArray(table, "qos_supported_algorithms");
metrics = Marshalling.ParseRef<VBD_metrics>(table, "metrics");
}
public bool DeepEquals(VBD other, bool ignoreCurrentOperations)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations))
return false;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._allowed_operations, other._allowed_operations) &&
Helper.AreEqual2(this._VM, other._VM) &&
Helper.AreEqual2(this._VDI, other._VDI) &&
Helper.AreEqual2(this._device, other._device) &&
Helper.AreEqual2(this._userdevice, other._userdevice) &&
Helper.AreEqual2(this._bootable, other._bootable) &&
Helper.AreEqual2(this._mode, other._mode) &&
Helper.AreEqual2(this._type, other._type) &&
Helper.AreEqual2(this._unpluggable, other._unpluggable) &&
Helper.AreEqual2(this._storage_lock, other._storage_lock) &&
Helper.AreEqual2(this._empty, other._empty) &&
Helper.AreEqual2(this._other_config, other._other_config) &&
Helper.AreEqual2(this._currently_attached, other._currently_attached) &&
Helper.AreEqual2(this._status_code, other._status_code) &&
Helper.AreEqual2(this._status_detail, other._status_detail) &&
Helper.AreEqual2(this._runtime_properties, other._runtime_properties) &&
Helper.AreEqual2(this._qos_algorithm_type, other._qos_algorithm_type) &&
Helper.AreEqual2(this._qos_algorithm_params, other._qos_algorithm_params) &&
Helper.AreEqual2(this._qos_supported_algorithms, other._qos_supported_algorithms) &&
Helper.AreEqual2(this._metrics, other._metrics);
}
public override string SaveChanges(Session session, string opaqueRef, VBD server)
{
if (opaqueRef == null)
{
Proxy_VBD p = this.ToProxy();
return session.proxy.vbd_create(session.uuid, p).parse();
}
else
{
if (!Helper.AreEqual2(_userdevice, server._userdevice))
{
VBD.set_userdevice(session, opaqueRef, _userdevice);
}
if (!Helper.AreEqual2(_bootable, server._bootable))
{
VBD.set_bootable(session, opaqueRef, _bootable);
}
if (!Helper.AreEqual2(_mode, server._mode))
{
VBD.set_mode(session, opaqueRef, _mode);
}
if (!Helper.AreEqual2(_type, server._type))
{
VBD.set_type(session, opaqueRef, _type);
}
if (!Helper.AreEqual2(_unpluggable, server._unpluggable))
{
VBD.set_unpluggable(session, opaqueRef, _unpluggable);
}
if (!Helper.AreEqual2(_other_config, server._other_config))
{
VBD.set_other_config(session, opaqueRef, _other_config);
}
if (!Helper.AreEqual2(_qos_algorithm_type, server._qos_algorithm_type))
{
VBD.set_qos_algorithm_type(session, opaqueRef, _qos_algorithm_type);
}
if (!Helper.AreEqual2(_qos_algorithm_params, server._qos_algorithm_params))
{
VBD.set_qos_algorithm_params(session, opaqueRef, _qos_algorithm_params);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static VBD get_record(Session session, string _vbd)
{
return new VBD((Proxy_VBD)session.proxy.vbd_get_record(session.uuid, (_vbd != null) ? _vbd : "").parse());
}
/// <summary>
/// Get a reference to the VBD instance with the specified UUID.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<VBD> get_by_uuid(Session session, string _uuid)
{
return XenRef<VBD>.Create(session.proxy.vbd_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse());
}
/// <summary>
/// Create a new VBD instance, and return its handle.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<VBD> create(Session session, VBD _record)
{
return XenRef<VBD>.Create(session.proxy.vbd_create(session.uuid, _record.ToProxy()).parse());
}
/// <summary>
/// Create a new VBD instance, and return its handle.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<Task> async_create(Session session, VBD _record)
{
return XenRef<Task>.Create(session.proxy.async_vbd_create(session.uuid, _record.ToProxy()).parse());
}
/// <summary>
/// Destroy the specified VBD instance.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static void destroy(Session session, string _vbd)
{
session.proxy.vbd_destroy(session.uuid, (_vbd != null) ? _vbd : "").parse();
}
/// <summary>
/// Destroy the specified VBD instance.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static XenRef<Task> async_destroy(Session session, string _vbd)
{
return XenRef<Task>.Create(session.proxy.async_vbd_destroy(session.uuid, (_vbd != null) ? _vbd : "").parse());
}
/// <summary>
/// Get the uuid field of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static string get_uuid(Session session, string _vbd)
{
return (string)session.proxy.vbd_get_uuid(session.uuid, (_vbd != null) ? _vbd : "").parse();
}
/// <summary>
/// Get the allowed_operations field of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static List<vbd_operations> get_allowed_operations(Session session, string _vbd)
{
return Helper.StringArrayToEnumList<vbd_operations>(session.proxy.vbd_get_allowed_operations(session.uuid, (_vbd != null) ? _vbd : "").parse());
}
/// <summary>
/// Get the current_operations field of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static Dictionary<string, vbd_operations> get_current_operations(Session session, string _vbd)
{
return Maps.convert_from_proxy_string_vbd_operations(session.proxy.vbd_get_current_operations(session.uuid, (_vbd != null) ? _vbd : "").parse());
}
/// <summary>
/// Get the VM field of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static XenRef<VM> get_VM(Session session, string _vbd)
{
return XenRef<VM>.Create(session.proxy.vbd_get_vm(session.uuid, (_vbd != null) ? _vbd : "").parse());
}
/// <summary>
/// Get the VDI field of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static XenRef<VDI> get_VDI(Session session, string _vbd)
{
return XenRef<VDI>.Create(session.proxy.vbd_get_vdi(session.uuid, (_vbd != null) ? _vbd : "").parse());
}
/// <summary>
/// Get the device field of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static string get_device(Session session, string _vbd)
{
return (string)session.proxy.vbd_get_device(session.uuid, (_vbd != null) ? _vbd : "").parse();
}
/// <summary>
/// Get the userdevice field of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static string get_userdevice(Session session, string _vbd)
{
return (string)session.proxy.vbd_get_userdevice(session.uuid, (_vbd != null) ? _vbd : "").parse();
}
/// <summary>
/// Get the bootable field of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static bool get_bootable(Session session, string _vbd)
{
return (bool)session.proxy.vbd_get_bootable(session.uuid, (_vbd != null) ? _vbd : "").parse();
}
/// <summary>
/// Get the mode field of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static vbd_mode get_mode(Session session, string _vbd)
{
return (vbd_mode)Helper.EnumParseDefault(typeof(vbd_mode), (string)session.proxy.vbd_get_mode(session.uuid, (_vbd != null) ? _vbd : "").parse());
}
/// <summary>
/// Get the type field of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static vbd_type get_type(Session session, string _vbd)
{
return (vbd_type)Helper.EnumParseDefault(typeof(vbd_type), (string)session.proxy.vbd_get_type(session.uuid, (_vbd != null) ? _vbd : "").parse());
}
/// <summary>
/// Get the unpluggable field of the given VBD.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static bool get_unpluggable(Session session, string _vbd)
{
return (bool)session.proxy.vbd_get_unpluggable(session.uuid, (_vbd != null) ? _vbd : "").parse();
}
/// <summary>
/// Get the storage_lock field of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static bool get_storage_lock(Session session, string _vbd)
{
return (bool)session.proxy.vbd_get_storage_lock(session.uuid, (_vbd != null) ? _vbd : "").parse();
}
/// <summary>
/// Get the empty field of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static bool get_empty(Session session, string _vbd)
{
return (bool)session.proxy.vbd_get_empty(session.uuid, (_vbd != null) ? _vbd : "").parse();
}
/// <summary>
/// Get the other_config field of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static Dictionary<string, string> get_other_config(Session session, string _vbd)
{
return Maps.convert_from_proxy_string_string(session.proxy.vbd_get_other_config(session.uuid, (_vbd != null) ? _vbd : "").parse());
}
/// <summary>
/// Get the currently_attached field of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static bool get_currently_attached(Session session, string _vbd)
{
return (bool)session.proxy.vbd_get_currently_attached(session.uuid, (_vbd != null) ? _vbd : "").parse();
}
/// <summary>
/// Get the status_code field of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static long get_status_code(Session session, string _vbd)
{
return long.Parse((string)session.proxy.vbd_get_status_code(session.uuid, (_vbd != null) ? _vbd : "").parse());
}
/// <summary>
/// Get the status_detail field of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static string get_status_detail(Session session, string _vbd)
{
return (string)session.proxy.vbd_get_status_detail(session.uuid, (_vbd != null) ? _vbd : "").parse();
}
/// <summary>
/// Get the runtime_properties field of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static Dictionary<string, string> get_runtime_properties(Session session, string _vbd)
{
return Maps.convert_from_proxy_string_string(session.proxy.vbd_get_runtime_properties(session.uuid, (_vbd != null) ? _vbd : "").parse());
}
/// <summary>
/// Get the qos/algorithm_type field of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static string get_qos_algorithm_type(Session session, string _vbd)
{
return (string)session.proxy.vbd_get_qos_algorithm_type(session.uuid, (_vbd != null) ? _vbd : "").parse();
}
/// <summary>
/// Get the qos/algorithm_params field of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static Dictionary<string, string> get_qos_algorithm_params(Session session, string _vbd)
{
return Maps.convert_from_proxy_string_string(session.proxy.vbd_get_qos_algorithm_params(session.uuid, (_vbd != null) ? _vbd : "").parse());
}
/// <summary>
/// Get the qos/supported_algorithms field of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static string[] get_qos_supported_algorithms(Session session, string _vbd)
{
return (string [])session.proxy.vbd_get_qos_supported_algorithms(session.uuid, (_vbd != null) ? _vbd : "").parse();
}
/// <summary>
/// Get the metrics field of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static XenRef<VBD_metrics> get_metrics(Session session, string _vbd)
{
return XenRef<VBD_metrics>.Create(session.proxy.vbd_get_metrics(session.uuid, (_vbd != null) ? _vbd : "").parse());
}
/// <summary>
/// Set the userdevice field of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
/// <param name="_userdevice">New value to set</param>
public static void set_userdevice(Session session, string _vbd, string _userdevice)
{
session.proxy.vbd_set_userdevice(session.uuid, (_vbd != null) ? _vbd : "", (_userdevice != null) ? _userdevice : "").parse();
}
/// <summary>
/// Set the bootable field of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
/// <param name="_bootable">New value to set</param>
public static void set_bootable(Session session, string _vbd, bool _bootable)
{
session.proxy.vbd_set_bootable(session.uuid, (_vbd != null) ? _vbd : "", _bootable).parse();
}
/// <summary>
/// Set the mode field of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
/// <param name="_mode">New value to set</param>
public static void set_mode(Session session, string _vbd, vbd_mode _mode)
{
session.proxy.vbd_set_mode(session.uuid, (_vbd != null) ? _vbd : "", vbd_mode_helper.ToString(_mode)).parse();
}
/// <summary>
/// Set the type field of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
/// <param name="_type">New value to set</param>
public static void set_type(Session session, string _vbd, vbd_type _type)
{
session.proxy.vbd_set_type(session.uuid, (_vbd != null) ? _vbd : "", vbd_type_helper.ToString(_type)).parse();
}
/// <summary>
/// Set the unpluggable field of the given VBD.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
/// <param name="_unpluggable">New value to set</param>
public static void set_unpluggable(Session session, string _vbd, bool _unpluggable)
{
session.proxy.vbd_set_unpluggable(session.uuid, (_vbd != null) ? _vbd : "", _unpluggable).parse();
}
/// <summary>
/// Set the other_config field of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _vbd, Dictionary<string, string> _other_config)
{
session.proxy.vbd_set_other_config(session.uuid, (_vbd != null) ? _vbd : "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _vbd, string _key, string _value)
{
session.proxy.vbd_add_to_other_config(session.uuid, (_vbd != null) ? _vbd : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given VBD. If the key is not in that Map, then do nothing.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _vbd, string _key)
{
session.proxy.vbd_remove_from_other_config(session.uuid, (_vbd != null) ? _vbd : "", (_key != null) ? _key : "").parse();
}
/// <summary>
/// Set the qos/algorithm_type field of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
/// <param name="_algorithm_type">New value to set</param>
public static void set_qos_algorithm_type(Session session, string _vbd, string _algorithm_type)
{
session.proxy.vbd_set_qos_algorithm_type(session.uuid, (_vbd != null) ? _vbd : "", (_algorithm_type != null) ? _algorithm_type : "").parse();
}
/// <summary>
/// Set the qos/algorithm_params field of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
/// <param name="_algorithm_params">New value to set</param>
public static void set_qos_algorithm_params(Session session, string _vbd, Dictionary<string, string> _algorithm_params)
{
session.proxy.vbd_set_qos_algorithm_params(session.uuid, (_vbd != null) ? _vbd : "", Maps.convert_to_proxy_string_string(_algorithm_params)).parse();
}
/// <summary>
/// Add the given key-value pair to the qos/algorithm_params field of the given VBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_qos_algorithm_params(Session session, string _vbd, string _key, string _value)
{
session.proxy.vbd_add_to_qos_algorithm_params(session.uuid, (_vbd != null) ? _vbd : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the qos/algorithm_params field of the given VBD. If the key is not in that Map, then do nothing.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_qos_algorithm_params(Session session, string _vbd, string _key)
{
session.proxy.vbd_remove_from_qos_algorithm_params(session.uuid, (_vbd != null) ? _vbd : "", (_key != null) ? _key : "").parse();
}
/// <summary>
/// Remove the media from the device and leave it empty
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static void eject(Session session, string _vbd)
{
session.proxy.vbd_eject(session.uuid, (_vbd != null) ? _vbd : "").parse();
}
/// <summary>
/// Remove the media from the device and leave it empty
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static XenRef<Task> async_eject(Session session, string _vbd)
{
return XenRef<Task>.Create(session.proxy.async_vbd_eject(session.uuid, (_vbd != null) ? _vbd : "").parse());
}
/// <summary>
/// Insert new media into the device
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
/// <param name="_vdi">The new VDI to 'insert'</param>
public static void insert(Session session, string _vbd, string _vdi)
{
session.proxy.vbd_insert(session.uuid, (_vbd != null) ? _vbd : "", (_vdi != null) ? _vdi : "").parse();
}
/// <summary>
/// Insert new media into the device
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
/// <param name="_vdi">The new VDI to 'insert'</param>
public static XenRef<Task> async_insert(Session session, string _vbd, string _vdi)
{
return XenRef<Task>.Create(session.proxy.async_vbd_insert(session.uuid, (_vbd != null) ? _vbd : "", (_vdi != null) ? _vdi : "").parse());
}
/// <summary>
/// Hotplug the specified VBD, dynamically attaching it to the running VM
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static void plug(Session session, string _vbd)
{
session.proxy.vbd_plug(session.uuid, (_vbd != null) ? _vbd : "").parse();
}
/// <summary>
/// Hotplug the specified VBD, dynamically attaching it to the running VM
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static XenRef<Task> async_plug(Session session, string _vbd)
{
return XenRef<Task>.Create(session.proxy.async_vbd_plug(session.uuid, (_vbd != null) ? _vbd : "").parse());
}
/// <summary>
/// Hot-unplug the specified VBD, dynamically unattaching it from the running VM
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static void unplug(Session session, string _vbd)
{
session.proxy.vbd_unplug(session.uuid, (_vbd != null) ? _vbd : "").parse();
}
/// <summary>
/// Hot-unplug the specified VBD, dynamically unattaching it from the running VM
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static XenRef<Task> async_unplug(Session session, string _vbd)
{
return XenRef<Task>.Create(session.proxy.async_vbd_unplug(session.uuid, (_vbd != null) ? _vbd : "").parse());
}
/// <summary>
/// Forcibly unplug the specified VBD
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static void unplug_force(Session session, string _vbd)
{
session.proxy.vbd_unplug_force(session.uuid, (_vbd != null) ? _vbd : "").parse();
}
/// <summary>
/// Forcibly unplug the specified VBD
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static XenRef<Task> async_unplug_force(Session session, string _vbd)
{
return XenRef<Task>.Create(session.proxy.async_vbd_unplug_force(session.uuid, (_vbd != null) ? _vbd : "").parse());
}
/// <summary>
/// Throws an error if this VBD could not be attached to this VM if the VM were running. Intended for debugging.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static void assert_attachable(Session session, string _vbd)
{
session.proxy.vbd_assert_attachable(session.uuid, (_vbd != null) ? _vbd : "").parse();
}
/// <summary>
/// Throws an error if this VBD could not be attached to this VM if the VM were running. Intended for debugging.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vbd">The opaque_ref of the given vbd</param>
public static XenRef<Task> async_assert_attachable(Session session, string _vbd)
{
return XenRef<Task>.Create(session.proxy.async_vbd_assert_attachable(session.uuid, (_vbd != null) ? _vbd : "").parse());
}
/// <summary>
/// Return a list of all the VBDs known to the system.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<VBD>> get_all(Session session)
{
return XenRef<VBD>.Create(session.proxy.vbd_get_all(session.uuid).parse());
}
/// <summary>
/// Get all the VBD Records at once, in a single XML RPC call
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<VBD>, VBD> get_all_records(Session session)
{
return XenRef<VBD>.Create<Proxy_VBD>(session.proxy.vbd_get_all_records(session.uuid).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid;
/// <summary>
/// list of the operations allowed in this state. This list is advisory only and the server state may have changed by the time this field is read by a client.
/// </summary>
public virtual List<vbd_operations> allowed_operations
{
get { return _allowed_operations; }
set
{
if (!Helper.AreEqual(value, _allowed_operations))
{
_allowed_operations = value;
Changed = true;
NotifyPropertyChanged("allowed_operations");
}
}
}
private List<vbd_operations> _allowed_operations;
/// <summary>
/// links each of the running tasks using this object (by reference) to a current_operation enum which describes the nature of the task.
/// </summary>
public virtual Dictionary<string, vbd_operations> current_operations
{
get { return _current_operations; }
set
{
if (!Helper.AreEqual(value, _current_operations))
{
_current_operations = value;
Changed = true;
NotifyPropertyChanged("current_operations");
}
}
}
private Dictionary<string, vbd_operations> _current_operations;
/// <summary>
/// the virtual machine
/// </summary>
public virtual XenRef<VM> VM
{
get { return _VM; }
set
{
if (!Helper.AreEqual(value, _VM))
{
_VM = value;
Changed = true;
NotifyPropertyChanged("VM");
}
}
}
private XenRef<VM> _VM;
/// <summary>
/// the virtual disk
/// </summary>
public virtual XenRef<VDI> VDI
{
get { return _VDI; }
set
{
if (!Helper.AreEqual(value, _VDI))
{
_VDI = value;
Changed = true;
NotifyPropertyChanged("VDI");
}
}
}
private XenRef<VDI> _VDI;
/// <summary>
/// device seen by the guest e.g. hda1
/// </summary>
public virtual string device
{
get { return _device; }
set
{
if (!Helper.AreEqual(value, _device))
{
_device = value;
Changed = true;
NotifyPropertyChanged("device");
}
}
}
private string _device;
/// <summary>
/// user-friendly device name e.g. 0,1,2,etc.
/// </summary>
public virtual string userdevice
{
get { return _userdevice; }
set
{
if (!Helper.AreEqual(value, _userdevice))
{
_userdevice = value;
Changed = true;
NotifyPropertyChanged("userdevice");
}
}
}
private string _userdevice;
/// <summary>
/// true if this VBD is bootable
/// </summary>
public virtual bool bootable
{
get { return _bootable; }
set
{
if (!Helper.AreEqual(value, _bootable))
{
_bootable = value;
Changed = true;
NotifyPropertyChanged("bootable");
}
}
}
private bool _bootable;
/// <summary>
/// the mode the VBD should be mounted with
/// </summary>
public virtual vbd_mode mode
{
get { return _mode; }
set
{
if (!Helper.AreEqual(value, _mode))
{
_mode = value;
Changed = true;
NotifyPropertyChanged("mode");
}
}
}
private vbd_mode _mode;
/// <summary>
/// how the VBD will appear to the guest (e.g. disk or CD)
/// </summary>
public virtual vbd_type type
{
get { return _type; }
set
{
if (!Helper.AreEqual(value, _type))
{
_type = value;
Changed = true;
NotifyPropertyChanged("type");
}
}
}
private vbd_type _type;
/// <summary>
/// true if this VBD will support hot-unplug
/// First published in XenServer 4.1.
/// </summary>
public virtual bool unpluggable
{
get { return _unpluggable; }
set
{
if (!Helper.AreEqual(value, _unpluggable))
{
_unpluggable = value;
Changed = true;
NotifyPropertyChanged("unpluggable");
}
}
}
private bool _unpluggable;
/// <summary>
/// true if a storage level lock was acquired
/// </summary>
public virtual bool storage_lock
{
get { return _storage_lock; }
set
{
if (!Helper.AreEqual(value, _storage_lock))
{
_storage_lock = value;
Changed = true;
NotifyPropertyChanged("storage_lock");
}
}
}
private bool _storage_lock;
/// <summary>
/// if true this represents an empty drive
/// </summary>
public virtual bool empty
{
get { return _empty; }
set
{
if (!Helper.AreEqual(value, _empty))
{
_empty = value;
Changed = true;
NotifyPropertyChanged("empty");
}
}
}
private bool _empty;
/// <summary>
/// additional configuration
/// </summary>
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config;
/// <summary>
/// is the device currently attached (erased on reboot)
/// </summary>
public virtual bool currently_attached
{
get { return _currently_attached; }
set
{
if (!Helper.AreEqual(value, _currently_attached))
{
_currently_attached = value;
Changed = true;
NotifyPropertyChanged("currently_attached");
}
}
}
private bool _currently_attached;
/// <summary>
/// error/success code associated with last attach-operation (erased on reboot)
/// </summary>
public virtual long status_code
{
get { return _status_code; }
set
{
if (!Helper.AreEqual(value, _status_code))
{
_status_code = value;
Changed = true;
NotifyPropertyChanged("status_code");
}
}
}
private long _status_code;
/// <summary>
/// error/success information associated with last attach-operation status (erased on reboot)
/// </summary>
public virtual string status_detail
{
get { return _status_detail; }
set
{
if (!Helper.AreEqual(value, _status_detail))
{
_status_detail = value;
Changed = true;
NotifyPropertyChanged("status_detail");
}
}
}
private string _status_detail;
/// <summary>
/// Device runtime properties
/// </summary>
public virtual Dictionary<string, string> runtime_properties
{
get { return _runtime_properties; }
set
{
if (!Helper.AreEqual(value, _runtime_properties))
{
_runtime_properties = value;
Changed = true;
NotifyPropertyChanged("runtime_properties");
}
}
}
private Dictionary<string, string> _runtime_properties;
/// <summary>
/// QoS algorithm to use
/// </summary>
public virtual string qos_algorithm_type
{
get { return _qos_algorithm_type; }
set
{
if (!Helper.AreEqual(value, _qos_algorithm_type))
{
_qos_algorithm_type = value;
Changed = true;
NotifyPropertyChanged("qos_algorithm_type");
}
}
}
private string _qos_algorithm_type;
/// <summary>
/// parameters for chosen QoS algorithm
/// </summary>
public virtual Dictionary<string, string> qos_algorithm_params
{
get { return _qos_algorithm_params; }
set
{
if (!Helper.AreEqual(value, _qos_algorithm_params))
{
_qos_algorithm_params = value;
Changed = true;
NotifyPropertyChanged("qos_algorithm_params");
}
}
}
private Dictionary<string, string> _qos_algorithm_params;
/// <summary>
/// supported QoS algorithms for this VBD
/// </summary>
public virtual string[] qos_supported_algorithms
{
get { return _qos_supported_algorithms; }
set
{
if (!Helper.AreEqual(value, _qos_supported_algorithms))
{
_qos_supported_algorithms = value;
Changed = true;
NotifyPropertyChanged("qos_supported_algorithms");
}
}
}
private string[] _qos_supported_algorithms;
/// <summary>
/// metrics associated with this VBD
/// </summary>
public virtual XenRef<VBD_metrics> metrics
{
get { return _metrics; }
set
{
if (!Helper.AreEqual(value, _metrics))
{
_metrics = value;
Changed = true;
NotifyPropertyChanged("metrics");
}
}
}
private XenRef<VBD_metrics> _metrics;
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Cetera.Compression;
using Cetera.Image;
using Cetera.IO;
using Cetera.Properties;
namespace Cetera.Font
{
public class BCFNT
{
static Lazy<BCFNT> StdFntLoader = new Lazy<BCFNT>(() => new BCFNT(new MemoryStream(GZip.Decompress(Resources.cbf_std_bcfnt))));
public static BCFNT StandardFont => StdFntLoader.Value;
[StructLayout(LayoutKind.Sequential, Pack = 1)]
[DebuggerDisplay("[{left}, {glyph_width}, {char_width}]")]
public struct CharWidthInfo
{
public sbyte left;
public byte glyph_width;
public byte char_width;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct CFNT
{
public uint magic;
public ushort endianness;
public short header_size;
public int version;
public int file_size;
public int num_blocks;
};
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct FINF
{
public uint magic;
public int section_size;
public byte font_type;
public byte line_feed;
public short alter_char_index;
public CharWidthInfo default_width;
public byte encoding;
public int tglp_offset;
public int cwdh_offset;
public int cmap_offset;
public byte height;
public byte width;
public byte ascent;
public byte reserved;
};
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct TGLP
{
public uint magic;
public int section_size;
public byte cell_width;
public byte cell_height;
public byte baseline_position;
public byte max_character_width;
public int sheet_size;
public short num_sheets;
public short sheet_image_format;
public short num_columns;
public short num_rows;
public short sheet_width;
public short sheet_height;
public int sheet_data_offset;
};
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)]
public struct CMAP
{
public uint magic;
public int section_size;
public char code_begin;
public char code_end;
public short mapping_method;
public short reserved;
public int next_offset;
};
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct CWDH
{
public uint magic;
public int section_size;
public short start_index;
public short end_index;
public int next_offset;
};
FINF finf;
TGLP tglp;
public Bitmap[] bmps;
ImageAttributes attr = new ImageAttributes();
List<CharWidthInfo> lstCWDH = new List<CharWidthInfo>();
Dictionary<char, int> dicCMAP = new Dictionary<char, int>();
public CharWidthInfo GetWidthInfo(char c) => lstCWDH[GetIndex(c)];
public int LineFeed => finf.line_feed;
int GetIndex(char c)
{
int result;
if (!dicCMAP.TryGetValue(c, out result))
dicCMAP.TryGetValue('?', out result);
return result;
}
public void SetColor(Color color)
{
attr.SetColorMatrix(new ColorMatrix(new[]
{
new[] { color.R / 255f, 0, 0, 0, 0 },
new[] { 0, color.G / 255f, 0, 0, 0 },
new[] { 0, 0, color.B / 255f, 0, 0 },
new[] { 0, 0, 0, 1f, 0 },
new[] { 0, 0, 0, 0, 1f }
}));
}
public void Draw(char c, Graphics g, float x, float y, float scaleX, float scaleY)
{
var index = GetIndex(c);
var widthInfo = lstCWDH[index];
int cellsPerSheet = tglp.num_rows * tglp.num_columns;
int sheetNum = index / cellsPerSheet;
int cellRow = (index % cellsPerSheet) / tglp.num_columns;
int cellCol = index % tglp.num_columns;
int xOffset = cellCol * (tglp.cell_width + 1);
int yOffset = cellRow * (tglp.cell_height + 1);
if (widthInfo.glyph_width > 0)
g.DrawImage(bmps[sheetNum],
new[] { new PointF(x + widthInfo.left * scaleX, y),
new PointF(x + (widthInfo.left + widthInfo.glyph_width) * scaleX, y),
new PointF(x + widthInfo.left * scaleX, y + tglp.cell_height * scaleY) },
new RectangleF(xOffset + 1, yOffset + 1, widthInfo.glyph_width, tglp.cell_height),
GraphicsUnit.Pixel,
attr);
}
public float MeasureString(string text, char stopChar, float scale = 1.0f)
{
return text.TakeWhile(c => c != stopChar).Sum(c => GetWidthInfo(c).char_width) * scale;
}
public BCFNT(Stream input)
{
using (var br = new BinaryReaderX(input))
{
// @todo: read as sections
br.ReadStruct<CFNT>();
finf = br.ReadStruct<FINF>();
// read TGLP
br.BaseStream.Position = finf.tglp_offset - 8;
tglp = br.ReadStruct<TGLP>();
// read image data
br.BaseStream.Position = tglp.sheet_data_offset;
int width = tglp.sheet_width;
int height = tglp.sheet_height;
bmps = Enumerable.Range(0, tglp.num_sheets).Select(_ => Image.Common.Load(br.ReadBytes(tglp.sheet_size), new ImageSettings
{
Width = width,
Height = height,
Format = ImageSettings.ConvertFormat(tglp.sheet_image_format)
})).ToArray();
// read CWDH
for (int offset = finf.cwdh_offset; offset != 0;)
{
br.BaseStream.Position = offset - 8;
var cwdh = br.ReadStruct<CWDH>();
for (int i = cwdh.start_index; i <= cwdh.end_index; i++)
lstCWDH.Add(br.ReadStruct<CharWidthInfo>());
offset = cwdh.next_offset;
}
// read CMAP
for (int offset = finf.cmap_offset; offset != 0;)
{
br.BaseStream.Position = offset - 8;
var cmap = br.ReadStruct<CMAP>();
switch (cmap.mapping_method)
{
case 0:
var charOffset = br.ReadUInt16();
for (char i = cmap.code_begin; i <= cmap.code_end; i++)
{
int idx = i - cmap.code_begin + charOffset;
dicCMAP[i] = idx < ushort.MaxValue ? idx : 0;
}
break;
case 1:
for (char i = cmap.code_begin; i <= cmap.code_end; i++)
{
int idx = br.ReadInt16();
if (idx != -1) dicCMAP[i] = idx;
}
break;
case 2:
var n = br.ReadUInt16();
for (int i = 0; i < n; i++)
{
char c = br.ReadChar();
int idx = br.ReadInt16();
if (idx != -1) dicCMAP[c] = idx;
}
break;
default:
throw new Exception("Unsupported mapping method");
}
offset = cmap.next_offset;
}
}
}
}
}
| |
// 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.Net.Sockets;
using System.Net.Test.Common;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.NetworkInformation.Tests
{
public class NetworkInterfaceBasicTest
{
private readonly ITestOutputHelper _log;
public NetworkInterfaceBasicTest()
{
_log = TestLogging.GetInstance();
}
[Fact]
public void BasicTest_GetNetworkInterfaces_AtLeastOne()
{
Assert.NotEqual<int>(0, NetworkInterface.GetAllNetworkInterfaces().Length);
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void BasicTest_AccessInstanceProperties_NoExceptions()
{
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
_log.WriteLine("- NetworkInterface -");
_log.WriteLine("Name: " + nic.Name);
_log.WriteLine("Description: " + nic.Description);
_log.WriteLine("ID: " + nic.Id);
_log.WriteLine("IsReceiveOnly: " + nic.IsReceiveOnly);
_log.WriteLine("Type: " + nic.NetworkInterfaceType);
_log.WriteLine("Status: " + nic.OperationalStatus);
_log.WriteLine("Speed: " + nic.Speed);
// Validate NIC speed overflow.
// We've found that certain WiFi adapters will return speed of -1 when not connected.
Assert.InRange(nic.Speed, nic.OperationalStatus != OperationalStatus.Down ? 0 : -1, long.MaxValue);
_log.WriteLine("SupportsMulticast: " + nic.SupportsMulticast);
_log.WriteLine("GetPhysicalAddress(): " + nic.GetPhysicalAddress());
}
}
[Fact]
[PlatformSpecific(PlatformID.Linux)]
public void BasicTest_AccessInstanceProperties_NoExceptions_Linux()
{
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
_log.WriteLine("- NetworkInterface -");
_log.WriteLine("Name: " + nic.Name);
string description = nic.Description;
Assert.False(string.IsNullOrEmpty(description), "NetworkInterface.Description should not be null or empty.");
_log.WriteLine("Description: " + description);
string id = nic.Id;
Assert.False(string.IsNullOrEmpty(id), "NetworkInterface.Id should not be null or empty.");
_log.WriteLine("ID: " + id);
Assert.Throws<PlatformNotSupportedException>(() => nic.IsReceiveOnly);
_log.WriteLine("Type: " + nic.NetworkInterfaceType);
_log.WriteLine("Status: " + nic.OperationalStatus);
try
{
_log.WriteLine("Speed: " + nic.Speed);
Assert.InRange(nic.Speed, 0, long.MaxValue);
}
// We cannot guarantee this works on all devices.
catch (PlatformNotSupportedException pnse)
{
_log.WriteLine(pnse.ToString());
}
_log.WriteLine("SupportsMulticast: " + nic.SupportsMulticast);
_log.WriteLine("GetPhysicalAddress(): " + nic.GetPhysicalAddress());
}
}
[Fact]
[PlatformSpecific(PlatformID.OSX)]
public void BasicTest_AccessInstanceProperties_NoExceptions_Osx()
{
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
_log.WriteLine("- NetworkInterface -");
_log.WriteLine("Name: " + nic.Name);
string description = nic.Description;
Assert.False(string.IsNullOrEmpty(description), "NetworkInterface.Description should not be null or empty.");
_log.WriteLine("Description: " + description);
string id = nic.Id;
Assert.False(string.IsNullOrEmpty(id), "NetworkInterface.Id should not be null or empty.");
_log.WriteLine("ID: " + id);
Assert.Throws<PlatformNotSupportedException>(() => nic.IsReceiveOnly);
_log.WriteLine("Type: " + nic.NetworkInterfaceType);
_log.WriteLine("Status: " + nic.OperationalStatus);
_log.WriteLine("Speed: " + nic.Speed);
Assert.InRange(nic.Speed, 0, long.MaxValue);
_log.WriteLine("SupportsMulticast: " + nic.SupportsMulticast);
_log.WriteLine("GetPhysicalAddress(): " + nic.GetPhysicalAddress());
}
}
[Fact]
[Trait("IPv4", "true")]
public void BasicTest_StaticLoopbackIndex_MatchesLoopbackNetworkInterface()
{
Assert.True(Capability.IPv4Support());
_log.WriteLine("Loopback IPv4 index: " + NetworkInterface.LoopbackInterfaceIndex);
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
foreach (UnicastIPAddressInformation unicast in nic.GetIPProperties().UnicastAddresses)
{
if (unicast.Address.Equals(IPAddress.Loopback))
{
Assert.Equal<int>(nic.GetIPProperties().GetIPv4Properties().Index,
NetworkInterface.LoopbackInterfaceIndex);
return; // Only check IPv4 loopback
}
}
}
}
[Fact]
[Trait("IPv4", "true")]
public void BasicTest_StaticLoopbackIndex_ExceptionIfV4NotSupported()
{
Assert.True(Capability.IPv4Support());
_log.WriteLine("Loopback IPv4 index: " + NetworkInterface.LoopbackInterfaceIndex);
}
[Fact]
[Trait("IPv6", "true")]
public void BasicTest_StaticIPv6LoopbackIndex_MatchesLoopbackNetworkInterface()
{
Assert.True(Capability.IPv6Support());
_log.WriteLine("Loopback IPv6 index: " + NetworkInterface.IPv6LoopbackInterfaceIndex);
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
foreach (UnicastIPAddressInformation unicast in nic.GetIPProperties().UnicastAddresses)
{
if (unicast.Address.Equals(IPAddress.IPv6Loopback))
{
Assert.Equal<int>(
nic.GetIPProperties().GetIPv6Properties().Index,
NetworkInterface.IPv6LoopbackInterfaceIndex);
return; // Only check IPv6 loopback.
}
}
}
}
[Fact]
[Trait("IPv6", "true")]
public void BasicTest_StaticIPv6LoopbackIndex_ExceptionIfV6NotSupported()
{
Assert.True(Capability.IPv6Support());
_log.WriteLine("Loopback IPv6 index: " + NetworkInterface.IPv6LoopbackInterfaceIndex);
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void BasicTest_GetIPInterfaceStatistics_Success()
{
// This API is not actually IPv4 specific.
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
IPInterfaceStatistics stats = nic.GetIPStatistics();
_log.WriteLine("- Stats for : " + nic.Name);
_log.WriteLine("BytesReceived: " + stats.BytesReceived);
_log.WriteLine("BytesSent: " + stats.BytesSent);
_log.WriteLine("IncomingPacketsDiscarded: " + stats.IncomingPacketsDiscarded);
_log.WriteLine("IncomingPacketsWithErrors: " + stats.IncomingPacketsWithErrors);
_log.WriteLine("IncomingUnknownProtocolPackets: " + stats.IncomingUnknownProtocolPackets);
_log.WriteLine("NonUnicastPacketsReceived: " + stats.NonUnicastPacketsReceived);
_log.WriteLine("NonUnicastPacketsSent: " + stats.NonUnicastPacketsSent);
_log.WriteLine("OutgoingPacketsDiscarded: " + stats.OutgoingPacketsDiscarded);
_log.WriteLine("OutgoingPacketsWithErrors: " + stats.OutgoingPacketsWithErrors);
_log.WriteLine("OutputQueueLength: " + stats.OutputQueueLength);
_log.WriteLine("UnicastPacketsReceived: " + stats.UnicastPacketsReceived);
_log.WriteLine("UnicastPacketsSent: " + stats.UnicastPacketsSent);
}
}
[Fact]
[PlatformSpecific(PlatformID.Linux)]
public void BasicTest_GetIPInterfaceStatistics_Success_Linux()
{
// This API is not actually IPv4 specific.
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
IPInterfaceStatistics stats = nic.GetIPStatistics();
_log.WriteLine("- Stats for : " + nic.Name);
_log.WriteLine("BytesReceived: " + stats.BytesReceived);
_log.WriteLine("BytesSent: " + stats.BytesSent);
_log.WriteLine("IncomingPacketsDiscarded: " + stats.IncomingPacketsDiscarded);
_log.WriteLine("IncomingPacketsWithErrors: " + stats.IncomingPacketsWithErrors);
Assert.Throws<PlatformNotSupportedException>(() => stats.IncomingUnknownProtocolPackets);
_log.WriteLine("NonUnicastPacketsReceived: " + stats.NonUnicastPacketsReceived);
Assert.Throws<PlatformNotSupportedException>(() => stats.NonUnicastPacketsSent);
_log.WriteLine("OutgoingPacketsDiscarded: " + stats.OutgoingPacketsDiscarded);
_log.WriteLine("OutgoingPacketsWithErrors: " + stats.OutgoingPacketsWithErrors);
_log.WriteLine("OutputQueueLength: " + stats.OutputQueueLength);
_log.WriteLine("UnicastPacketsReceived: " + stats.UnicastPacketsReceived);
_log.WriteLine("UnicastPacketsSent: " + stats.UnicastPacketsSent);
}
}
[Fact]
[PlatformSpecific(PlatformID.OSX)]
public void BasicTest_GetIPInterfaceStatistics_Success_OSX()
{
// This API is not actually IPv4 specific.
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
IPInterfaceStatistics stats = nic.GetIPStatistics();
_log.WriteLine("- Stats for : " + nic.Name);
_log.WriteLine("BytesReceived: " + stats.BytesReceived);
_log.WriteLine("BytesSent: " + stats.BytesSent);
_log.WriteLine("IncomingPacketsDiscarded: " + stats.IncomingPacketsDiscarded);
_log.WriteLine("IncomingPacketsWithErrors: " + stats.IncomingPacketsWithErrors);
_log.WriteLine("IncomingUnknownProtocolPackets: " + stats.IncomingUnknownProtocolPackets);
_log.WriteLine("NonUnicastPacketsReceived: " + stats.NonUnicastPacketsReceived);
_log.WriteLine("NonUnicastPacketsSent: " + stats.NonUnicastPacketsSent);
Assert.Throws<PlatformNotSupportedException>(() => stats.OutgoingPacketsDiscarded);
_log.WriteLine("OutgoingPacketsWithErrors: " + stats.OutgoingPacketsWithErrors);
_log.WriteLine("OutputQueueLength: " + stats.OutputQueueLength);
_log.WriteLine("UnicastPacketsReceived: " + stats.UnicastPacketsReceived);
_log.WriteLine("UnicastPacketsSent: " + stats.UnicastPacketsSent);
}
}
[Fact]
public void BasicTest_GetIsNetworkAvailable_Success()
{
Assert.True(NetworkInterface.GetIsNetworkAvailable());
}
[Theory]
[PlatformSpecific(~PlatformID.OSX)]
[InlineData(false)]
[InlineData(true)]
public async Task NetworkInterface_LoopbackInterfaceIndex_MatchesReceivedPackets(bool ipv6)
{
using (var client = new Socket(SocketType.Dgram, ProtocolType.Udp))
using (var server = new Socket(SocketType.Dgram, ProtocolType.Udp))
{
server.Bind(new IPEndPoint(ipv6 ? IPAddress.IPv6Loopback : IPAddress.Loopback, 0));
var serverEndPoint = (IPEndPoint)server.LocalEndPoint;
Task<SocketReceiveMessageFromResult> receivedTask =
server.ReceiveMessageFromAsync(new ArraySegment<byte>(new byte[1]), SocketFlags.None, serverEndPoint);
while (!receivedTask.IsCompleted)
{
client.SendTo(new byte[] { 42 }, serverEndPoint);
await Task.Delay(1);
}
Assert.Equal(
(await receivedTask).PacketInformation.Interface,
ipv6 ? NetworkInterface.IPv6LoopbackInterfaceIndex : NetworkInterface.LoopbackInterfaceIndex);
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using IndexFileNameFilter = Lucene.Net.Index.IndexFileNameFilter;
namespace Lucene.Net.Store
{
/// <summary>A Directory is a flat list of files. Files may be written once, when they
/// are created. Once a file is created it may only be opened for read, or
/// deleted. Random access is permitted both when reading and writing.
///
/// <p/> Java's i/o APIs not used directly, but rather all i/o is
/// through this API. This permits things such as: <list>
/// <item> implementation of RAM-based indices;</item>
/// <item> implementation indices stored in a database, via JDBC;</item>
/// <item> implementation of an index as a single file;</item>
/// </list>
///
/// Directory locking is implemented by an instance of <see cref="LockFactory" />
///, and can be changed for each Directory
/// instance using <see cref="SetLockFactory" />.
///
/// </summary>
//[Serializable] //Disabled for https://github.com/dotnet/standard/issues/300
public abstract class Directory : System.IDisposable
{
protected internal volatile bool isOpen = true;
/// <summary>Holds the LockFactory instance (implements locking for
/// this Directory instance).
/// </summary>
[NonSerialized]
protected internal LockFactory interalLockFactory;
/// <summary>Returns an array of strings, one for each file in the directory.</summary>
/// <exception cref="System.IO.IOException"></exception>
public abstract System.String[] ListAll();
/// <summary>Returns true iff a file with the given name exists. </summary>
public abstract bool FileExists(System.String name);
/// <summary>Returns the time the named file was last modified. </summary>
public abstract long FileModified(System.String name);
/// <summary>Set the modified time of an existing file to now. </summary>
public abstract void TouchFile(System.String name);
/// <summary>Removes an existing file in the directory. </summary>
public abstract void DeleteFile(System.String name);
/// <summary>Returns the length of a file in the directory. </summary>
public abstract long FileLength(System.String name);
/// <summary>Creates a new, empty file in the directory with the given name.
/// Returns a stream writing this file.
/// </summary>
public abstract IndexOutput CreateOutput(System.String name);
/// <summary>Ensure that any writes to this file are moved to
/// stable storage. Lucene uses this to properly commit
/// changes to the index, to prevent a machine/OS crash
/// from corrupting the index.
/// </summary>
public virtual void Sync(System.String name)
{
}
/// <summary>Returns a stream reading an existing file. </summary>
public abstract IndexInput OpenInput(System.String name);
/// <summary>Returns a stream reading an existing file, with the
/// specified read buffer size. The particular Directory
/// implementation may ignore the buffer size. Currently
/// the only Directory implementations that respect this
/// parameter are <see cref="FSDirectory" /> and <see cref="Lucene.Net.Index.CompoundFileReader" />
///.
/// </summary>
public virtual IndexInput OpenInput(System.String name, int bufferSize)
{
return OpenInput(name);
}
/// <summary>Construct a <see cref="Lock" />.</summary>
/// <param name="name">the name of the lock file
/// </param>
public virtual Lock MakeLock(System.String name)
{
return interalLockFactory.MakeLock(name);
}
/// <summary> Attempt to clear (forcefully unlock and remove) the
/// specified lock. Only call this at a time when you are
/// certain this lock is no longer in use.
/// </summary>
/// <param name="name">name of the lock to be cleared.
/// </param>
public virtual void ClearLock(System.String name)
{
if (interalLockFactory != null)
{
interalLockFactory.ClearLock(name);
}
}
[Obsolete("Use Dispose() instead")]
public void Close()
{
Dispose();
}
/// <summary>Closes the store. </summary>
public void Dispose()
{
Dispose(true);
}
protected abstract void Dispose(bool disposing);
/// <summary> Set the LockFactory that this Directory instance should
/// use for its locking implementation. Each * instance of
/// LockFactory should only be used for one directory (ie,
/// do not share a single instance across multiple
/// Directories).
///
/// </summary>
/// <param name="lockFactory">instance of <see cref="LockFactory" />.
/// </param>
public virtual void SetLockFactory(LockFactory lockFactory)
{
System.Diagnostics.Debug.Assert(lockFactory != null);
this.interalLockFactory = lockFactory;
lockFactory.LockPrefix = this.GetLockId();
}
/// <summary> Get the LockFactory that this Directory instance is
/// using for its locking implementation. Note that this
/// may be null for Directory implementations that provide
/// their own locking implementation.
/// </summary>
public virtual LockFactory LockFactory
{
get { return this.interalLockFactory; }
}
/// <summary> Return a string identifier that uniquely differentiates
/// this Directory instance from other Directory instances.
/// This ID should be the same if two Directory instances
/// (even in different JVMs and/or on different machines)
/// are considered "the same index". This is how locking
/// "scopes" to the right index.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
public virtual string GetLockId()
{
return ToString();
}
public override string ToString()
{
return base.ToString() + " lockFactory=" + LockFactory;
}
/// <summary> Copy contents of a directory src to a directory dest.
/// If a file in src already exists in dest then the
/// one in dest will be blindly overwritten.
///
/// <p/><b>NOTE:</b> the source directory cannot change
/// while this method is running. Otherwise the results
/// are undefined and you could easily hit a
/// FileNotFoundException.
///
/// <p/><b>NOTE:</b> this method only copies files that look
/// like index files (ie, have extensions matching the
/// known extensions of index files).
///
/// </summary>
/// <param name="src">source directory
/// </param>
/// <param name="dest">destination directory
/// </param>
/// <param name="closeDirSrc">if <c>true</c>, call <see cref="Close()" /> method on source directory
/// </param>
/// <throws> IOException </throws>
public static void Copy(Directory src, Directory dest, bool closeDirSrc)
{
System.String[] files = src.ListAll();
IndexFileNameFilter filter = IndexFileNameFilter.Filter;
byte[] buf = new byte[BufferedIndexOutput.BUFFER_SIZE];
for (int i = 0; i < files.Length; i++)
{
if (!filter.Accept(null, files[i]))
continue;
IndexOutput os = null;
IndexInput is_Renamed = null;
try
{
// create file in dest directory
os = dest.CreateOutput(files[i]);
// read current file
is_Renamed = src.OpenInput(files[i]);
// and copy to dest directory
long len = is_Renamed.Length();
long readCount = 0;
while (readCount < len)
{
int toRead = readCount + BufferedIndexOutput.BUFFER_SIZE > len?(int) (len - readCount):BufferedIndexOutput.BUFFER_SIZE;
is_Renamed.ReadBytes(buf, 0, toRead);
os.WriteBytes(buf, toRead);
readCount += toRead;
}
}
finally
{
// graceful cleanup
try
{
if (os != null)
os.Close();
}
finally
{
if (is_Renamed != null)
is_Renamed.Close();
}
}
}
if (closeDirSrc)
src.Close();
}
/// <throws> AlreadyClosedException if this Directory is closed </throws>
public /*protected internal*/ void EnsureOpen()
{
if (!isOpen)
throw new AlreadyClosedException("this Directory is closed");
}
public bool isOpen_ForNUnit
{
get { return isOpen; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
namespace DDay.iCal
{
/// <summary>
/// A list of objects that are keyed. This is similar to a
/// Dictionary<T,U> object, except
/// </summary>
#if !SILVERLIGHT
[Serializable]
#endif
public class KeyedList<T, U> :
IKeyedList<T, U> where T : IKeyedObject<U>
{
#region Private Fields
List<T> _Items = new List<T>();
#endregion
#region IKeyedList<T, U> Members
public event EventHandler<ObjectEventArgs<T>> ItemAdded;
public event EventHandler<ObjectEventArgs<T>> ItemRemoved;
protected void OnItemAdded(T obj)
{
if (ItemAdded != null)
ItemAdded(this, new ObjectEventArgs<T>(obj));
}
protected void OnItemRemoved(T obj)
{
if (ItemRemoved != null)
ItemRemoved(this, new ObjectEventArgs<T>(obj));
}
/// <summary>
/// Returns true if the list contains at least one
/// object with a matching key, false otherwise.
/// </summary>
public bool ContainsKey(U key)
{
return IndexOf(key) >= 0;
}
/// <summary>
/// Returns the index of the first object
/// with the matching key.
/// </summary>
public int IndexOf(U key)
{
return _Items.FindIndex(
delegate(T obj)
{
return object.Equals(obj.Key, key);
}
);
}
public int CountOf(U key)
{
return AllOf(key).Count;
}
public IList<T> AllOf(U key)
{
return _Items.FindAll(
delegate(T obj)
{
return object.Equals(obj.Key, key);
}
);
}
public T this[U key]
{
get
{
for (int i = 0; i < Count; i++)
{
T obj = _Items[i];
if (object.Equals(obj.Key, key))
return obj;
}
return default(T);
}
set
{
int index = IndexOf(key);
if (index >= 0)
{
OnItemRemoved(_Items[index]);
_Items[index] = value;
OnItemAdded(value);
}
else
{
Add(value);
}
}
}
public bool Remove(U key)
{
int index = IndexOf(key);
bool removed = false;
while (index >= 0)
{
T item = _Items[index];
RemoveAt(index);
OnItemRemoved(item);
removed = true;
index = IndexOf(key);
}
return removed;
}
#endregion
#region IKeyedList<T,U> Members
public T[] ToArray()
{
return _Items.ToArray();
}
#endregion
#region IList<T> Members
public int IndexOf(T item)
{
return _Items.IndexOf(item);
}
public void Insert(int index, T item)
{
_Items.Insert(index, item);
OnItemAdded(item);
}
public void RemoveAt(int index)
{
if (index >= 0 && index < Count)
{
T item = _Items[index];
_Items.RemoveAt(index);
OnItemRemoved(item);
}
}
public T this[int index]
{
get
{
return _Items[index];
}
set
{
if (index >= 0 && index < Count)
{
T item = _Items[index];
_Items[index] = value;
OnItemRemoved(item);
OnItemAdded(value);
}
}
}
#endregion
#region ICollection<T> Members
public void Add(T item)
{
_Items.Add(item);
OnItemAdded(item);
}
public void Clear()
{
foreach (T obj in _Items)
OnItemRemoved(obj);
_Items.Clear();
}
public bool Contains(T item)
{
return _Items.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
_Items.CopyTo(array, arrayIndex);
}
public int Count
{
get { return _Items.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(T item)
{
bool removed = _Items.Remove(item);
OnItemRemoved(item);
return removed;
}
#endregion
#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator()
{
return _Items.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return _Items.GetEnumerator();
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="CompilationLock.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
//#define MUTEXINSTRUMENTATION
namespace System.Web.Compilation {
using System;
using System.Threading;
using System.Globalization;
using System.Security.Principal;
using System.Web.Util;
using System.Web.Configuration;
using System.Runtime.InteropServices;
using System.Web.Management;
using System.Runtime.Versioning;
using System.Diagnostics;
using Debug = System.Web.Util.Debug;
internal sealed class CompilationMutex : IDisposable {
private String _name;
private String _comment;
#if MUTEXINSTRUMENTATION
// Used to keep track of the stack when the mutex is obtained
private string _stackTrace;
#endif
// ROTORTODO: replace unmanaged aspnet_isapi mutex with managed implementation
#if !FEATURE_PAL // No unmanaged aspnet_isapi mutex in Coriolis
private HandleRef _mutexHandle;
// Lock Status is used to drain out all worker threads out of Mutex ownership on
// app domain shutdown: -1 locked for good, 0 unlocked, N locked by a worker thread(s)
private int _lockStatus;
private bool _draining = false;
#endif // !FEATURE_PAL
internal CompilationMutex(String name, String comment) {
#if !FEATURE_PAL // No unmanaged aspnet_isapi mutex in Coriolis
// Attempt to get the mutex string from the registry (VSWhidbey 415795)
string mutexRandomName = (string) Misc.GetAspNetRegValue("CompilationMutexName",
null /*valueName*/, null /*defaultValue*/);
if (mutexRandomName != null) {
// If we were able to use the registry value, use it. Also, we need to prepend "Global\"
// to the mutex name, to make sure it can be shared between a terminal server session
// and IIS (VSWhidbey 307523).
_name += @"Global\" + name + "-" + mutexRandomName;
}
else {
// If we couldn't get the reg value, don't use it, and prepend "Local\" to the mutex
// name to make it local to the session (and hence prevent hijacking)
_name += @"Local\" + name;
}
_comment = comment;
Debug.Trace("Mutex", "Creating Mutex " + MutexDebugName);
_mutexHandle = new HandleRef(this, UnsafeNativeMethods.InstrumentedMutexCreate(_name));
if (_mutexHandle.Handle == IntPtr.Zero) {
Debug.Trace("Mutex", "Failed to create Mutex " + MutexDebugName);
throw new InvalidOperationException(SR.GetString(SR.CompilationMutex_Create));
}
Debug.Trace("Mutex", "Successfully created Mutex " + MutexDebugName);
#endif // !FEATURE_PAL
}
~CompilationMutex() {
Close();
}
void IDisposable.Dispose() {
Close();
System.GC.SuppressFinalize(this);
}
internal /*public*/ void Close() {
#if !FEATURE_PAL // No unmanaged aspnet_isapi mutex in Coriolis
if (_mutexHandle.Handle != IntPtr.Zero) {
UnsafeNativeMethods.InstrumentedMutexDelete(_mutexHandle);
_mutexHandle = new HandleRef(this, IntPtr.Zero);
}
#endif // !FEATURE_PAL
}
[ResourceExposure(ResourceScope.None)]
internal /*public*/ void WaitOne() {
#if !FEATURE_PAL // No unmanaged aspnet_isapi mutex in Coriolis
if (_mutexHandle.Handle == IntPtr.Zero)
throw new InvalidOperationException(SR.GetString(SR.CompilationMutex_Null));
// check the lock status
for (;;) {
int lockStatus = _lockStatus;
if (lockStatus == -1 || _draining)
throw new InvalidOperationException(SR.GetString(SR.CompilationMutex_Drained));
if (Interlocked.CompareExchange(ref _lockStatus, lockStatus+1, lockStatus) == lockStatus)
break; // got the lock
}
Debug.Trace("Mutex", "Waiting for mutex " + MutexDebugName);
if (UnsafeNativeMethods.InstrumentedMutexGetLock(_mutexHandle, -1) == -1) {
// failed to get the lock
Interlocked.Decrement(ref _lockStatus);
throw new InvalidOperationException(SR.GetString(SR.CompilationMutex_Failed));
}
#if MUTEXINSTRUMENTATION
// Remember the stack trace for debugging purpose
_stackTrace = (new StackTrace()).ToString();
#endif
Debug.Trace("Mutex", "Got mutex " + MutexDebugName);
#endif // !FEATURE_PAL
}
internal /*public*/ void ReleaseMutex() {
#if !FEATURE_PAL // No unmanaged aspnet_isapi mutex in Coriolis
if (_mutexHandle.Handle == IntPtr.Zero)
throw new InvalidOperationException(SR.GetString(SR.CompilationMutex_Null));
Debug.Trace("Mutex", "Releasing mutex " + MutexDebugName);
#if MUTEXINSTRUMENTATION
// Clear out the stack trace
_stackTrace = null;
#endif
if (UnsafeNativeMethods.InstrumentedMutexReleaseLock(_mutexHandle) != 0)
Interlocked.Decrement(ref _lockStatus);
#endif // !FEATURE_PAL
}
private String MutexDebugName {
get {
#if DBG
return (_comment != null) ? _name + " (" + _comment + ")" : _name;
#else
return _name;
#endif
}
}
}
internal static class CompilationLock {
private static CompilationMutex _mutex;
static CompilationLock() {
// Create the mutex (or just get it if another process created it).
// Make the mutex unique per application
int hashCode = ("CompilationLock" + HttpRuntime.AppDomainAppId.ToLower(CultureInfo.InvariantCulture)).GetHashCode();
_mutex = new CompilationMutex(
"CL" + hashCode.ToString("x", CultureInfo.InvariantCulture),
"CompilationLock for " + HttpRuntime.AppDomainAppVirtualPath);
}
internal static void GetLock(ref bool gotLock) {
// The idea of this try/finally is to make sure that the statements are always
// executed together (VSWhidbey 319154)
// This code should be using a constrained execution region.
try {
}
finally {
// Always take the BuildManager lock *before* taking the mutex, to avoid possible
// deadlock situations (VSWhidbey 530732)
#pragma warning disable 0618
//@TODO: This overload of Monitor.Enter is obsolete. Please change this to use Monitor.Enter(ref bool), and remove the pragmas -- [....]
Monitor.Enter(BuildManager.TheBuildManager);
#pragma warning restore 0618
_mutex.WaitOne();
gotLock = true;
}
}
internal static void ReleaseLock() {
_mutex.ReleaseMutex();
Monitor.Exit(BuildManager.TheBuildManager);
}
}
}
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Orleans.Runtime
{
/* Example of printout in logs:
StageAnalysis=
Stage: Runtime.IncomingMessageAgent.Application
Measured average CPU per request: 0.067 ms
Measured average Wall-clock per request: 0.068 ms
Measured number of requests: 1777325 requests
Estimated wait time: 0.000 ms
Suggested thread allocation: 2 threads (rounded up from 1.136)
Stage: Scheduler.WorkerPoolThread
Measured average CPU per request: 0.153 ms
Measured average Wall-clock per request: 0.160 ms
Measured number of requests: 4404680 requests
Estimated wait time: 0.000 ms
Suggested thread allocation: 7 threads (rounded up from 6.386)
Stage: Runtime.Messaging.GatewaySender.GatewaySiloSender
Measured average CPU per request: 0.152 ms
Measured average Wall-clock per request: 0.155 ms
Measured number of requests: 92428 requests
Estimated wait time: 0.000 ms
Suggested thread allocation: 1 threads (rounded up from 0.133)
Stage: Runtime.Messaging.SiloMessageSender.AppMsgsSender
Measured average CPU per request: 0.034 ms
Measured average Wall-clock per request: 0.125 ms
Measured number of requests: 1815072 requests
Estimated wait time: 0.089 ms
Suggested thread allocation: 2 threads (rounded up from 1.765)
CPU usage by thread type:
0.415, Untracked
0.359, Scheduler.WorkerPoolThread
0.072, Untracked.ThreadPoolThread
0.064, Runtime.IncomingMessageAgent.Application
0.049, ThreadPoolThread
0.033, Runtime.Messaging.SiloMessageSender.AppMsgsSender
0.008, Runtime.Messaging.GatewaySender.GatewaySiloSender
0.000, Scheduler.WorkerPoolThread.System
0.000, Runtime.Messaging.SiloMessageSender.SystemSender
0.000, Runtime.IncomingMessageAgent.System
0.000, Runtime.Messaging.SiloMessageSender.PingSender
0.000, Runtime.IncomingMessageAgent.Ping
EndStageAnalysis
*/
/// <summary>
/// Stage analysis, one instance should exist in each Silo
/// </summary>
internal class StageAnalysis
{
private readonly double stableReadyTimeProportion;
private readonly Dictionary<string, List<ThreadTrackingStatistic>> stageGroups;
public StageAnalysis()
{
// Load test experiments suggested these parameter values
stableReadyTimeProportion = 0.3;
stageGroups = new Dictionary<string, List<ThreadTrackingStatistic>>();
if (StatisticsCollector.CollectThreadTimeTrackingStats && StatisticsCollector.PerformStageAnalysis)
{
StringValueStatistic.FindOrCreate(StatisticNames.STAGE_ANALYSIS, StageAnalysisInfo);
}
}
public void AddTracking(ThreadTrackingStatistic tts)
{
lock (stageGroups)
{
// we trim all thread numbers from thread name, so allow to group them.
char[] toTrim = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '/', '_', '.' };
string stageName = tts.Name.Trim(toTrim);
List<ThreadTrackingStatistic> stageGroup;
if (!stageGroups.TryGetValue(stageName, out stageGroup))
{
stageGroup = new List<ThreadTrackingStatistic>();
stageGroups.Add(stageName, stageGroup);
}
stageGroup.Add(tts);
}
}
// the interesting stages to print in stage analysis
private static readonly List<string> stages = new List<string>()
{
"Runtime.IncomingMessageAgent.Application",
"Scheduler.WorkerPoolThread",
"Runtime.Messaging.GatewaySender.GatewaySiloSender",
"Runtime.Messaging.SiloMessageSender.AppMsgsSender"
};
// stages where wait time is expected to be nonzero
private static readonly HashSet<string> waitingStages = new HashSet<string>()
{
//stages[1], // if we know there is no waiting in the WorkerPoolThreads, we can remove it from waitingStages and get more accuarte measurements
stages[2],
stages[3]
};
private static readonly string firstStage = stages[0];
private string StageAnalysisInfo()
{
try
{
lock (stageGroups)
{
double cores = Environment.ProcessorCount;
Dictionary<string, double> cpuPerRequest = new Dictionary<string, double>(); // CPU time per request for each stage
Dictionary<string, double> wallClockPerRequest = new Dictionary<string, double>(); // Wallclock time per request for each stage
Dictionary<string, double> numberOfRequests = new Dictionary<string, double>(); // Number of requests for each stage
foreach (var keyVal in stageGroups)
{
string name = keyVal.Key;
if (GetNumberOfRequests(name) > 0)
{
cpuPerRequest.Add(name, GetCpuPerStagePerRequest(name));
wallClockPerRequest.Add(name, GetWallClockPerStagePerRequest(name));
numberOfRequests.Add(name, GetNumberOfRequests(name));
}
}
cpuPerRequest.Add("Untracked.ThreadPoolThread", GetCpuPerStagePerRequest("Untracked.ThreadPoolThread"));
numberOfRequests.Add("Untracked.ThreadPoolThread", GetNumberOfRequests("Untracked.ThreadPoolThread"));
double elapsedWallClock = GetMaxWallClock();
double elapsedCPUClock = GetTotalCPU();
// Idle time estimation
double untrackedProportionTime = 1 - elapsedCPUClock / (cores * elapsedWallClock);
// Ratio of wall clock per cpu time calculation
double sum = 0;
double num = 0;
foreach (var stage in wallClockPerRequest.Keys)
{
if (!waitingStages.Contains(stage))
{
double ratio = wallClockPerRequest[stage] / cpuPerRequest[stage] - 1;
sum += ratio * numberOfRequests[stage];
num += numberOfRequests[stage];
}
}
double avgRatio = sum / num;
// Wait time estimation - implementation of strategy 2 from the "local-throughput.pdf" "Coping with Practical Measurements".
var waitTimes = new Dictionary<string, double>(); // Wait time per request for each stage
foreach (var stage in wallClockPerRequest.Keys)
{
waitTimes.Add(stage,
waitingStages.Contains(stage)
? Math.Max(wallClockPerRequest[stage] - avgRatio*cpuPerRequest[stage] - cpuPerRequest[stage], 0)
: 0);
}
// CPU sum for denominator of final equation
double cpuSum = 0;
foreach (var stage in cpuPerRequest.Keys)
{
cpuSum += cpuPerRequest[stage] * numberOfRequests[stage];
}
// beta and lambda values
var beta = new Dictionary<string, double>();
var s = new Dictionary<string, double>();
var lambda = new Dictionary<string, double>();
foreach (var stage in wallClockPerRequest.Keys)
{
beta.Add(stage, cpuPerRequest[stage] / (cpuPerRequest[stage] + waitTimes[stage]));
s.Add(stage, 1000.0 / (cpuPerRequest[stage] + waitTimes[stage]));
lambda.Add(stage, 1000.0 * numberOfRequests[stage] / elapsedWallClock);
}
// Final equation thread allocation - implementation of theorem 2 from the "local-throughput.pdf" "Incorporating Ready Time".
var throughputThreadAllocation = new Dictionary<string, double>(); // Thread allocation suggestion for each stage
foreach (var stage in wallClockPerRequest.Keys)
{
// cores is p
// numberOfRequests is q
// cpuPerRequest is x
// stableReadyTimeProportion is alpha
// waitTimes is w
throughputThreadAllocation.Add(stage, cores * numberOfRequests[stage] * (cpuPerRequest[stage] * (1 + stableReadyTimeProportion) + waitTimes[stage]) / cpuSum);
}
double sum1 = 0;
foreach (var stage in s.Keys)
sum1 += lambda[stage]*beta[stage]/s[stage];
double sum2 = 0;
foreach (var stage in s.Keys)
sum2 += Math.Sqrt(lambda[stage]*beta[stage]/s[stage]);
var latencyThreadAllocation = new Dictionary<string, double>(); // Latency thread allocation suggestion for each stage
foreach (var stage in wallClockPerRequest.Keys)
latencyThreadAllocation.Add(stage, lambda[stage]/s[stage] + Math.Sqrt(lambda[stage])*(cores - sum1)/(Math.Sqrt(s[stage]*beta[stage])*sum2));
var latencyPenalizedThreadAllocationConst = new Dictionary<string, double>();
var latencyPenalizedThreadAllocationCoef = new Dictionary<string, double>();
foreach (var stage in wallClockPerRequest.Keys)
{
latencyPenalizedThreadAllocationConst.Add(stage, lambda[stage] / s[stage]);
latencyPenalizedThreadAllocationCoef.Add(stage, Math.Sqrt(lambda[stage] / (lambda[firstStage] * s[stage])));
}
double sum3 = 0;
foreach (var stage in s.Keys)
sum3 += beta[stage]*Math.Sqrt(lambda[stage]/s[stage]);
double zeta = Math.Pow(sum3 / (cores - sum1), 2) / lambda[firstStage];
var sb = new StringBuilder();
sb.AppendLine();
sb.AppendLine();
sb.AppendLine("zeta: " + zeta);
sb.AppendLine();
foreach (var stage in stages.Intersect(wallClockPerRequest.Keys))
{
sb.AppendLine("Stage: " + stage);
sb.AppendLine(" Measured average CPU per request: " + cpuPerRequest[stage].ToString("F3") + " ms");
sb.AppendLine(" Measured average Wall-clock per request: " + wallClockPerRequest[stage].ToString("F3") + " ms");
sb.AppendLine(" Measured number of requests: " + numberOfRequests[stage].ToString("F0") + " requests");
sb.AppendLine(" lambda: " + lambda[stage].ToString("F3") + " arrival rate requests/sec");
sb.AppendLine(" s: " + s[stage].ToString("F3") + " per thread service rate requests/sec");
sb.AppendLine(" beta: " + beta[stage].ToString("F3") + " per thread CPU usage");
sb.AppendLine(" Estimated wait time: " + waitTimes[stage].ToString("F3") + " ms");
sb.AppendLine(" Throughput thread allocation: " + Math.Ceiling(throughputThreadAllocation[stage]) + " threads (rounded up from " + throughputThreadAllocation[stage].ToString("F3") + ")");
sb.AppendLine(" Latency thread allocation: " + Math.Ceiling(latencyThreadAllocation[stage]) + " threads (rounded up from " + latencyThreadAllocation[stage].ToString("F3") + ")");
sb.AppendLine(" Regularlized latency thread allocation: " + latencyPenalizedThreadAllocationConst[stage].ToString("F3") + " + " + latencyPenalizedThreadAllocationCoef[stage].ToString("F3") + " / sqrt(eta) threads (rounded this value up)");
}
var cpuBreakdown = new Dictionary<string, double>();
foreach (var stage in cpuPerRequest.Keys)
{
double val = (numberOfRequests[stage] * cpuPerRequest[stage]) / (cores * elapsedWallClock);
cpuBreakdown.Add(stage == "ThreadPoolThread" ? "ThreadPoolThread.AsynchronousReceive" : stage, val);
}
cpuBreakdown.Add("Untracked", untrackedProportionTime);
sb.AppendLine();
sb.AppendLine("CPU usage by thread type:");
foreach (var v in cpuBreakdown.OrderBy(key => (-1*key.Value)))
sb.AppendLine(" " + v.Value.ToString("F3") + ", " + v.Key);
sb.AppendLine();
sb.Append("EndStageAnalysis");
return sb.ToString();
}
}
catch (Exception e)
{
return e + Environment.NewLine + e.StackTrace;
}
}
/// <summary>
/// get all cpu used by all types of threads
/// </summary>
/// <returns> milliseconds of total cpu time </returns>
private double GetTotalCPU()
{
double total = 0;
foreach (var keyVal in stageGroups)
foreach (var statistics in keyVal.Value)
total += statistics.ExecutingCpuCycleTime.Elapsed.TotalMilliseconds;
return total;
}
/// <summary>
/// gets total wallclock which is the wallclock of the stage with maximum wallclock time
/// </summary>
private double GetMaxWallClock()
{
double maxTime = 0;
foreach (var keyVal in stageGroups)
foreach (var statistics in keyVal.Value)
maxTime = Math.Max(maxTime, statistics.ExecutingWallClockTime.Elapsed.TotalMilliseconds);
maxTime -= 60 * 1000; // warmup time for grains needs to be subtracted
return maxTime;
}
/// <summary>
/// get number of requests for a stage
/// </summary>
/// <param name="stageName">name of a stage from thread tracking statistics</param>
/// <returns>number of requests</returns>
private double GetNumberOfRequests(string stageName)
{
if (stageName == "Untracked.ThreadPoolThread")
return 1;
double num = 0;
if (!stageGroups.ContainsKey(stageName))
return 0;
foreach (var tts in stageGroups[stageName])
num += tts.NumRequests;
return num;
}
/// <summary>
/// get wall clock time for a request of a stage
/// </summary>
/// <param name="stageName">name of a stage from thread tracking statistics</param>
/// <returns>average milliseconds of wallclock time per request</returns>
private double GetWallClockPerStagePerRequest(string stageName)
{
double sum = 0;
if (!stageGroups.ContainsKey(stageName))
return 0;
foreach (var statistics in stageGroups[stageName])
if (stageName == "ThreadPoolThread")
{
sum += statistics.ProcessingWallClockTime.Elapsed.TotalMilliseconds;
}
else
{
sum += statistics.ProcessingWallClockTime.Elapsed.TotalMilliseconds;
// We need to add the pure Take time, since in the GetCpuPerStagePerRequest we includes both processingCPUCycleTime and the Take time.
TimeSpan takeCPUCycles = statistics.ExecutingCpuCycleTime.Elapsed -
statistics.ProcessingCpuCycleTime.Elapsed;
sum += takeCPUCycles.TotalMilliseconds;
}
return sum / GetNumberOfRequests(stageName);
}
/// <summary>
/// get cpu time for a request of a stage
/// </summary>
/// <param name="stageName">name of a stage from thread tracking statistics</param>
/// <returns>average milliseconds of cpu time per request</returns>
private double GetCpuPerStagePerRequest(string stageName)
{
double sum = 0;
if (stageName == "Untracked.ThreadPoolThread")
{
foreach (var statistics in stageGroups["ThreadPoolThread"])
{
sum += statistics.ExecutingCpuCycleTime.Elapsed.TotalMilliseconds;
sum -= statistics.ProcessingCpuCycleTime.Elapsed.TotalMilliseconds;
}
return sum;
}
if (!stageGroups.ContainsKey(stageName))
return 0;
foreach (var statistics in stageGroups[stageName])
{
if (stageName == "ThreadPoolThread")
{
sum += statistics.ProcessingCpuCycleTime.Elapsed.TotalMilliseconds;
}
else
{
// this includes both processingCPUCycleTime and the Take time.
sum += statistics.ExecutingCpuCycleTime.Elapsed.TotalMilliseconds;
}
}
return sum / GetNumberOfRequests(stageName);
}
}
}
|